How can i receive a url parameter again after do validation method - java

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>

Related

Exception while calling updating data

this is my jsp file to edit data.
CustomerEdit.jsp
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Edit</title>
</head>
<body>
<div align="center">
<h3>Edit Customer Information</h3>
</div>
<form:form id="editForm" modelAttribute="user" action="editsave"
method="post">
<table align="center">
<tr>
<td><form:label path="customerid"></form:label></td>
<td><form:hidden path="customerid" name="customerid" id="customerid" /></td>
</tr>
<tr>
<td><form:label path="firstname">Firstname</form:label></td>
<td><form:input path="firstname" name="firstname" id="firstname" /></td>
</tr>
<tr>
<td><form:label path="lastname">Lastname</form:label></td>
<td><form:input path="lastname" name="lastname" id="lastname" /></td>
</tr>
<tr>
<td><form:label path="street">Street</form:label></td>
<td><form:input path="street" name="street" id="street" /></td>
</tr>
<tr>
<td><form:label path="city">City</form:label></td>
<td><form:input path="city" name="city" id="city" /></td>
</tr>
<tr>
<td><form:label path="province">Province</form:label></td>
<td><form:input path="province" name="province" id="province" /></td>
</tr>
<tr>
<td><form:label path="country">Country</form:label></td>
<td><form:input path="country" name="country" id="country" /></td>
</tr>
<tr>
<td><form:label path="birthday">Birthday</form:label></td>
<td><form:input path="birthday" name="birthday" id="birthday" /></td>
</tr>
<tr>
<td><form:label path="sin">SIN</form:label></td>
<td><form:input path="sin" name="sin" id="sin" /></td>
</tr>
<tr>
<td><form:label path="passport">Passport Number</form:label></td>
<td><form:input path="passport" name="passport" id="passport" /></td>
</tr>
<tr>
<td><form:label path="nationality">Nationality</form:label></td>
<td><form:input path="nationality" name="nationality" id="nationality" /></td>
</tr>
<tr>
<td><form:label path="email">Email Address</form:label></td>
<td><form:input path="email" name="email" id="email" /></td>
</tr>
<tr>
<td><form:label path="loginid"></form:label></td>
<td><form:hidden path="loginid" name="loginid" id="loginid" /></td>
</tr>
<tr>
<td><form:label path="password">Password</form:label></td>
<td><form:password path="password" name="password"
id="password" /></td>
</tr>
<tr>
<td></td>
<td><form:button id="submit" name="submit">Save</form:button></td>
</tr>
</table>
</form:form>
</body>
</html>
and my controller
#Controller
public class RegisterControl {​​​
#Autowired
UserDao dao;
#RequestMapping(value = "/editcust/{customerid}")
public ModelAndView edit(#PathVariable int customerid, Model m) {
User cust = dao.getCustomerById(customerid);
ModelAndView mav = new ModelAndView("CustomerEdit");
mav.addObject("user", cust);
return mav;
}
public UserService userService;
#RequestMapping(value = "/editsave", method = RequestMethod.POST)
public String editsave(#ModelAttribute("user") User user) {
System.out.println("HELLOOOOO!!!!!");
dao.update(user);
return "redirect:/homepage";
}
}
I get My customerEdit form with data. but when I click on save to update my data I get Exception
Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "editsave"]
I don't even get HELLOOOO printed on console.
PS: My Register form is working but getting error while updating data.
Please Help. Thanks in advance.
Apparently you are sending some kind of User field which is declared as int equal to "editsave" (which is string).
You can just change all User fields to String and check (with debug) which field is making problems.
You should realy make sure that client isn't able to send non number type of that field, although it may be tricky because you can't add type attribute because the spring:input form tag doesnt support the type attribute and there is no such thing as spring:number. But you can use jquery to add the type="number" attribute to the parsed html. Something like this:
$(".selector").attr({
"type" : "number",
});
EDIT after new exception:
you also need to add BindingResult to your controller method. In case you want to validate any field of User object you can set errors into it. If not, you can just copy my snippet
public UserService userService;
#RequestMapping(value = "/editsave", method = RequestMethod.POST)
public String editsave(#ModelAttribute("user") User user, BindingResult result) {
System.out.println("HELLOOOOO!!!!!");
dao.update(user);
return "redirect:/homepage";
}

Trying to open a edit form to edit an object in Spring but returning a 404

I'm trying to create an edit form and prepopulate to form with the chosen objects values but it is returning an HTTP status of 404 and the error message I'm getting is
org.springframework.web.servlet.DispatcherServlet.noHandlerFound No
mapping for GET
/AgentsCRUD/agent/edit/1;jsessionid=07E2EC08848D0C9C9346DC67563DDF1F
I think what I have is pretty logical but I must have messed up with the mapping.
The code in the get AllAgent.jsp
<spring:message code="welcome.message" />
<body>
<table style="width:100%">
<tr>
<th align="left"><spring:message code="label.agentId" /></th>
<th align="left"><spring:message code="label.name" /></th>
<th align="left"><spring:message code="label.fax" /></th>
<th align="left"><spring:message code="label.phone" /></th>
<th align="left"><spring:message code="label.email" /></th>
<th align="left"><spring:message code="label.datejoined" /></th>
<th align="left"><spring:message code="label.sales" /></th>
<th align="left"><spring:message code="label.actions" /></th>
</tr>
<c:forEach items="${agentList}" var="agent">
<tr>
<td>${agent.agentId}</td>
<td>${agent.name}</td>
<td>${agent.fax}</td>
<td>${agent.phone}</td>
<td>${agent.email}</td>
<td>
<spring:message code="label.delete" />
<spring:url value="/agent/edit/${agent.agentId}" var="editURL"/>
<spring:message code="label.edit" />
<spring:message code="label.insert" />
</td>
</tr>
</c:forEach>
</table>
</body>
the code in the controller AgentController.java
#GetMapping("/edit")
public ModelAndView EditAnAgent(#QueryParam("agentId") int agentId) {
return new ModelAndView("/editAgent", "agent", service.getAgentById(agentId));
}
#GetMapping("/editAgent")
public ModelAndView editAgent(#Valid #ModelAttribute("agent") Agents a, BindingResult result, ModelMap model) {
if (result.hasErrors()) {
return new ModelAndView("/editAgent");
}
service.editAgent(a);
return new ModelAndView("redirect:/agent");
}
the code in the Model AgentService.java
public static Agents getAgentByID(int agentId) {
EntityManager em = DBUtil.getEMF().createEntityManager();
Agents a = null;
try {
a = em.createNamedQuery("Agents.findByAgentId", Agents.class)
.setParameter("agentId", (agentId))
.getSingleResult();
} catch (Exception ex) {
System.out.println("Error in getting property details: " + ex);
} finally {
em.clear();
}
return a;
}
public void editAgent(Agents a) {
EntityManager em = DBUtil.getEMF().createEntityManager();
EntityTransaction transaction = em.getTransaction();
try {
transaction.begin();
em.merge(a);
transaction.commit();
} catch (Exception e) {
System.out.println(e);
} finally {
em.close();
}
}
the code in the editAgent.jsp
<form:form method="POST" action="/AgentsCRUD/agent/editAgent" modelAttribute="agent">
<table>
<tr>
<td><form:label path="agentId"><spring:message code="label.agentId" /></form:label></td>
<td><form:input path="agentId"/></td>
<td style="color:red"><form:errors path="agentId"/> </td>
</tr>
<tr>
<td><form:label path="name"><spring:message code="label.name" /></form:label></td>
<td><form:input path="name" /></td>
<td style="color:red"><form:errors path="name"/> </td>
</tr>
<tr>
<td><form:label path="phone"><spring:message code="label.phone" /></form:label></td>
<td><form:input path="phone"/></td>
<td style="color:red"><form:errors path="phone"/> </td>
</tr>
<tr>
<td><form:label path="fax"><spring:message code="label.fax" /></form:label></td>
<td><form:input path="fax"/></td>
<td style="color:red"> <form:errors path="fax"/> </td>
</tr>
<tr>
<td><form:label path="email"><spring:message code="label.email" /></form:label></td>
<td><form:input path="email"/></td>
<td style="color:red"> <form:errors path="email"/> </td>
</tr>
<tr>
<td><form:label path="username"><spring:message code="label.username" /></form:label></td>
<td><form:input path="username"/></td>
<td style="color:red"> <form:errors path="username"/> </td>
</tr>
<tr>
<td><form:label path="password"><spring:message code="label.password" /></form:label></td>
<td><form:input path="password"/></td>
<td style="color:red"> <form:errors path="password"/> </td>
</tr>
<tr>
<spring:message code="submit.button" var="labelSubmit"></spring:message>
<td><input type="submit" value="${labelSubmit}"/></td>
</tr>
</table>
</body>
</form:form>
In the Error the url given is .../edit/1 where 1 is a path parameter,
However in the get mapping, you are trying to read it as a query parameter.
Try this.
#GetMapping("/edit/{agentId}")
Patient getEmployee(#PathParam("agentId") int agentId) ;

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);
}

Form validation with form:options

Form:Options working pretty well, but if I submit wrong data in Form, form:options in newContact.jsp shows the first element of departmentList as selected.
ContactController:
#RequestMapping(value="/saveContact", method=RequestMethod.GET)
public ModelAndView newuserForm(){
ModelAndView mav = new ModelAndView("newContact");
// Contact contact = new Contact();
// Department department = new Department();
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername();
mav.addObject("username", name);
mav.addObject("newContact", new Contact());
// mav.addObject("department", department);
mav.addObject("departmentList", departmentService.listDepartment());
//mav.getModelMap().put("newContact", contact);
return mav;
}
#RequestMapping(value="/saveContact", method=RequestMethod.POST)
public String create(#ModelAttribute("newContact")Contact contact, BindingResult result, SessionStatus status,Map<String, Object> map)
{
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername();
map.put("departmentList", departmentService.listDepartment());
map.put("username", name);
contactFormvalidator.validate(contact, result);
if (result.hasErrors())
{
return "newContact";
}
contactService.addContact(contact);
status.setComplete();
//return "redirect:/showContacts.do";
return "newContactSuccess";
}
newContact.jsp:
<%#include file="header.jsp"%>
<div id="menu">
<div id="subMenu"></div>
</div>
<div id="main">
<h2>Contact Manager</h2>
<form:form method="post" action="saveContact.do" commandName="newContact" >
<table>
<tr>
<td><form:label path="firstname">
<spring:message code="label.firstname" />
</form:label></td>
<td><form:input path="firstname" /></td>
<td><form:errors path="firstname" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td><form:label path="lastname">
<spring:message code="label.lastname" />
</form:label></td>
<td><form:input path="lastname" /></td>
<td><form:errors path="lastname" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td><form:label path="email">
<spring:message code="label.email" />
</form:label></td>
<td><form:input path="email" /></td>
<td><form:errors path="email" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td><form:label path="telephone">
<spring:message code="label.telephone" />
</form:label></td>
<td><form:input path="telephone" /></td>
<td><form:errors path="telephone" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td><form:label path="department">
<spring:message code="label.department" />
</form:label></td>
<td><form:select path="department" >
<form:option label="**SELECT**" value="0"></form:option>
<form:options items="${departmentList}" itemValue="id" itemLabel="name"></form:options>
</form:select> </td>
<td><form:errors path="department" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td colspan="2"><input type="submit"
value="<spring:message code="label.addcontact"/>" /></td>
</tr>
</table>
</form:form>
</div>
<%# include file="footer.jsp"%>
ContactFormValidator:
package pl.ivmx.contact.validator;
import java.util.regex.*;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import pl.ivmx.contact.form.Contact;;
//#Component("contactFormValidator")
public class ContactFormValidator implements Validator{
#Override
public boolean supports(Class clazz) {
return Contact.class.isAssignableFrom(clazz);
}
#SuppressWarnings("unchecked")
#Override
public void validate(Object obj, Errors errors) {
Contact contact = (Contact) obj;
Pattern p = Pattern.compile("[a-zA-Z]*[0-9]*#[a-zA-Z]*.[a-zA-Z]*");
Matcher m = p.matcher(contact.getEmail());
boolean b = m.matches();
if (b != true) {
errors.rejectValue("email", "error.is.not.valid",
"Email does not Valid ");
}
if (contact.getFirstname() == null || contact.getFirstname().length() < 3) {
errors.rejectValue("firstname", "error.empty.field",
"Please Enter First Name");
}
if (contact.getLastname() == null || contact.getLastname().length() < 4) {
errors.rejectValue("lastname", "error.empty.field",
"Please Enter Last Name");
}
if (contact.getTelephone() == 0 || String.valueOf(contact.getTelephone()).trim().length() < 2 ||
String.valueOf(contact.getTelephone()).trim().length() > 9) {
errors.rejectValue("telephone", "error.empty.field",
"Please Enter Telephone");
}
if (contact.getDepartment() == null) {
errors.rejectValue("department", "error.empty.field",
"Please select department");
}
}
}
Instead of returning String in your submit method return ModelAndView ...
#RequestMapping(value="/saveContact", method=RequestMethod.POST)
public ModelAndView create(#ModelAttribute("newContact")Contact contact, BindingResult result, SessionStatus status,ModelMap map)
{
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername();
map.addAttribute("departmentList", departmentService.listDepartment());
map.addAttribute("username", name);
contactFormvalidator.validate(contact, result);
if (result.hasErrors())
{
return new ModelAndView("newContact",map);
}
contactService.addContact(contact);
status.setComplete();
//return new ModelAndView("redirect:/showContacts.do");
return new ModelAndView("newContactSuccess");
}

#RequestParam is null (Spring MVC)

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";

Categories