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);
}
Related
I want to take get a url parameter again after I've done another method. I tried adding the line new ModelAndView (updatealbum.htm?albumId=${album.albumId}"); but failed.
My path when I click the edit link is:
http://localhost:8089/MusicStore/admin/updatealbum.htm?albumId=13
My path after press submit button:
http://localhost:8089/MusicStore/admin/submitupdatealbum.htm?albumId=13
But when I click submit again:
http://localhost:8089/MusicStore/admin/submitupdatealbum.htm?albumId=
AlbumController.java
#RequestMapping(value = "*/updatealbum.htm", method = RequestMethod.GET)
public ModelAndView updatealbum(
#RequestParam(value = "albumId") int albumId, ModelMap model,
#ModelAttribute("album") Album album) {
Album theAlbum = albumService.findAlbum(albumId);
List<Category> listCategory = albumService.getListCategory();
System.out.println(theAlbum.getName());
model.addAttribute("listCategory", listCategory);
model.addAttribute("theAlbum", theAlbum);
return new ModelAndView("updatealbum", "command", new Album());
}
#RequestMapping(value = "*/submitupdatealbum.htm", method = RequestMethod.POST)
public ModelAndView submitUpdateAlbum(
#Valid #ModelAttribute("album") Album album, BindingResult result,
#RequestParam(value = "albumId") int albumId,
ModelMap model) {
if (result.hasErrors()) {
System.out.println(result);
ModelAndView model1 = new ModelAndView("updatealbum");
model.addAttribute("albumId",albumId);
System.out.println(albumId);
return model1;
}
Album newAlbum = albumService.findAlbum(albumId);
album.parseDateToString();
newAlbum.setReleaseDate(album.getReleaseDate());
newAlbum.setAuthor(album.getAuthor());
newAlbum.setDiscount(album.getDiscount());
newAlbum.setName(album.getName());
newAlbum.setPicture(album.getPicture());
newAlbum.setReleaseDate(album.getReleaseDate());
newAlbum.setSinger(album.getSinger());
newAlbum.setCategory(album.getCategory());
albumService.editAlbum(newAlbum);
model.addAttribute("succsessMgs", "Form successfully submitted");
return new ModelAndView(setupForm1(model));
}
updatealbum.jsp
<div class="content">
<c:if test="${not empty succsessMgs}">
<div class="mgs">${succsessMgs}</div>
</c:if>
<div align="center">
<form:form action="submitupdatealbum.htm?albumId=${theAlbum.albumId} "
method='POST' commandName="album">
<table>
<tr height="40" align="left">
<td>Album Name:</td>
<td><form:input path="name" value="${theAlbum.name}"/></td>
<td><form:errors path="name" cssStyle="color: #ff0000;"/></td>
</tr>
<tr height="40" align="left">
<td>Singer:</td>
<td><form:input path="author" value="${theAlbum.author}"/></td>
<td><form:errors path="author" cssStyle="color: #ff0000;"/></td>
</tr>
<tr height="40" align="left">
<td>Release Date:</td>
<td><form:input path="releaseDate" value="${theAlbum.releaseDate}"/></td>
<td><form:errors path="releaseDate" cssStyle="color: #ff0000;"/></td>
</tr>
<tr height="40" align="left">
<td>Discount:</td>
<td><form:input path="discount" value="${theAlbum.discount}"/></td>
<td><form:errors path="discount" cssStyle="color: #ff0000;"/></td>
</tr>
<tr height="40" align="left">
<td>Author:</td>
<td><form:input path="author" value="${theAlbum.author}" /></td>
<td><form:errors path="author" cssStyle="color: #ff0000;"/></td>
</tr>
<%-- <tr height="40" align="left">
<td>Picture:</td>
<td><form:form enctype="multipart/form-data"
modelAttribute="album">
<input type="file" name='picture'>
</form:form></td>
</tr> --%>
<tr height="40" align="left">
<td>Image URL:</td>
<td><form:input path="picture" value="${theAlbum.picture}" /></td>
<td><form:errors path="picture" cssStyle="color: #ff0000;"/></td>
</tr>
<tr height="40" align="left">
<td>Category:</td>
<td><form:form modelAttribute="album">
<form:select path="category.categoryId">
<form:option value="" label="Choose category" />
<form:options items="${listCategory}" itemValue="categoryId"
itemLabel="categoryName" />
</form:select>
</form:form></td>
<td><springForm:errors path="category.categoryId" cssClass="error" /></td>
</tr>
<tr>
<td><input name="submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
</div>
</div>
Use it
#RequestMapping(value = "*/submitupdatealbum.htm", method = RequestMethod.POST)
public ModelAndView submitUpdateAlbum(
#Valid #ModelAttribute("album") Album album, BindingResult result,
#RequestParam(value = "albumId") int albumId, ModelMap model) {
System.out.println("ssssssssssssssssss:" + result);
if (result.hasErrors()) {
System.out.println("result:" + result);
System.out.println("asdasdasd");
ModelAndView model1 = new ModelAndView(
"redirect:updatealbum.htm?albumId=" + album.getAlbumId());
return model1;
}
But it can't show the <td><form:errors path="name" cssStyle="color: #ff0000;"/></td>
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
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.
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">
I'm trying to add an edit function to my web app but I'm having some problems using #RequestParam. The parameter it is getting is null which it shouldn't be. I'm hoping someone can point out where I have made a mistake.
Here are the methods from the controller :
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public String getEdit(#RequestParam("customerId") Integer customerId, Model model) {
Customer existingCustomer = customerService.retrieveCustomer(customerId);
model.addAttribute("customerAttribute", existingCustomer);
return "edit-customer";
}
#RequestMapping(value = "/edit", method = RequestMethod.POST)
public String postEdit(#RequestParam("customerId") Integer customerId,
#ModelAttribute("customerAttribute") #Valid Customer customer, BindingResult result) {
if (result.hasErrors()) {
return "edit-customer";
}
customer.setCustomerId(customerId);
customerService.editCustomer(customer);
return "redirect:/test/customer/list";
and the two jsp pages
edit-customer.jsp :
<body>
<h1>Edit Existing Customer</h1>
<c:url var="saveUrl" value="/test/customer/edit?customerId=${customerAttribute.customerId}" />
<form:form modelAttribute="customerAttribute" method="POST" action="${saveUrl}">
<table>
<tr>
<td><form:label path="customerId">Customer Id:</form:label></td>
<td><form:input path="customerId" disabled="true"/></td>
</tr>
<tr>
<td><form:label path="customerCountry">Customer Country</form:label></td>
<td><form:input path="customerCountry"/></td>
</tr>
<tr>
<td><form:label path="customerName">Customer Name:</form:label></td>
<td><form:input path="customerName"/></td>
</tr>
</table>
<input type="submit" value="Save" />
</form:form>
</body>
view-all-customers.jsp :
<body>
Home
<h1>Customers</h1>
<c:url var="addUrl" value="/test/customer/add" />
<c:url var="editUrl" value="/test/customer/edit?customerId=${customer.customerId}"/>
<c:if test="${!empty customers}">
Add
</c:if>
<table style="border: 1px solid; width: 500px; text-align:center">
<thead style="background:#ccc">
<tr>
<th>Customer Id</th>
<th>Customer Country</th>
<th>Customer Name</th>
<th colspan="4"></th>
</tr>
</thead>
<tbody>
<c:forEach items="${customers}" var="customer">
<tr>
<td><c:out value="${customer.customerId}" /></td>
<td><c:out value="${customer.customerCountry}" /></td>
<td><c:out value="${customer.customerName}" /></td>
<td>Edit</td>
</tr>
</c:forEach>
</tbody>
</table>
<c:if test="${empty customers}">
There are currently no customers in the list. Add a customers.
</c:if>
</body>
Can anyone see why Integer customerId in the GET method is null?
Thank you,
D
You're using ${customer.customerId} before it's initialized:
<!-- you use it here -->
<c:url var="editUrl" value="/test/customer/edit?customerId=${customer.customerId}"/>
<c:if test="${!empty customers}">
....
<tbody>
<!-- and initialize it here -->
<c:forEach items="${customers}" var="customer">
<tr>
<td><c:out value="${customer.customerId}" /></td>
<td><c:out value="${customer.customerCountry}" /></td>
<td><c:out value="${customer.customerName}" /></td>
<td>Edit</td>
</tr>
</c:forEach>
</tbody>
</table>
Simply set editUrl inside the loop:
<c:if test="${!empty customers}">
....
<tbody>
<c:forEach items="${customers}" var="customer">
<c:url var="editUrl" value="/test/customer/edit?customerId=${customer.customerId}"/>
<tr>
<td><c:out value="${customer.customerId}" /></td>
<td><c:out value="${customer.customerCountry}" /></td>
<td><c:out value="${customer.customerName}" /></td>
<td>Edit</td>
</tr>
</c:forEach>
</tbody>
</table>
and it should work. You'd have to reset the editUrl for each customer anyway.
It may be because of you are accepting customerId as Integer, try to accept it as String.
try this one :
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public String getEdit(#RequestParam("customerId") String customerId, Model model) {
Customer existingCustomer = customerService.retrieveCustomer(Integer.parseInt(customerId));
model.addAttribute("customerAttribute", existingCustomer);
return "edit-customer";
}
#RequestMapping(value = "/edit", method = RequestMethod.POST)
public String postEdit(#RequestParam("customerId") String customerId,
#ModelAttribute("customerAttribute") #Valid Customer customer, BindingResult result) {
if (result.hasErrors()) {
return "edit-customer";
}
customer.setCustomerId(Integer.parseInt(customerId));
customerService.editCustomer(customer);
return "redirect:/test/customer/list";