Exception while calling updating data - java

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

Related

how to display "Model object Attribute ArrayList<String>" values as DROP DOWN values in JSP

<form:form action="saveNewUsers" method="post" modelAttribute="users">
<table>
<tr><td>Id</td>
<td><form:input path="id"/></td>
</tr>
<tr>
<td>User</td>
<td><form:input path="user" /></td>
</tr>
<tr>
<td>Password</td>
<td><form:input path="password" /></td>
</tr>
<tr>
<td>FirstName</td>
<td><form:input path="first_name" /></td>
</tr>
<tr>
<td>LastName</td>
<td><form:input path="last_name" /></td>
</tr>
<tr>
<td>Group Id</td>
<td>
<select name="GroupId">
<c:forEach items="${users.al}" var="item">
<option value="${item.value}">${item.value}</option>
</c:forEach>
</select>
</td>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save"></td>
</tr>
</table>
Please let me know how to get ArrayList attribute from ModelObject of 'users' and print those values of ArrayList as DROPDOWN Menu in JSP.
Actually I send that 'users' model object from the Controller of the Spring MVC

<form:select spring mvc shows the object as a string

Hi all I am using spring mvc and I have a form where I have to use a combo box in step a list of objects driver to be loaded into the combo box but it turns out I show it as a string and not as the object .
a little above I have a combo box where I pass in the same way but is out of form and position with JSTL.
what I need is that the first two attributes of my object is loaded for the combo box
Here is the code and images so they can help me.
Controller
#RequestMapping(value="products.htm", method=RequestMethod.GET)
public String homeSuppliers(#RequestParam(required=false) String state, ModelMap model){
try {
if (state != null) {
model.addAttribute("state", state);
}
List<ProveedoresDTO> listSupplier = supplierService.getAllSuppliersDTO();
List<ProductosDTO> listProducts = productService.getAllProductsDTO();
model.addAttribute("listProducts",listProducts);
model.addAttribute("listSupplier",listSupplier);
model.addAttribute("productAtt", new ProductsDTO());
} catch (Exception e) {
model.addAttribute("msg",e.getMessage());
}
return "productsView/products";
}
JSP
<select id="comboProducts" onchange="BuscaProductPorId()">
<option value="0"></option>
<c:forEach items="${listProducts}" var="product">
<option value="${product.productID}">${product.productName}</option>
</c:forEach>
</select>
<h1>${msg}</h1>
<form:form commandName="productAtt" action="crearProduct" method="get"
id="formSend">
<fieldset>
<legend>Product</legend>
<form:hidden path="productID" />
<table>
<tr>
<td><form:label path="productName">Nombre Product</form:label></td>
<td>:</td>
<td><form:input path="productName" /></td>
<td><form:errors path="productName" /></td>
</tr>
<tr>
<td><form:label path="supplierID">Select Supplier</form:label></td>
<td>:</td>
<td><form:select path="supplierID" multiple="false" items="${listSupplier}"></form:select></td>
<td><form:errors path="supplierID" /></td>
</tr>
<tr>
<td><form:label path="quantityPerUnit">Cantidad por Unidad</form:label></td>
<td>:</td>
<td><form:input path="quantityPerUnit" /></td>
<td><form:errors path="quantityPerUnit" /></td>
</tr>
<tr>
<td><form:label path="unitPrice">Precio Unitario</form:label></td>
<td>:</td>
<td><form:input path="unitPrice" /></td>
<td><form:errors path="unitPrice" /></td>
</tr>
<tr>
<td><form:label path="unitsInStock">Unidades en Stock</form:label></td>
<td>:</td>
<td><form:input path="unitsInStock" /></td>
<td><form:errors path="unitsInStock" /></td>
</tr>
<tr>
<td><form:label path="unitsOnOrder">Unidades en Orden</form:label></td>
<td>:</td>
<td><form:input path="unitsOnOrder" /></td>
<td><form:errors path="unitsOnOrder" /></td>
</tr>
<tr>
<td><form:label path="reorderLevel">Nivel de Orden</form:label></td>
<td>:</td>
<td><form:input path="reorderLevel" /></td>
<td><form:errors path="reorderLevel" /></td>
</tr>
<tr>
<td><form:label path="discontinued">Descontinuado</form:label></td>
<td>:</td>
<td><form:input path="discontinued" /></td>
<td><form:errors path="discontinued" /></td>
</tr>
<tr>
<td><br></td>
</tr>
<tr>
<td><input type="submit" value="Crear Product" name="crea"
id="crea"></td>
<td><input type="button" onclick="formReset()"
value="Limpiar Campos" /></td>
</tr>
</table>
</fieldset>
</form:form>
Result
You are not specifying what to use for your options. Try this:
<form:select path="supplierID" multiple="false">
<form:options items="${listSupplier}" itemValue="SupplierID" itemLabel="CompanyName"/>
</form:select>
Please note the items name has been changed to match the one given by the #Controller

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

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

Web Flow problems from GET Jsp to a POST JSP (Form) - Spring MVC Annotated

i have a JSP with hyperlink
<table>
<tr>
<td>Product Name : </td>
<td>${product.name}</td>
</tr>
<tr>
<td>Description:</td>
<td>${product.description}</td>
</tr>
<tr>
<td>Price:</td>
<td>${product.price}</td>
</tr>
<tr><td> </td></tr>
<tr>
<td>
Add to shopping basket
</td>
</tr>
<tr><td> </td></tr>
<tr><td> </td></tr>
<tr>
<td>
<table>
<tr>
<td>Return to Home Page</td>
<td> </td>
<td>Logout
(<security:authentication property="principal.username" />)
</td>
</tr>
</table>
</td>
</tr>
And the controller
#Controller
#SessionAttributes("basket")
public class ShopBasketController {
private BasketManager basketManager;
private CustomerManager customerManager;
private CategoryManager categoryManager;
#Autowired
public ShopBasketController(BasketManager basketManager, CustomerManager customerManager, CategoryManager categoryManager) {
this.basketManager = basketManager;
this.customerManager = customerManager;
this.categoryManager = categoryManager;
}
#RequestMapping(value="/basketItems", method=RequestMethod.POST)
public String removeProduct(#ModelAttribute("basket") Basket basket, BindingResult bindingResult, Model model) {
Basket newBasket = ShoppingBasketUtils.removeFromBasket(basket, basketManager);
basketManager.update(newBasket);
model.addAttribute("basket",newBasket);
model.addAttribute("customer", "Sonx"+" Nkuks");
model.addAttribute("totalItems", basketManager.getTotalNumberOfItems(basket));
model.addAttribute("totalPrice", ShoppingBasketUtils.currencyFormat(basketManager.getTotalProductPrice(basket)));
return "basketItems";
}
#RequestMapping("/populateBasket")
public String populateBasket(#RequestParam("code") String productCode, #RequestParam("name") String categoryName, Model model) {
Customer customer = customerManager.getCustomer("Sonx", "Nkuks");
if(customer != null) {
Basket shopBasket = ShoppingBasketUtils.addToBasket(productCode, categoryManager.getCategory(categoryName),
basketManager.getBasket(customer.getReferenceNumber()), basketManager);
basketManager.update(shopBasket);
model.addAttribute("basket",shopBasket);
model.addAttribute("customer", customer.getFirstName()+" "+customer.getLastName());
model.addAttribute("totalItems", basketManager.getTotalNumberOfItems(shopBasket));
model.addAttribute("totalPrice", ShoppingBasketUtils.currencyFormat(basketManager.getTotalProductPrice(shopBasket)));
return "basketItems";
}
model.addAttribute("customer", "test".concat(" test"));
return "/error";
}
}
Then the form ...
<form:form commandName="basket">
<table>
<tr>
<td>
<table>
<tr>
<td>Customer Name : </td>
<td>${customer}</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table width="600" border="1" cellspacing="0" cellpadding="2"
border="0">
<thead>
<tr>
<td>Products:</td>
</tr>
<tr>
<td>Product Name</td>
<td>Product Code</td>
<td>Description</td>
<td>Price</td>
<td>Remove</td>
</tr>
</thead>
<tbody>
<c:forEach items="${basket.products}" var="product">
<tr>
<td>${product.name}</td>
<td>${product.productCode}</td>
<td>${product.description}</td>
<td>${product.price}</td>
<td><form:checkbox path="removeItemCodes" value="${product.productCode}" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</td>
</tr>
<tr>
<td>
<table>
<tr>
<td>Total Price</td>
<td> </td>
<td>${totalPrice}</td>
</tr>
<tr>
<td>Total Items</td>
<td> </td>
<td>${totalItems}</td>
</tr>
</table>
</td>
</tr>
<tr><td> </td></tr>
<tr>
<td><input type="submit" value="Remove Items" /></td>
</tr>
<tr><td> </td></tr>
<tr><td> </td></tr>
<tr>
<td>
<table>
<tr>
<td>Return to Home Page</td>
<td> </td>
<td>Logout
(<security:authentication property="principal.username" />)
</td>
</tr>
</table>
</td>
</tr>
</table>
When i press the link from the first JSP "" the controller succesfully execute the method populateBasket and loads the Form. But when i submit the form, i want it to call the POST method (basketItems)... But it doesn't, pressng the submit button always executes the GET method (populateBasket) .. This doesn't happen if i load the form directly from the index page, it loads successfully . Problem is when coming from that JSP ?
If you want the form to submit to a different URL from the one that was used to retrieve the page, you need to explicitly set the action on it. Otherwise Spring is going to just fill it in with the current URL.

Categories