Showing error message on JSP using BindingResult - java

I am new to Spring.
I am trying to show error messages on jsp for the wrong user and password by using BindingResult. But the error messages are not showing.
Please suggest me what I is wrong in the below code.
JSP
<script type="text/javascript">
function loginUser() {
$('#loginForm').submit();
}
</script>
</head>
<body>
<form:form action="login.test" id="loginForm" commandName="loginForm" method="POST">
<div class="brand_area"></div>
<div class="content_area">
<table style="top: 360px; position: relative; margin-left: 333px;">
<tr id="uNameID">
<td class="label">User Name:</td>
<td><form:input id="userNameID" path="userName" class="textInput" /></td>
<td><form:errors path="userName" class="error"/></td>
</tr>
<tr id="pID">
<td class="label">Password:</td>
<td><form:password id="passwordID" path="password" class="textInput" /></td>
<td><form:errors path="password" class="error"/></td>
</tr>
<tr>
<td></td>
<td><span id="saveButton" class="loginButton"
onclick="loginUser()"> <span>Login</span>
</span></td>
</tr>
</table>
</div>
</form:form>
Controller
#RequestMapping(value = "login.test", method = RequestMethod.POST)
public String processForm( LoginForm loginForm, BindingResult result, ModelMap model, HttpSession session) throws SQLException {
String resultedPage;
model.addAttribute("l_nodes", reportService.getAllLiveNodes());
model.addAttribute("s_nodes", reportService.getAllStaticReportNodes());
User user = userService.getUserByName( loginForm.getUserName() );
if( user != null ){
session.setAttribute("userID", user.getUserID());
if( loginForm.getPassword().equals( user.getPassword() ) ){
resultedPage = "home/userHome";
}else{
result.rejectValue( "password", "login.passwordNotValid");
resultedPage = "redirect:login.test";
}
}else{
result.rejectValue( "userName", "login.userNotValid");
resultedPage = "redirect:login.test";
}
return resultedPage;
}
Thanks

In case anyone else research the same...
Add the hasBindErrors tag to your JSP:
<spring:hasBindErrors name="loginForm">
<c:forEach var="error" items="${errors.allErrors}">
<b><spring:message message="${error}" /></b>
<br/>
</c:forEach>
</spring:hasBindErrors>

Well, i generally send back the values using the Model object.
May be this answer might help you.

Related

spring web application - html button - post method outside form - 404 ERROR

I`m trying to send post request from JSP view to Controller by Button "onClick" method but i getting 404 Error that the RequestMapping is not sign, why is that?
HomeController:
#RequestMapping(value = "/showSelectedRequest/{id}", method = RequestMethod.POST)
public String loadRequestProducts(#PathVariable("id") int id, Model model) {
logger.debug("HomeController.RequestIdSelected() - Start");
logger.debug("HomeController.RequestIdSelected: id: " + id);
model.addAttribute("RequestIdSelected", id);
logger.debug("HomeController.RequestIdSelected() - Done");
return "/home";
}
Home.jsp:
<form action="${contextPath}/requestlist" method="post">
<table class="table table-sm">
<thead class="thead-inverse">
<tr>
<th>
Id
</th>
<th>
Name
</th>
<th>
Show request
</th>
</tr>
</thead>
<c:forEach items="${requestDTOList}" var="requestDTO">
<tr>
<td>
${requestDTO.getId()}
</td>
<td>
${requestDTO.getName()}
</td>
<td>
<button class="btn btn-info" onclick="post(/showSelectedRequest/${requestDTO.getId()})">Query</button>
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
</td>
</tr>
</c:forEach>
</table>
</form>
When you have a form, the action field is what will be executed when you will click on the input of type "submit".
As a solution you can modify your code as follow:
<form action="${contextPath}/showSelectedRequest/${requestDTO.getId()}" method="post">
// Form elements ...
<input type="submit" value="Query" />
</form>

Receive parameters from Thymleaf page

I have tried to send a parameter from this thymleaf page
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Email</th>
<th>Send Invoice</th>
</tr>
</thead>
<tbody>
<tr class="table-row" th:each="p : ${POList}">
<td th:text="${p.email}"></td>
<td>
<form style='float:left; padding:5px; height:0px' th:object="${p}" th:method="post" th:action="#{/dashboard/makeAndSendInvoice/{email}(email=${p.email})}">
<button class="btn btn-default btn-xs" type="submit">Send Invoice</button>
</form>
</td>
</tr>
</tbody>
and then I tried to receive the parameter (email) using this code
#RequestMapping(method=POST, path="/makeAndSendInvoice/{email}")
public void makeAndSendInvoice(#PathVariable("email") String email) throws Exception {
System.out.println("Invoice is sent to..................."+email);
}
The problem is when the value of p.email is something like myemail#gmail.com
what I receive in the method makeAndSendInvoice is only myemail#gmail
and it does not send me the .com part
How can I fix it?
(email=${p.email}) means , you are passing a query parameter.
So, how can you be able to catch the query param value using path variable?
We can use #RequestParam to catch the queryparam value in Spring
Try the below java code :
#RequestMapping(method=POST, path="/makeAndSendInvoice/{email}")
public void makeAndSendInvoice(#RequestParam("email") String email) throws Exception {
System.out.println("Invoice is sent to..................."+email);
}
The period in ".com" will need to be encoded to be used in the url to prevent it being parsed as the suffix
Your HTML:
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Email</th>
<th>Send Invoice</th>
</tr>
</thead>
<tbody>
<tr class="table-row" th:each="p : ${POList}">
<td th:text="${p.email}"></td>
<td>
<form method="post" th:action="#{/dashboard/makeAndSendInvoice/__${p.email}__} ">
<button class="btn btn-default btn-xs" type="submit">Send Invoice</button>
</form>
</td>
</tr>
</tbody>
Your controller
#RequestMapping(value = "/dashboard")
#Controller
public class testController {
...
#RequestMapping(value = "/makeAndSendInvoice/{email}", method = RequestMethod.POST)
public ModelAndView makeAndSendInvoice(#PathVariable String email, ModelAndView mav) {
return mav; // <- Break point, debug !!
}
}

After submitting a form go back to previous page (Spring/Hibernate)

I have a restaurant edit page located "/restaurant/edit/{id}". From that page I can (among other things) add tables to the restaurant by pressing an "Add tables" button. That button takes me to another page located "/restaurant/edit/{id}/table". The question is, after I have added the table - how do I get back to the previous page by pressing a button? Right now my contoller is returning "editRestaurant.jsp" which is the right value, but I don't know how to pass that same restaurant id as well. I hope you understand what I mean.
My RestaurantTableController.java:
#Controller
public class RestaurantTableController {
#Autowired
private RestaurantService restaurantService;
#Autowired
private RestaurantTableService restaurantTableService;
#RequestMapping(value="restaurant/{id}/table", method = RequestMethod.GET)
public String addRestaurantTable(Model model, #PathVariable Long id) {
model.addAttribute("table", new RestaurantTable());
return "newTable";
}
#RequestMapping(value = "restaurant/{id}/table", method = RequestMethod.POST)
public String addRestaurantTableAction(#PathVariable Long id, #ModelAttribute ("table") RestaurantTable table, BindingResult result) {
RestaurantTableFormValidator restaurantTableFormValidator = new RestaurantTableFormValidator();
restaurantTableFormValidator.validate(table, result);
if (result.hasErrors()) {
return "newTable";
}
restaurantService.mergeRestaurant(id, table);
return "editRestaurant";
}
}
My "newTable.jsp":
<body>
<jsp:include page="../fragments/menu.jsp"/>
<div id="body">
<section class="content-wrapper main-content clear-fix">
<h2>Add New Table</h2>
<form:form method="POST" modelAttribute="table">
<table>
<tr>
<td>Table size:</td>
<td><form:input path="tableSize" /></td>
<td><form:errors path="tableSize" cssClass="error"/></td>
</tr>
<tr>
<td>Table number:</td>
<td><form:input path="tableNumber" /></td>
<td><form:errors path="tableNumber" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit" onclick="goback()"/>
</td>
</tr>
</table>
</form:form>
</section>
</div>
<jsp:include page="../fragments/footer.jsp"/>
</body>
Relevant methods in RestaurantController.java:
#RequestMapping(value = "restaurant/edit/{id}", method = RequestMethod.GET)
public String editRestaurant(#PathVariable Long id, Model model) {
Restaurant restaurant = restaurantService.getRestaurant(id);
model.addAttribute("restaurant", restaurant);
return "editRestaurant";
}
#RequestMapping(value = "restaurant/edit/{id}", method = RequestMethod.POST, params="submit")
public String editRestaurant(#ModelAttribute ("restaurant") Restaurant restaurant, BindingResult result) {
RestaurantFormValidator restaurantFormValidator = new RestaurantFormValidator();
restaurantFormValidator.validate(restaurant, result);
if (result.hasErrors()) {
return "editRestaurant";
}
restaurantService.updateRestaurant(restaurant);
return "redirect:/bookings";
}
"editRestaurant.jsp":
<div id="body">
<section class="content-wrapper main-content clear-fix">
<h2>Edit</h2>
<form:form method="POST" modelAttribute="restaurant" >
<table>
<tr>
<td>Restaurant:</td>
<td><form:input path="restaurantName" /></td>
<td><form:errors path="restaurantName" cssClass="error"/></td>
</tr>
<tr>
<td>Address:</td>
<td><form:input path="address" /></td>
<td><form:errors path="address" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Submit" name="submit"/>
</td>
</tr>
<tr>
<c:forEach items="${restaurant.table}" var="item">
<td>${item.toString()}</td>
</c:forEach>
</tr>
<tr>
<td>Add Table</td>
</tr>
</table>
</form:form>
<div>
Back to List
</div>
</section>
</div>
After successful POST you should do a redirect.
Something like this:
return "redirect:/restaurant/edit/" + restaurant.getId();
or
return new RedirectView("/restaurant/edit/" + restaurant.getId(), false);
There is a different method you can use to return the model that will include the parameter. I believe this may solve your problem.
#RequestMapping(value = "restaurant/edit/{id}", method = RequestMethod.GET)
public String editRestaurant(#PathVariable Long id, Model model) {
Restaurant restaurant = restaurantService.getRestaurant(id);
return new ModelAndView("editRestaurant", "restaurant", restaurant);
}

Spring JSP passing variables

I want to handle simple form. Here's form from my signUp.jsp, where from I receive my data
<form:form method="POST" commandName="user-entity" action="process.html">
<table>
<tr>
<td><form:label path="userName">Name:</form:label></td>
<td><form:input path="userName" /></td>
</tr>
<tr>
<td><form:label path="label">Age:</form:label></td>
<td><form:label path="label"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
<td></td>
<td></td>
</tr>
</table>
</form:form>
And part of my result.jsp
<p>User's name is ${user.userName}. The age is ${user.age}.</p>
And UserController.java
#Controller
public class UserController {
#RequestMapping(value = "/signUp")
public ModelAndView signUpPage() {
return new ModelAndView("signUp", "user-entity", new User());
}
#RequestMapping(value = "/process")
public ModelAndView processUser(#ModelAttribute User user) {
ModelAndView model = new ModelAndView();
model.setViewName("result");
model.addObject("user", user);
return model;
}
}
As the result I get
User's name is ${user.userName}. The age is ${user.password}.
and i have no idea why. Where might be the problem?
Missing
<%# page isELIgnored="false"%> in result.jsp
Solution brought from here

form:errors does not display error message when value is rejected

the complete code is in github:
https://github.com/cuipengfei/MPJSP/tree/master/tmp
in the controller, there is a method that handles the submit:
#RequestMapping(value = "/home", method = RequestMethod.POST)
public void handleSubmit(Customer model, BindingResult result) {
System.out.println(model.getUserName());
result.rejectValue("userName", "required.userName", "user name invalid");
}
and in jsp, there is a form like this:
<form:form method="POST" action="home" modelAttribute="Customer">
<table>
<tr>
<td>Username :</td>
<td><form:input path="userName" /></td>
<td><form:errors path="userName" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
the controllers just rejects value every time, but the error message is not displayed.
the complete code can be found here:
https://github.com/cuipengfei/MPJSP/tree/master/tmp
try to set commandName attribute in your form tag
<form:form method="POST" action="home" commandName="Customer">

Categories