get and set values to a Map in jsp using jstl - java

I have a Map Object,this Map Object has some values and i m populating these values on a jsp page but the problem is that when i post the jsp page to another controller i want the same values to be present in the map Object.
Map(Some values)--->controller--->jsp(Map+some additional values)----post----->another controller[want Map+additional values]
MailContent.java
public class MailContent {
private String from;
private String to;
private String[] toMany;
private Map<String,byte[]> attachements;
//getter setter
}
some.jsp
<f:form action="../hr/sendNotification" commandName="mailHolder">
<table>
<tr>
<td><label>From:</label></td>
<td><input class="inputq" type="text" name="from" /></td>
</tr>
<tr>
<td><label>To:</label></td>
<td><input type="text" class="inputq" name="to" id="to"></input></td>
</tr>
<tr>
<td><label>Subject:</label></td>
<td><input class="inputq" type="text" name="subject" /></td>
</tr>
<c:forEach var="attach" items="${mailHolder.attachements }" varStatus="i">
<tr>
<td><label>Attachement:${i.index+1 }</label></td>
<td><input class="inputq" type="text" value="${attach.value }" name="attachements[${i.index }].value"/>
<input class="inputq" type="text" value="${attach.key }" name="attachements[${i.index }].key"/>
</tr>
</c:forEach>
<tr>
<td><label>Message:</label></td>
<td><textarea class="tarea" cols="60" rows="10" name="message"></textarea></td>
</tr>
<tr>
<td></td>
<td><input class="fancy" type="submit" value="Send" />
<input class="fancy" type="reset"
value="Reset" /></td>
</tr>
</table>
</f:form>
The key value pair is displayed successfully on jsp but when i post it to another controller and get the values then the key part is filled with some index instead of value.
on console:
before:
MailContent [from=null, to=null, attachements={abc=[B#1d37913, xyz=[B#b20ff5}, subject=null, message=null]
Afetr post:
MailContent [from=from, to=to#gmail.com, attachements={0=[B#ebe064, 1=[B#1d90655}, subject=subject, message=message]

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

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

servlets: get the null parameters by ajax in servlets

String isno1=request.getParameter("isbn");
String bktitle2=request.getParameter("booktitle");
String authr3=(String) request.getParameter("author");
System.out.println(isno1+bktitle2+authr3);
Enumeration paramaterNames = request.getParameterNames();
when i am taking the parameters in servlet then i am gettin my values as 'null'
what wrong am i doing.
this is the way i am setting the parameters...
from a jsp page using script tag
<script type="text/javascript">
function getHTTPObject()
{
var httpobject;
if(!httpobject && typeof(XMLHttpRequest) != 'undefined')
{
try{
httpobject=new XMLHttpRequest();
}
catch(e){
xmlhttp=false;
}
}
return httpobject;
}
var httpob=getHTTPObject();
function handleHttpResponse(){
if(httpob.readyState==4){
//alert("sd");
var result=httpob.responseText;
alert(result);
/* document.write("hi your book is submitted !!!!!"); */
}
}
function auth(){
var params="isbn="+document.mayurform.isbn.value+"&booktitle="+document.mayurform.booktitle.value+"&author="+document.mayurform.author.value;
alert("params sending"+params);
httpob.open("POST","addbook",true);
httpob.setRequestHeader("Content-type","application/x-www-form-urlencoded");
httpob.setRequestHeader("Content-length",params.length);
httpob.setRequestHeader("Connection","close");
/* httpob.setRequestHeader("Content-type","application/x-www-from-urlencoded");
httpob.setRequestHeader("Content-length",params.length);
httpob.setRequestHeader("Connection","close"); */
httpob.onreadystatechange=handleHttpResponse;
httpob.send();
}
</script>
and this my form.....
<form style="margin: 100px;" name="mayurform">
<table align="center">
<tr>
<td align="center">ISBN NO.</td>
<td><input align="middle" type="text" size="20" name="id" id="isbn">
</tr>
<tr>
<td align="center">Book-Title</td>
<td><input align="middle" type="text" size="20" name="pwd" id="booktitle">
</td>
</tr>
<tr>
<td align="center">Author</td>
<td><input align="middle" type="text" size="20" name="pwd" id="author">
</tr>
<tr>
<td><input align="middle" type="button" size="20" name="Add-Book" onclick="auth()">
</tr>
</table>
</form>
You are fetching parameters with ID's you should give Names.
for example
String isno1=request.getParameter("isbn"); //here is isbn is id
you should write
<input align="middle" type="text" size="20" name="id" id="isbn">
String isno1=request.getParameter("id");-----------^
and also
<td><input align="middle" type="text" size="20" name="pwd" id="booktitle">
<td><input align="middle" type="text" size="20" name="pwd" id="author">
both inputs have the same **name** please check it
http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Form-Data.html
Use like below ajax send() to send data
function auth(){
var params="isbn="+document.mayurform.isbn.value+"&booktitle="+document.mayurform.booktitle.value+"&author="+document.mayurform.author.value;
alert("params sending"+params);
.......
...
httpob.send(params);//change is here
}
call httpob.send(),passing in the parameters that will be sent (without the "?" prefix).

Spring MVC Request Param

I have a login page with form action of j_security_check. As of now this form just have two fields namely username
and password. I want to add a new dropdown to this form and collect the selected value in controller using
#RequestParam. For some reason I am not able to pass this dropdown value from JSP to my controller as its throwing the
exception: MissingServletRequestParameterException (Which occurs anytime a request param is missing).
In the code below I added the Visuals dropdown. Do I need to use Spring:Bind tag here?
Also on successful login, the control is directed to a controller with request mapping /controller1.html and this is where
I am trying to collect the dropdown value.
<form name="appLogin" action="j_security_check" method="POST">
<table width="100%">
<tr>
<td align="center">
<table>
<tr>
<td>Username: </td>
<td><input id="userName" name="j_username" value=""/></td>
</tr>
<tr>
<td>Password: </td>
<td><input name="j_password" type="password" value="" /></td>
</tr>
<tr>
<td>Visual: </td>
<td><Select name="visuals" id="visuals"/>
<option value="S1">S1</option>
<option value="S2">S2</option>
<option value="S3">S3</option>
<option value="S4">S4</option>
</Select>
</td>
</tr>
</table>
<table>
<tr>
<td>
<button type="submit" name="submit" value="Sign In">Sign In</button>
<input type="submit"/>
</td>
</tr>
</table>
</div>
</div>
</td>
</tr>
</table>
</form>
Controller Code:
#RequestMapping( value = " /controller1.html", method = RequestMethod.GET )
public String setupForm( #RequestParam(value = "visuals", required=false) String visuals,
ModelMap model )
{
List<String> studentNames = new ArrayList<String>();
List<String> teacherNames = new ArrayList<String>();
model.addAttribute("someData", teacherNames);
model.addAttribute("anotherData", studentNames);
model.addAttribute("visuals", visuals);
log.info("Role from Dropdown: " + visuals);
return "school/classTen";
}
You need to create yyour own Filter by extending AbstractAuthenticationProcessingFilter
I don't have the entire code in front of my eyes, but the following article could help you:
http://mark.koli.ch/2010/07/spring-3-and-spring-security-setting-your-own-custom-j-spring-security-check-filter-processes-url.html

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