Why Http status code 404 shows when I click on submit using war file deployed - spring-boot

Image 1. Successful GET request
Image 2. Failed POST when click on submit
Welcome page i.e. index.jsp aprears on localhost:8080/war_filename
but when we click on login in index page it shows http status code 404
Is anyone there, who's having the same issue?
I've copied the war file in apache\webapps
WebController.java
#Controller
public class indexController {
String errorMessage = "Invalid credentials";
#GetMapping("/login")
public String login() {
return "index.jsp";
}
/*********** Login using form ************/
#RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(#RequestParam("firstname") String firstName,
#RequestParam("lastname") String lastName) {
System.out.println("inside login form");
Customer object = repository.findByFirstNameAndLastName(firstName,
lastName);
if (object != null) {
return "home.jsp";
}
return "index.jsp";
}
}
index.jsp
<h3>Do Login Here</h3>
<form method="POST" action="/login">
<table>
<tr>
<td>Employee ID</td>
<td><input type="text" name="firstname" placeholder="Username" required></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="lastname" placeholder="Password" required></td>
</tr>
<tr>
<td><input type="submit" value="Login" /></td>
</tr>
</table>
</form>
home.jsp
<body>
<h3>Operations</h3>
<form action="/selectusingform" method="get">
Select
</form>
<table>
<tr>
<td>Insert</td>
</tr>
<tr>
<td>Update</td>
</tr>
<tr>
<td>Delete</td>
</tr>
<tr>
<td>Find</td>
</tr>
</table>

Related

ModelAndView Spring

Details:
I am testing my first spring project , I am unable to get form data in backing bean . Here my code please help me execute this.
Welcome.jsp is my landing page from here I want to take userid and password and show in userInfo page.
Controller :--
package com.accounts.common.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.accounts.common.backingBean.LoginBackingBean;
/**
* Handles requests for the application welcome page.
*/
#Controller
public class WelcomeController {
/**
* Simply selects the welcome view to render by returning void and relying
* on the default request-to-view-translator.
*/
#RequestMapping(value= "/welcome" ,method = RequestMethod.GET)
**public ModelAndView welcome() {
return new ModelAndView("welcome", "userForm", new LoginBackingBean());
}**
#RequestMapping(value="/userInfo" ,method = RequestMethod.POST)
public String userInfo(#ModelAttribute("userForm")LoginBackingBean login ,
ModelMap model){
model.addAttribute("userId" , login.getUserId());
model.addAttribute("password" , login.getPassword());
return "userInfo";
}
}
Here is code for Welcome JSP :-- Only snapshot I am adding
<body>
<form id=login method="POST" action="/AccountingSW/userInfo" >
<div align="center">
<table>
<tr>
<td>User ID : </td>
<td> <input type="text"> </td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password"> </td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value ="Login">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<label style="font-size: 10;color: red">Already existing Member</label>
</td>
</tr>
<tr><td colspan="2" align="center">OR</td></tr>
<tr><td colspan="2" align="center">
<input type="submit" value ="SignUp"></td></tr>
<tr>
<td colspan="2" align="center">
<label style="font-size: 10;color: red">New Member</label>
</td>
</tr>
</table>
</div>
</form >
</body>
</html>
Here is code for UserInfo JSP :
I am putting only snapshot of what the jsp contains
<title>Hello ${userForm.userId}</title>
</head>
<body>
<h2>User Info</h2>
<table>
<tr>
<td>UserId</td>
<td>${userForm.userId}</td>
</tr>
<tr>
<td>Password</td>
<td>${userForm.password}</td>
</tr>
</table>
</body>
</html>
Here is code for Backing Bean :--
package com.accounts.common.backingBean;
public class LoginBackingBean {
private String userId;
private String password;
/* Getter and setters generated */
}
I am able to execute the jsp(s) but the userId and Password is not getting set
Please try to change from
public String userInfo(#ModelAttribute("userForm")LoginBackingBean login
to
public String userInfo(#ModelAttribute("loginBackingBean")LoginBackingBean login
as #ModelAttribute's document
The default model attribute name is inferred from the declared
attribute type (i.e. the method parameter type or method return type),
based on the non-qualified class name: e.g. "orderAddress" for class
"mypackage.OrderAddress", or "orderAddressList" for
"List".
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/ModelAttribute.html#name--
In your welcome.jsp you are missing property name on inputs:
<td> <input type="text" name ="userId"> </td>
<td><input type="password" name="password"> </td>

Spring: get input button id

I have this html template in thymeleaf.
<table id="listAllAccountantTable" th:cellspacing="0" class="table table-striped table-bordered" style="width:100%;">
<thead>
<tr>
<th>No. </th>
<th>Registered Date</th>
<th>Status</th>
<th>Name</th>
<th>Email</th>
<th>Contact No.</th>
<th>IC No.</th>
<th>IC attachment</th>
<th>Actions </th>
</tr>
<tr th:each="acc,iterationStatus : ${accountantListing}">
<td th:text="${iterationStatus.count}">1</td>
<td th:text="${acc.currentTimeStamp}"></td>
<td th:text="${acc.active}">1</td>
<td th:text="${acc.name}">Name</td>
<td th:text="${acc.email}">Email</td>
<td th:text="${acc.phoneNumber}">Contact No.</td>
<td th:text="${acc.icNumber}">IC No.</td>
<td th:text="${acc.id}"> To be fixed: upload IC image</td>
<td>
<form action="#" data-th-action="#{/accountantApplication}" method="post">
<button type="submit" name="action" th:id="${acc.id}"
value="Accept">Accept</button>
<button type="submit" name="action" th:id="${acc.id}"
value="Reject">Reject</button>
</form>
</td>
</tr>
My Spring controller is:
#RequestMapping(value="/accountantApplication", method=RequestMethod.POST, params="action=Accept")
public ModelAndView Accept() {
ModelAndView modelAndView = new ModelAndView();
System.out.println("######## Accepting accountant");
modelAndView.setViewName("AccountantListing");
return modelAndView;
}
#RequestMapping(value="/accountantApplication", method=RequestMethod.POST, params="action=Reject")
public ModelAndView Reject() {
ModelAndView modelAndView = new ModelAndView();
System.out.println("######## Rejecting accountant");
modelAndView.setViewName("AccountantListing");
return modelAndView;
}
The table shows a list of accountants.
All accountants are loaded from db and displayed on the table.
They need to be accepted or rejected.
When I click the accept button, Accept() is called.
How do I get the ID attached to button?
Or if there is better way of immplementing this. let me know too. Thanks so much
In your form, you should have a hidden input:
<form action="#" data-th-action="#{/accountantApplication}" method="post">
<input type="hidden" name="id" th:value="${acc.id}" />
<button type="submit" name="action" value="Accept">Accept</button>
<button type="submit" name="action" value="Reject">Reject</button>
</form>
Then, in your controllers:
public ModelAndView accept(#RequestParam String id) {
.
.
.
}
public ModelAndView Reject(#RequestParam String id) {
.
.
.
}
Also, as a side note, you can replace:
#RequestMapping(value="/accountantApplication", method=RequestMethod.POST, params="action=Accept")
#RequestMapping(value="/accountantApplication", method=RequestMethod.POST, params="action=Reject")
with
#PostMapping(value="/accountantApplication", params="action=Accept")
#PostMapping(value="/accountantApplication", params="action=Reject")

Logout with Spring Security with Java configuration

I am using Spring Security 4.0.2.RELEASE with Spring 4.2.0.RELEASE.
I am unable to create a logout link (I maen what must be the value of the href attribute).
Consider :
Configuring DelegatingFilterProxy in Java with WebApplicationInitializer:
public class SecurityWebInitializer
extends AbstractSecurityWebApplicationInitializer {
}
Simple configuration class to enable web security for Spring MVC
#Configuration
#EnableWebSecurity
public class SecurityConfig
extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin().and()
.authorizeRequests()
.antMatchers("/spitter/").authenticated()
.antMatchers(HttpMethod.GET, "/spitter/register").authenticated().and()
.logout().deleteCookies("remove")
.invalidateHttpSession(true).logoutUrl("/logout")
.logoutSuccessUrl("/");
}
#Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password")
.roles("USER").and().withUser("admin").password("password")
.roles("USER", "ADMIN");
}
}
Controller:
#Controller
#RequestMapping(value = "/spitter")
public class SpittrController {
private SpittleRepository spittleRepository;
#Autowired
public SpittrController(SpittleRepository spittleRepository) {
this.spittleRepository = spittleRepository;
}
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String showRegistrationForm() {
return "registerForm";
}
#RequestMapping(value = "/register", method = RequestMethod.POST)
public String processingRegistration(#Valid Spitter spitter, Errors errors) {
if (errors.hasErrors()) {
return "registerForm";
}
spittleRepository.save(spitter);
return "redirect:/spitter/" + spitter.getUserName();
}
#RequestMapping(value = "/{username}", method = RequestMethod.GET)
public String showSpitterProfile(#PathVariable("username") String username,
Model model) {
Spitter spitter = spittleRepository.findByUsername(username);
if(spitter != null){
model.addAttribute(spitter);
}
return "profile";
}
}
registerForm.jsp:
<form method="post">
<table>
<tr>
<td>First Name:</td>
<td><input type="text" name="firstName" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="lastName" /></td>
</tr>
<tr>
<td>User Name:</td>
<td><input type="text" name="userName" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td><input type="submit" value="Register" /></td>
</tr>
</table>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}">
</form>
After submission of registerForm.jsp, the profile.jsp is shown to the user:
profile.jsp:
<body>
<h1>Hello world!</h1>
<p>The time on the server is ${serverTime}.</p>
<h1>Your Profile</h1>
<h1>Logout</h1>
<table>
<tr>
<td>First Name:</td>
<td><c:out value="${spitter.firstName}" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><c:out value="${spitter.lastName}" /></td>
</tr>
<tr>
<td>User Name:</td>
<td><c:out value="${spitter.userName}" /></td>
</tr>
</table>
</body>
When I hit
http://localhost:8080/web/spitter/register
I am redirected to the login page. After login and submitting the form, the profile.jsp is shown in which I have included a Logout link. On clicking that, HTTP 404 comes up.
I have gone through Spring Security docs, but they have taken thymeleaf into consideration. My is a simple JSP page.
Furthermore, I have also considered taking this into account,
By default POST request is required to the logout url. To perform
logout on GET request you need:
http
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"));
1:
http://docs.spring.io/spring-security/site/docs/3.2.x/guides/hellomvc.html
Any suggestions?
Update the your code in profile.jsp as
<h1>logout</h1>
<c:url var="logoutUrl" value="/logout" />
<form action="${logoutUrl}" method="post" id="logoutForm">
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
</form>

How to know from which jsp page the request has come to the controller in Spring MVC

I am developing an app where LoginForm.jsp and UserRegistration.jsp will lead to UserAccount jsp page on specific action.In LoginForm when a user presses a 'Login' button ->UserAccount form is displayed.In UserRegistration Form when details are entered and submitted ->UserAccount form is displayed.
Below is the controller code when a request comes as UserAccount.html
#RequestMapping(value="/UserAccount.html", method = RequestMethod.POST)
public ModelAndView userAccountForm(#Valid #ModelAttribute("user") UserDetails user,BindingResult result) {
if(result.hasErrors())
{ System.out.println(result.getAllErrors());
ModelAndView model1=new ModelAndView("UserRegistration");
return model1;
}
// User validation
System.out.println(user.getAccountType());
userDAO.create(user);
ModelAndView model1 = new ModelAndView("UserAccount");
return model1;
}
LoginForm.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<body>
<h1
style="background-color: green; color: Yellow; padding: 10px; text-align: center;">Mybank
Online Login</h1>
<form:errors path="user.*" />
<form action="/MyBankProject/UserAccount.html" method="post">
<div
style="background-color: yellow; color: black; padding: 10px; text-align: center;"
align="center">
<p>
User ID <input type="text" name="userName" />
</p>
<p>
Password <input type="password" name="password" />
</p>
<input type="submit" value="Login" /> New User?
</div>
<input type="hidden" name="page" value="LoginForm"/>
</form>
</body>
</html>
UserRegistration.jsp
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<body>
<h1>${headerMessage}</h1>
<h3>USER REGISTRATION</h3>
<form:errors path="user.*" />
<form action="/MyBankProject/UserAccount.html" method="post">
<table border="1" style="width:100%" >
<tr>
<td>FirstName :</td>
<td><input type="text" name="firstName" /></td>
</tr>
<tr>
<td>LastName :</td>
<td><input type="text" name="lastName" /></td>
</tr>
<tr>
<td>User's EmailId :</td>
<td><input type="text" name="emailId" /></td>
</tr>
<tr>
<td>user's gender :</td>
<td><select name="gender" multiple>
<option value="M">Male</option>
<option value="F">Female</option>
</select></td>
</tr>
<tr>
<td>user's age :</td>
<td><input type="text" name="age" /></td>
</tr>
<tr>
<td>user's DOB :</td>
<td><input type="text" name="dOB" /></td>
</tr>
<tr>
<td>Account Type :</td>
<td><select name="accountType" multiple>
<option value="Savings">Savings</option>
<option value="Current">Current</option>
<option value="FixedDeposit">Fixed Deposit</option>
</select>
<td>
</tr>
<tr>
<td>Amount :</td>
<td><input type="text" name="amount" /></td>
</tr>
</table>
<table>
<tr>
<td>UserName</td>
<td><input type="text" name="userName" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
</table>
<table>
<tr>
<td>User's Address :</td>
</tr>
<tr>
<td>country: <input type="text" name="address.country" /></td>
<td>city: <input type="text" name="address.city" /></td>
<td>street: <input type="text" name="address.street" /></td>
<td>pincode:<input type="text" name="address.pincode" /></td>
</tr>
<tr>
<td><button type="submit">Submit</button></td>
<td><input type="button" onclick="history.back();"
value="Cancel"></td>
</tr>
</table>
<input type="hidden" name="page" value="UserRegistration"/>
</form>
</body>
</html>
Now for me I need to know the jsp page from which the UserAccount invoked ,to perform different actions based on that.
I am new to Spring MVC and searched all over the internet for the solution.
HTTP is a stateless protocol. This means that you can not make assumptions about previous states.
I think you have two options to get information about the previous page anyways.
Add a hidden field to your form and send the name of the page with the request.
HTML:
<form>
<input type="hidden" name="page" value="[the name of the current page]"/>
</form>
Controller:
#RequestMapping(value="/UserAccount.html", method = RequestMethod.POST)
public ModelAndView userAccountForm(#RequestParam(value="page", required=false) String page) {
[...]
}
Now you can check the page value.
Use the session. Store the current page in the controller methods that render the form:
#RequestMapping("/login")
public String login(HttpServletRequest request) {
request.getSession().setAttribute("lastPage", "login");
return "redirect:/UserAccount.html";
}
#RequestMapping("/register")
public String register(HttpServletRequest request) {
request.getSession().setAttribute("lastPage", "register");
return "redirect:/UserAccount.html";
}
Check the lastPage value in userAccountForm():
#RequestMapping(value="/UserAccount.html", method = RequestMethod.POST)
public ModelAndView userAccountForm(HttpServletRequest request) {
HttpSession session = request.getSession();
String lastPage = (String) session.getAttribute("lastPage");
session.removeAttribute("lastPage");
[...]
}
Check the referer field of the request header.
#RequestMapping(value="/UserAccount.html", method = RequestMethod.POST)
public ModelAndView userAccountForm(#RequestHeader(value = "referer", required = false) String referer) {
[...]
}
This gives you the referer as a method argument if there is one. Be careful. It is possible that there was no referer or that the field was manipulated by the client.
Hope this will solve your need.
URL url = new URL(request.getHeader("referer"));
System.out.println("last page url"+ url.getPath());
if(url.getPath().equals("your last url"){
//code
}

How are Spring MVC Controllers being bound to JSP pages?

Hi I am new to spring and I am trying to develop a simple portlet that accepts users first and last name and saves it to db using hibernate.
Basically I cannot figure out how the jsps and controllers communicate; I am missing some chunk here.
This is my first controller that needs to be called (where do I mention so?)
package codes.controller;
import javax.portlet.RenderResponse;
import codes.base.User;
import codes.service.UserService;
#Controller(value="SimpleUserController")
#RequestMapping(value = "VIEW")
public class SimpleUserController {
// -- auto-wiring of service dependency
#Autowired
#Qualifier("userService")
private UserService userService;
// --maps the incoming portlet request to this method
#RenderMapping
public String showUsers(RenderResponse response) {
return "home";
}
#ExceptionHandler({ Exception.class })
public String handleException() {
return "errorPage";
}
// -- #ModelAttribute here works as the referenceData method
#ModelAttribute(value="user")
public User getCommandObject() {
return new User();
}
}
Initially I am displaying a home.jsp that will display the form with two input boxes and a submit button.
<%#include file="include.jsp" %>
<portlet:actionURL var="addUserActionUrl">
<portlet:param name="myaction" value="addUser" />
</portlet:actionURL>
<form:form name="home" commandName="user" method="post"
action="${addUserActionUrl}">
<table>
<tr>
<td>First Name:<font style="color: #C11B17;">*</font></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td>Last Name:<font style="color: #C11B17;">*</font></td>
<td><form:input path="lastname" /></td>
</tr>
<table align="right">
<tr>
<td> </td>
<td><input type="submit" value="SUBMIT" /></td>
</tr>
</table>
</table>
</form:form>
This JSP should call the action method in the AddUserController.java:
package codes.controller;
import javax.portlet.ActionResponse;
import javax.portlet.RenderResponse;
import codes.base.User;
import codes.service.UserService;
#Controller(value = "AddUserController")
#RequestMapping(value = "VIEW")
public class AddUserController {
#Autowired
#Qualifier("userService")
private UserService userService;
#RenderMapping(params = "myaction=addUser")
public String showRegisterPage(Model model) {
model.addAttribute("user", new User());
model.addAttribute("users", getUsers());
return "addUser";
}
public List<User> getUsers() {
return userService.getAllUsers();
}
#ActionMapping(params = "myaction=addUser")
public void addBook(#ModelAttribute(value = "user") User user,
BindingResult bindingResult, ActionResponse response,
SessionStatus sessionStatus) {
if (!bindingResult.hasErrors()) {
userService.addUser(user);
response.setRenderParameter("myaction", "users");
sessionStatus.setComplete();
} else {
response.setRenderParameter("myaction", "addUser");
}
}
}
This time this firstname+last name should be saved in the db AND the screen should refresh to show a new form that will have a dropdown with the current users' names in the database and another first name and last name form fields. If you select a username from the dropdown the form fields are populated and you can edit these values and click on UPdate button to save the values in DB. Otherwise you can add a new user to the database using submit button.
addUser.jsp:
<%#include file="include.jsp" %>
<portlet:actionURL var="addUserActionUrl">
<portlet:param name="myaction" value="addUser" />
</portlet:actionURL>
<portlet:renderURL var="homeUrl">
<portlet:param name="myaction" value="Users" />
</portlet:renderURL>
<script type="text/javascript" src="js/userRelated.js"></script>
<form:form name="addUser" commandName="user" method="post"
action="${addUserActionUrl}">
<form:select path="model">
<form:option value="NONE" label="--- Select ---" id="userList" onchange="showHide()"/>
<form:options items="${users}" />
</form:select>
<table>
<tr>
<td>First Name:<font style="color: #C11B17;">*</font></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td>Last Name:<font style="color: #C11B17;">*</font></td>
<td><form:input path="lastname" /></td>
</tr>
<table align="right">
<tr>
<td> </td>
<td><input type="submit" id="submit" value="SUBMIT" />SUBMIT</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" id="update" value="SUBMIT" />UPDATE</td>
</tr>
</table>
</table>
</form:form>
I am hiding and unhiding the SUBMIT/UPDATE button using onchange of dropdown. How do I call different functions in the addUsercontroller depending on the button available?
by updating the action attribute of form element with javascript

Resources