Spring, modelmap, getting attributes from the jsp - spring

I develop an MVC application with spring framework and some other frameworks (and I'm a beginner). I have a controller to manage jsp handling, for example when I want add new person to my 'person list' I call a instantiate a person object and I pass it to the jsp view corresponding to the add method. And I do that by this a method like this:
#RequestMapping(value = "/persons/add", method = RequestMethod.GET)
public String getAdd(Model model) {
logger.debug("Received request to show add page");
// Create new UserDomain and add to model
// This is the formBackingOBject
model.addAttribute("personAttribute", new UserDomain());
// This will resolve to /WEB-INF/jsp/addpage.jsp
return "addpage-tiles";
}
My problem is that now, I want to pass to add to the model two different Objects, for example, I want to pass the 'new UserDomain()' and also an other object which is from an other table in my database, for example a 'new UserSecurity()'.
I think I should use a 'modelMap' instead of the 'model.addAttribute...', but I can't do this, so if someone could help me.
I get my model from the jsp by a code like :
<form:form modelAttribute="personAttribute" method="POST" action="${saveUrl}">
<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="userName">User name</form:label></td>
<td><form:input path="userName"/></td>
</tr>
<tr>
<td><form:label path="email">E-mail</form:label></td>
<td><form:input path="email"/></td>
</tr>
</table>
<input type="submit" value="Save" />
thank you a lot for helping me.

Simply passing more than one object to the view is not a problem -- just use model.addAttribute multiple times, and then you can access both objects.
However, if you want to edit more than one model in <form:form> you'll need to create a class that contains both of the objects:
public class UserDomainSecurity {
private UserDomain userDomain;
private UserSecurity userSecurity;
// getters and setters for both
}
Then pass an instance of this into the view:
model.addAttribute("userDomainSecurity", new UserDomainSecurity());
And use it in the form:
<form:form commandName="userDomainSecurity" method="POST" action="${saveUrl}">
...
<form:input path="userDomain.firstName"/>
....
<form:input path="userSecurity.someSecurityProperty"/>
It's sometimes annoying to have to create all these additional classes, but it is somewhat logical. The wrapper class creates kind of namespaces in the form and thus separates the individual objects that you want to edit.

I wanted to add on this as it's really the present problem I have encountered minutes ago.
In this case, I assumed that you're UserSecurity and UserDomain are relative to each other.
Let say you have,
public class UserDomain {
public UserSecurity userSecurity
public String firstName;
public String lastName;
// getters and setters...
}
and you have your UserSecurity something like,
public class UserSecurity {
public String someSecurityProperty;
// getters and setters...
}
Since userSecurity property can be accessed publicly, then you can just do what you have did in your Controller,
#RequestMapping(value = "/persons/add", method = RequestMethod.GET)
public String getAdd(Model model) {
logger.debug("Received request to show add page");
// Create new UserDomain and add to model
// This is the formBackingOBject
model.addAttribute("userDomainSecurity", new UserDomain());
// This will resolve to /WEB-INF/jsp/addpage.jsp
return "addpage-tiles";
}
then just access it in your addpage.jsp like it's an object property like below,
<form:form commandName="userDomainSecurity" method="POST" action="${saveUrl}">
...
<form:input path="firstName />
<form:input path="lastname />
....
<form:input path="userSecurity.someSecurityProperty"/>
as you notice, I access the someSecurityProperty by the property declared in UserDomain class.

Related

Mapping to List Object in Spring MVC when Page is not displayed by a Controller

I am trying to map the value from Front end to Back Bean which is a List. Now the problem is that the page/view is not displayed by a Spring controller it is a jsp which is being displayed by CMS(content management system). So I cant initialse List and add elements to it and pass as a mode attribute
This is how my bean looks
public class LodgingAvailabilityRequest implements Serializable
{
private List<GuestCount> guestCounts = new ArrayList<GuestCount>();
public List<GuestCount> getGuestCounts() {
return guestCounts;
}
public void setGuestCounts(List<GuestCount> guestCounts) {
this.guestCounts = guestCounts;
}
and the GuestCount has the count field
public class GuestCount implements Serializable
{
private Double count;
this is how my JSP looks like
<jsp:useBean id="lodgingAvailability" class="com.pegasus.gen.LodgingAvailabilityRequest" scope="request"/>
<jsp:useBean id="guestCount" class="com.pegasus.gen.GuestCount" scope="request"/>
<body>
<form:form method="POST" action="/lodgingbyroom" modelAttribute="lodgingAvailability">
<table>
<tr>
<td>Count: <form:input path=guestCounts[0].count /></td>
</tr>
<td><input type="submit" value="Submit lodgingAvailability request by ROOM type"/></td>
</tr>
</table>
</form:form>
Now using above code gives me Array Out of Bounds exception so I tried couple of things as mentioned in some other posts
Changed to this <td>Count: <form:input path="${guestCounts[0].count}" /></td> I dont get any compilation error but the vaue in controller is not getting mapped. The list is empty.
Added a for loop but this didnt work as expected since the list is empty and it wont enter the loop.
<c:forEach items="${lodgingAvailability.guestCounts}" varStatus="counter">
<tr>
<td>Count: <form:input path="guestCounts[${counter.index}].count" /></td>
</tr>
</c:forEach>
This is how my controller looks, where the form gets submitted
#RequestMapping(value = "/lodgingbyroom", method = RequestMethod.POST)
public String lodgingAvailabilityByRoom(ModelMap model, LodgingAvailabilityRequest request,
RedirectAttributes redirectAttributes) {
final RestTemplate restTemplate = new RestTemplate();
final Map<String, List<DXARoom>> groupByRoom = restTemplate
.postForEntity(pegasusPath + "/lodgingbyroom", request, Map.class).getBody();
redirectAttributes.addFlashAttribute("pegasusResponse", groupByRoom);
}
I was able to Fix the above problem. Since the list was not having any elements in it the only way to make it work is add a dummy element to list. So you can traverse the list and then map the values
<% lodgingAvailability.getGuestCounts().add(guestCount) ;%>
<% lodgingAvailability.getGuestCounts().add(guestCount) ;%>
<c:forEach items="${lodgingAvailability.guestCounts}" varStatus="counter">
<tr>
<td>Count: <form:input path="guestCounts[${counter.index}].count" /></td>
</tr>
</c:forEach>
for this piece of code to work make sure that you declare the beans
<jsp:useBean id="lodgingAvailability" class="com.pegasus.gen.LodgingAvailabilityRequest" scope="request"/>
<jsp:useBean id="guestCount" class="com.pegasus.gen.GuestCount" scope="request"/>

#ModelAttribute and abstract class

I know that there have been similar questions. The examples given in them are too fragmentary and unclear.
I need to edit the entities through a form on the page that sends the POST. The standard method is a method in the controller uses the parameter with #ModelAttribute and validator. If one form serves some subclass of an abstract class, there are no problems with the generation of the necessary fields, but there is a problem in the controller.
As I understand it, #ModelAttribute works this way: it initializes the desired object class, and then collects his fields of the parameters of the request. Of course, if the object is an abstract class, it can not be initialized. Therefore, the form has a field that will indicate what subclass to initialize. Next, we need peace of code, that will read this attribute and initialize the correct subclass. What should it be? I saw fragmentary examples about the Converter, PrepertyEditor, WebDataBinder, but difficult to put everything together.
So. There are the following hierarchy:
public abstract class Person {role, name, email, password ...}
public class Student extends Person {}
public class Lecturer extends Person {}
There is a controller and methods in it:
#RequestMapping (Path = "/ persons / uid {personId} / edit",
method = RequestMethod.GET)
public String editPerson (#PathVariable Integer personId, Model model) {
Person find = personDAO.read (personId);
model.addAttribute ( "person", find);
return "editPerson";
}
#RequestMapping (Path = "/ persons / uid {personId} / edit",
method = RequestMethod.POST)
public String editPersonPost (#PathVariable Integer personId,
#Valid #ModelAttribute ( "Person") Person person,
BindingResult result) {
if (result.hasErrors ()) return "editPerson error = true?";
personDAO.update (person);
return "redirect: / persons / uid" + personId + "saved = true?";
}
And there is a JSP with a form:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<h1>${person.name}</h1>
<form:form action="edit" method="post" commandName="person">
<input type="hidden" value="${person.role}" name="person_type" />
<table>
<tr>
<td>Password</td>
<td><form:input path="httpAuth.password" type="password"/></td>
<td><form:errors path="httpAuth.password" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>Email</td>
<td><form:input path="email" /></td>
<td><form:errors path="email" cssClass="error"></form:errors></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save"></td>
<td></td>
</tr>
</table>
</form:form>
Also, the converter has been written, but I doubt whether it is necessary, or else do it (inheriting another class ...)
public class PersonConverter implements Converter <String, Person> {
public Person convert (String personType) {
Person person = null;
switch (personType) {
case "Student":
person = new Student ();
break;
case "Lecturer":
person = new Lecturer ();
break;
default:
throw new IllegalArgumentException (
"Unknown person type:" + personType);
}
return person;
}}
Which is registered with ConversionService
<bean class="org.springframework.context.support.ConversionServiceFactoryBean"
id="theConversionService">
<property name="converters">
<list>
<bean class="schedule.service.PersonConverter"></bean>
</list>
</property>
</bean>
<mvc:annotation-driven conversion-service="theConversionService" validator="validator"/>
Nevertheless, something is missing, that is a method that will take person_type from request parameters and give it to converter, and it will return a result of the method the controller via the automatic binding mechanisms.
Help me please.
You just need to ensure that the element below
<input type="hidden" value="${person.role}" name="person_type" />
has its named attribute changed to person
<input type="hidden" value="${person.role}" name="person" />
so that it matches the model attribute in your controller
public String editPersonPost (#PathVariable Integer personId,
#Valid #ModelAttribute ( "person") Person person,
BindingResult result)
This is how it works.
When a request is received and Spring needs to create the model attribute it checks if the attribute already exists. If it doesn`t exist and there is no request parameter of matching name it creates a new object using the default constructor of the parameter class
If it exists and matches the argument type it proceeds to bind the request parameters. If it is not compatible or a request parameter of same name is available it tries to find a converter capable of converting the current value to the required type
If conversion is successful it binds the request parameters to the result otherwise it throws an Exception
In your case the person attribute is sent as a String. Spring will attempt to convert it to a Person. It picks your PersonConverter to do the conversion to an appropriate subclass before binding

Replace only selected fields using binding

I'm building simple twitter clone in Spring MVC. I want to provide edit functionality to posted messages.
Message domain object looks like this (simplified)
public class Message {
long id;
String text;
Date date;
User user;
}
I created jps form
<form:form action="edit" method="post" modelAttribute="message">
<table>
<tr>
<td><label for="text">Message: </label></td>
<td><form:textarea path="text" id="text"/></td>
</tr>
<tr>
<td><input type="submit" name="commit" value="Save" /></td>
</tr>
</table>
</form:form>
and added those method in controller class
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public String showEditMessage(#RequestParam long id, Model model) {
Message message = messageService.findMessage(id);
if (message == null) {
return "404";
}
model.addAttribute("message", message);
return "users/editMessage";
}
#RequestMapping(value = "/edit", method = RequestMethod.POST)
public String editMessage(#Valid #ModelAttribute Message message, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "/users/editMessage";
}
messageService.updateMessage(message);
return "/users/editMessage";
}
The problem is that the Message received in editMessage() contains only text field. I assume that this is expected behaviour. Can it be configured to replace fields that are only in jsp form?
I know this is only one field and I could just use #RequestParam String message, but sooner or later I will face similar problem with more than just one field.
I also have side question.
Are attributes added in showEditMessage() are passed to editMessage() method? I tried to add "id" attribute in first method, but I couldn't retrive it using "#RequestParam long id" in second.
#SessionAttributes("message")
On top of controller class solved it.

Getting NumberFormatException while getting the value in JSP using JSTL

I am working on Spring/Hibernate sample web application. Actually, I am trying to load the employees from database. In this case, while getting the data from database for both employee and address tables i am getting the NumberFormat exception.
Following is the code i am working on,
JSP Code:
<c:if test="${!empty employeeList}">
<table class="data">
<c:forEach items="${employeeList}" var="emp">
<tr>
<td><c:out value="${emp.firstname}" /></td>
<td><c:out value="${emp.lastname}" /></td>
<td><c:out value="${emp.email}" /></td>
<td>Edit</td>
<td>Delete</td>
</tr>
</c:forEach>
Controller Code:
#RequestMapping(value = "/", method = RequestMethod.GET)
public String listEmployees(ModelMap map)
{
map.addAttribute("employeeList", employeeManager.getAllEmployees());
return "editEmployeeList";
}
Service Layer Code:
#Override
#Transactional
public List<EmployeeEnitity> getAllEmployees() {
return employeeDAO.getAllEmployees();
}
public List<EmployeeEntity> getAllEmployees() {
return this.sessionFactory.getCurrentSession().createQuery("select ee.firstname,ee.lastname,addr.email from " +
"com.howtodoinjava.entity.EmployeeEntity ee, com.howtodoinjava.entity.AddressEntity addr where ee.id=addr.id").list();
}
Please help me to resolve this exception
The return type of session.createQuery(String).list() in your service method getAllEmployees is List<Object[]>, it is not List<Employee>
In controller you are adding this List<Object[]> to your model at this line:
map.addAttribute("employeeList",employeeList);
Now in JSP you are trying to access the model object in JSTL forEach loop:
<c:forEach items="${employeeList}" var="emp">
As employeeList represents List<Object[]>, the variable emp represents Object[], it is not Employee. Now using dot (.) operator on variable emp means you are trying to access an element at a particular index position. For example:
emp.0 --> is same as emp[0]
emp.1 --> is same as emp[1]
emp.indexPosition --> is same as emp[indexPosition]
So when you say emp.firstName, then the firstName is converted to integer, as firstName is not an integer you are getting NumberFormatException

how to read the already existing bean in jstl|form?

I have simple form with SpringMVC, I want retrieve my already had bean by pbid. the problem is the server side I can get the already setting bean, but the jsp side it always get new bean. Can I use the #ModelAttribute("productbean") to received some parameters to get the bean store in my server-side? how to do it? The jstl|form seem always get new form
<form:form method="post" modelAttribute="productbean" action="">
<table>
</tr>
<tr>
<td width="118"><form:label for="name" path="name" > Production Name:</form:label></td>
<td colspan="2"><form:hidden path="pbid"/><form:input path="name" type="text" size="50" /></td>
</tr>
...
My controler is like:
#RequestMapping(value="/createproduct", method=RequestMethod.GET)
public String getProduct(HttpServletRequest req, Model model,
#RequestParam(value = "pbid", required = false, defaultValue = "") String spbid) throws MalformedURLException {
UUID pbid;
if(spbid.isEmpty())pbid=UUID.randomUUID();
else pbid=UUID.fromString(spbid);
ProductBean tmp;
if(!products.containsKey(pbid)){
tmp=createbean();
pbid=tmp.getPbid();
System.err.println("============new productbean===============\n");
}else{
tmp=products.get(pbid);
System.err.println(tmp.getMpf().size());
System.err.println(tmp.getMpf().printFileNameList());
}
.....
#ModelAttribute("productbean")
public ProductBean createbean(){
ProductBean productbean=new ProductBean(context.getRealPath(filepath));
products.put(productbean.assignID(), productbean);
return productbean;
}
Add session attribute annotation over class
#SessionAttributes("productbean")
#controller
public class test() {
}

Resources