i am trying to make simple spring mvc application, using jdbctemplate,but when i try to open registration page i got this error- java.lang.IllegalArgumentException: Attribute 'items' must be an array, a Collection or a Map.
last time i used this thing in another applicaton, it worked fine,but this time it is not working :(
here is my controller code and register.jsp
#RequestMapping("/register")
public ModelAndView registerEmployee(#ModelAttribute Employee employee) {
List<String> cityList = new ArrayList<String>();
cityList.add("kashipur");
cityList.add("moradabad");
cityList.add("delhi");
cityList.add("noida");
List<String> genderList = new ArrayList<String>();
genderList.add("male");
genderList.add("female");
Map<String,List<String>> map = new HashMap<String,List<String>>();
map.put("cityList",cityList);
map.put("genderList",genderList);
return new ModelAndView("register","map",map);
}
register.jsp is
<div>
<form:form method="post" action="/insert" modelAttribute="employee">
<table>
<tr>
<td>Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobuttons path="gender" items="${map.genderList}" /></td>
</tr>
<tr>
<td>City :</td>
<td><form:select path="city" items="${map.cityList}" /></td>
<tr>
<tr>
<td>Email :</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Phone :</td>
<td><form:input path="phone" /></td>
</tr>
<tr>
<td><input type="submit" value="Save" /></td>
</tr>
<tr>
<td colspan="2"><a href="getList">Click Here to See User
List</a></td>
</tr>
</table>
</form:form>
</div>
Try to change this List<String> cityList
to this ArrayList<String> cityList
same here
Map<String,List<String>> map = new HashMap<String,List<String>>();
Also try to access map element like this map['cityList']
You don't need to qualify with ${map.
Simply write
return new ModelAndView("register", map);
and in the JSP:
<td><form:radiobuttons path="gender" items="${genderList}" /></td>
and
<td><form:select path="city" items="${cityList}" /></td>
Related
I tried all the solutions but I keep getting this error. Moreover if i don't use form:form in jsp file and use a simple HTML, I get the desired output.
Controller Class
#Controller
public class controller_class {
/*
* #RequestMapping(path = "/index", method = RequestMethod.GET) public
* ModelAndView mar() { return new ModelAndView("index","command",new marks());
* }
*/
#RequestMapping("/index")
public ModelAndView showComments() {
return new ModelAndView("marks","command",new marks());
}
#RequestMapping(value = "/addMarks", method = RequestMethod.POST)
public ModelAndView stud(#ModelAttribute("marks") marks m) {
ModelAndView mv = new ModelAndView("result");
int k = m.calculate();
mv.addObject("tot_marks", k);
return mv;
}
}
index.jsp
<form:form method = "POST" modelAttribute="marks" action = "/springmvc_qa3/addMarks">
<table>
<tr>
<td><form:label path = "sci_marks">Name</form:label></td>
<td><form:input path = "sci_marks" /></td>
</tr>
<tr>
<td><form:label path = "maths_marks">Age</form:label></td>
<td><form:input path = "maths_marks" /></td>
</tr>
<tr>
<td><form:label path = "eng_marks">id</form:label></td>
<td><form:input path = "eng_marks" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
Correct Output if I use this instead
<form method="POST" action="/springmvc_qa3/addMarks" >
<table>
<tr>
<td><label >Science Marks</label></td>
<td><input type="text" name="sci_marks" /></td>
</tr>
<tr>
<td><label >Mathematics Marks</label></td>
<td><input type="text" name="maths_marks" /></td>
</tr>
<tr>
<td><label >English Marks</label></td>
<td><input type="text" name="eng_marks" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
What is the reason that I can't get the right output using the first method?
add the following to your controller class:
#ModelAttribute("marks")
public Marks nameOfMethodDoesntMatter(){
return new Marks();
}
make sure your Marks class has getters, setters and default constructor.
consider calling your class MarksDTO or something similar to convey its meaning better (DTO = data transfer object).
i have following scenario :
#ModelAttribute("persons")
public void addAttributes(Model model) {
Person person = new Person()
;
person.setAge(26);
person.setFirstName("mars");
model.addAttribute("persons", person);
}
#RequestMapping(value="/process-person")
public ModelAndView processPerson(#ModelAttribute Person person,#ModelAttribute ("persons")Person persons,ModelAndView modelAndView ) {
//
//ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("person-result-page");
modelAndView.getModel().remove("personObj");
modelAndView.addObject("pers", person);
----> modelAndView.addObject("pers2", persons);// persons holds the myname1 provided in input box
modelAndView.addObject("personObj", person);
return modelAndView;
}
As shown in the --> i want this variable -persons to hold the value obtained from addAttributes() method but it is taking the same values that i input from the jsp page :
<form:form method="POST" commandName="person-entity" action="process-person.html">
<table>
<tr>
<td><form:label path="firstName">Name:</form:label></td>
<td><form:input path="firstName" /></td>
</tr>
<tr>
<td><form:label path="age">Age:</form:label></td>
<td><form:input path="age" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit"/>
</td>
<td></td>
<td></td>
</tr>
</table>
</form:form>
<br/>
i saw few similar questions but none of them resolved this problem . Here i want values from addAttribute method to placed inside "persons" object, but it is taking the same value as that of "person" being provided from the form.jsp.
please help me out
I am working on a Spring-MVC application and I must use image upload for storing images in Database. I tried to go through examples on internet, but my overall observation is there is some argument regarding type of upload, and who manages it. Nevertheless, I am uploading the image from an HTML, saving it in Database as OID, using byte array with #Lob to save. I am unable to see the image preview when i use :
I will post code of how I have achieved it, kindly let me know whats wrong.
HTML code for image preview :
<img src="${product.productimage}" width="100" height="100"/>
When I use product.getImage().toString in service, I get weird characters by 'B[jlkisf12', but only 12-13 of them, I imagine that is the path.
Entity :
#Column(name = "productimage")
byte[] productimage; // With getters and setters
JSP file :
<c:url var="add" value="/product/add"></c:url>
<form:form action="${add}" commandName="product">
<table>
<c:if test="${!empty product.productname}">
<tr>
<td>
<form:label path="productid">
<spring:message text="productid"/>
</form:label>
</td>
<td>
<form:input path="productid" readonly="true" size="8" disabled="true" />
<form:hidden path="productid" />
</td>
</tr>
</c:if>
<tr>
<td>
<form:label path="productname">
<spring:message text="productname:"/>
</form:label>
</td>
<td>
<form:input path="productname"/>
</td>
</tr>
<tr>
<td>
<form:label path="productdescription">
<spring:message text="productdescription"/>
</form:label>
</td>
<td>
<form:input path="productdescription"/>
</td>
</tr>
<tr>
<td>
<form:label path="productcondition">
<spring:message text="productcondition"/>
</form:label>
</td>
<td>
<form:input path="productcondition"/>
</td>
</tr>
<tr>
<td>
<form:label path="productage">
<spring:message text="productage"/>
</form:label>
</td>
<td>
<form:input path="productage" />
</td>
</tr>
<tr>
<td>
<form:label path="productean">
<spring:message text="productean"/>
</form:label>
</td>
<td>
<form:input path="productean" />
</td>
</tr>
<tr>
<td>
<form:label path="productisbn">
<spring:message text="productisbn"/>
</form:label>
</td>
<td>
<form:input path="productisbn" />
</td>
</tr>
<tr>
<td>
<form:label path="ordernumber">
<spring:message text="ordernumber"/>
</form:label>
</td>
<td>
<form:input path="ordernumber" />
</td>
</tr>
<tr>
<td>
<form:label path="productimage">
<spring:message text="productimage"/>
</form:label>
</td>
<td>
<form:input type="file" path="productimage" />
</td>
</tr>
</table>
<tr>
<td colspan="2">
<c:if test="${!empty product.productname}">
<input type="submit"
value="<spring:message text="Edit Product"/>" />
</c:if>
<c:if test="${empty product.productname}">
<input type="submit"
value="<spring:message text="Add Product"/>" />
</c:if>
</td>
</tr>
</form:form>
<br>
<h3>Product List</h3>
<c:if test="${!empty listProducts}">
<table class="tg">
<tr>
<th width="80">Product ID</th>
<th width="80">Product image</th>
<th width="120">Product name</th>
<th width="120">Product description</th>
<th width="120">Product condition</th>
<th width="120">Product age</th>
<th width="120">Product EAN</th>
<th width="120">Product ISBN</th>
<th width="120">Product ordernumber</th>
<th width="120">Product owners id</th>
<th width="60">Edit</th>
<th width="60">Delete</th>
</tr>
<c:forEach items="${listProducts}" var="product">
<tr>
<td>${product.productid}</td>
<td>${product.productimage} </td>
<td>${product.productname}</td>
<td>${product.productdescription}</td>
<td>${product.productcondition}</td>
<td>${product.productage}</td>
<td>${product.productean}</td>
<td>${product.productisbn}</td>
<td>${product.ordernumber}</td>
<td>${product.user1id}</td>
<img src="${image}" width="100" height="100"/> //image not found
<td><a href="<c:url value='/editproduct/${product.productid}' />" >Edit Product</a></td>
<td><a href="<c:url value='/removeproduct/${product.productid}' />" >Delete Product</a></td>
</tr>
<img src="${product.saveimage}" height="100" width="100">
</c:forEach>
</table>
</c:if>
Controller :
#RequestMapping(value="/product/show",method= RequestMethod.GET)
public String listProducts(#ModelAttribute("product") ProductBasic productBasic,Model model) {
User user = userService.getCurrentlyAuthenticatedUser();
model.addAttribute("product", new ProductBasic());
model.addAttribute("listProducts",this.productBasicService.listProduct(user));
BASE64Encoder base64Encoder = new BASE64Encoder();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("data:image/png;base64,");
stringBuilder.append(base64Encoder.encode(productBasic.getProductimage()));
String image = stringBuilder.toString();
model.addAttribute("saveimage",image);
return "product";
}
#RequestMapping(value="/product/add")
public String addProduct(#ModelAttribute("product") ProductBasic productBasic,Model model){
User user = userService.getCurrentlyAuthenticatedUser();
model.addAttribute("product", new ProductBasic());
productBasicService.addProduct(user,productBasic);
return "redirect:/product/show";
}
#RequestMapping("/removeproduct/{id}")
public String removeProduct(#PathVariable("id") int productid,Model model) {
User user = userService.getCurrentlyAuthenticatedUser();
model.addAttribute("listProducts",this.productBasicService.listProduct(user));
this.productBasicService.removeProduct(productid,user);
return "redirect:/product/show";
}
#RequestMapping("/editproduct/{id}")
public String updateProduct(#ModelAttribute("product") ProductBasic productBasic,#PathVariable("id") Integer id,Model model){
User user = userService.getCurrentlyAuthenticatedUser();
model.addAttribute("product", this.productBasicService.getProductById(id));
model.addAttribute("listProducts",this.productBasicService.listProduct(user));
return "product";
}
NullPointerException:
java.lang.NullPointerException
java.io.ByteArrayInputStream.<init>(ByteArrayInputStream.java:106)
sun.misc.CharacterEncoder.encode(CharacterEncoder.java:188)
com.WirTauschen.UserController.listProducts(UserController.java:67)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
What am I doing wrong? Kindly let me know.
In your Controller or method add below code for image
BASE64Encoder base64Encoder = new BASE64Encoder();
StringBuilder imageString = new StringBuilder();
imageString.append("data:image/png;base64,");
imageString.append(base64Encoder.encode(bytes)); //bytes will be image byte[] come from DB
String image = imageString.toString();
modelView.put("imagetoDisplay",image);// put in your model object for using in your JSP
And in your JSP
<img src="${imagetoDisplay}" width="100" height="100"/>
I'm learning Spring MVC with the tutorial of the site here
My question is basically in the code fragment bellow.
#RequestMapping(value = "/addContact", method = RequestMethod.POST)
public String addContact(#ModelAttribute("contact")
Contact contact, BindingResult result) {
System.out.println("First Name:" + contact.getFirstname() +
"Last Name:" + contact.getLastname());
return "redirect:contacts.html";
}
What should the value of #ModelAttribute be when just handling a POST request from a form submit?
Or in other words, what exactly does the "contact" value refers to in this situation?
The posted form is defined as follows:
<form:form method="post" action="addContact.html">
<table>
<tr>
<td><form:label path="firstname">First Name</form:label></td>
<td><form:input path="firstname" /></td>
</tr>
<tr>
<td><form:label path="lastname">Last Name</form:label></td>
<td><form:input path="lastname" /></td>
</tr>
<tr>
<td><form:label path="lastname">Email</form:label></td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td><form:label path="lastname">Telephone</form:label></td>
<td><form:input path="telephone" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Add Contact"/>
</td>
</tr>
</table>
</form:form>
I m trying to write spring mvc application with ajax and jquery and stuck at some point and not able to find solution since last 1 week..please help me out.
i want send request for showing all my users in database using ajax,see how i done
Show User List
now javascript ajax request
function doAjaxPost(id)
{ var submitId=id;
if(submitId=="showUserList")
{
$.ajax({
type: "POST",
url: "showUserList.html",
success: function(response){
// we have the response
if(response!='')
{
//alert(response);
//Not getting this $('#listofUser').html(response);
$("#homeDiv").hide();
$("#userListDiv").show("5");
}
},
error: function(e){
alert('Error: ' + e);
}
});
}
}
now see me controller
#RequestMapping(value="/showUserList",method = RequestMethod.POST)
public #ResponseBody ModelMap showUserList()
{
System.out.println("Ajax Request For user List");
List<UserDetails> userList=service.getAllUser();
ModelMap model=new ModelMap();
model.put("users", userList);
return model;
}
now see how i m displaying the user list on jsp page
<div id="listofUser">
<c:if test="${!empty users}">
<table id="rounded-corner" summary="List Of System Users">
<thead>
<tr>
<th scope="col" class="rounded-select">Select</th>
<th scope="col" class="rounded-id">ID</th>
<th scope="col" class="rounded-fname">Name</th>
<th scope="col" class="rounded-gender">Gender</th>
<th scope="col" class="rounded-username">UserName</th>
<!-- <th scope="col" class="rounded-password">Password</th> -->
<th scope="col" class="rounded-usertype">Type</th>
<th scope="col" class="rounded-userStatus">Status</th>
<th scope="col" class="rounded-Email">Email</th>
<th scope="col" class="rounded-address">Address</th>
<th scope="col" class="rounded-phno">PhoneNo.</th>
</tr>
</thead>
<form action="adminOperations.html" name="userListForm" onsubmit="return ConfirmOperation();" method="post">
<tbody>
<c:forEach items="${users}" var="users" varStatus="status">
<tr>
<td><input type="checkbox" value="${users.id}" id="select" name="select"/></td>
<td><c:out value="${users.id}" /></td>
<td><c:out value="${users.firstName}" /> <c:out value="${users.lastName}" /></td>
<td><c:out value="${users.gender}" /></td>
<td><c:out value="${users.userName}" /></td>
<%-- <td><c:out value="${users.userPassword}" /></td> --%>
<td><c:out value="${users.userType}" /></td>
<td><c:out value="${users.status}" /></td>
<td><c:out value="${users.emailId}" /></td>
<td><c:out value="${users.address}" /></td>
<td><c:out value="${users.contactNo}" /></td>
</tr>
</c:forEach>
</tbody>
<tfoot>
<tr>
<td colspan="12" class="rounded-foot-center" align="center">
<input type="submit" name="activate" id="activate" value="Activate" onClick="ButtonClicked(this);">
<input type="submit" name="deactivate" id="deactivate" value="Deactivate" onClick="ButtonClicked(this);">
<input type="submit" name="update" id="update" value="Update" onclick="ButtonClicked(this);">
<input type="submit" name="delete" id="delete" value="Delete" onclick="ButtonClicked(this);">
</td>
</tr>
</tfoot>
</form>
</table>
<br/>
</c:if>
<c:if test="${empty users}">
There are currently no user found.
</c:if>
</div>
.......................................................................
what i m not getting is , when response come from controller(ModelMap object in my case)
how would i pass model containing list of users to my jsp page so that it can display.
i tried
$('#listofUser').html(response); but it is not working,
i want model containing (model.put("users", userList);) users to be available from javascript to my display part..
please help me out.....
thanks and regards,
Hemant Singh
i am using spring mvc
public ModelAndView showUserList(HttpServletRequest request, HttpServletResponse response) throws Exception {
return new ModelAndView("GiveAnyName","users", userList);
}
Now you can get User List in JSP Page
List rows = (List) request.getAttribute("users");
#ResponseBody doesn't work like that, you should return a JSON and in order to display the content you can do it with jQuery but is a bit tricky, that's why I recommend to you AngularJS, forget JSTL.
Here there is a tutorial where SpringMVC, JSTL and asynchronous requests work together