I have a problem while creating a with a default value contained in my current object.
The value is correctly set in the field, but when I submit the form, the default value is still there, even if the user chose another value in the list...
Here is my controller :
#RequestMapping(method = RequestMethod.GET)
public String createForm(final ModelMap modelMap){
User user;
user = new User();
user.setGroup("HelpDesk");
user.setName("John");
ArrayList<String> groupList = new ArrayList<>();
groupList.add("Admin");
groupList.add("HelpDesk");
groupList.add("GroupManager");
groupList.add("Others");
modelMap.addAttribute("user", user);
modelMap.addAttribute("groupList", groupList);
return "/user/user-add";
}
#RequestMapping(method = RequestMethod.POST)
public String createUser(#ModelAttribute("user") final User user, BindingResult result) {
userValidator.validate(user, result, groupList);
logger.info(user.getGroup()); //Will print "HelpDesk,Admin" for instance
return "...";
}
And here is my JSP :
<table>
<form:form method="POST" modelAttribute="user">
<tr>
<td>Name:</td>
<td><form:input path="name"/></td>
<td><form:errors path="name" cssClass="error" /></td>
</tr>
<tr>
<td>Group:</td>
<td><form:select path="group" items="${groupList}" multiple="single"/></td>
<td><form:errors path="group" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</form:form>
</table>
For instance, if i choose "Admin" in the select list, i'll get "HelpDesk, Admin" in the property "group" of my user after submitting the form...
What am i doing wrong?
Thanks for your help!
Can I see your "POST" method or the "onSubmit" method? In your post method you must specify the User object as your model attribute or command.
Related
A number of questions regarding this error have been asked. But I could not find a solution.
This is my form :
<form:form id="flightSearchForm" modelAttribute="flightSearch" action="searchFlights"
method="post">
<table align="center">
<tr>
<td><form:label path="departureLocation">Departure Location: </form:label></td>
<td><form:input path="departureLocation" name="departureLocation" id="departureLocation" />
</td>
</tr>
<tr>
<td><form:label path="arrivalLocation">Arrival Location:</form:label></td>
<td><form:input path="arrivalLocation" name="arrivalLocation"
id="arrivalLocation" /></td>
</tr>
<tr>
<td><form:label path="flightDate">Flight Date</form:label></td>
<td><form:input type="date" path="flightDate" name="flightDate"
id="flightDate" /></td>
</tr>
<tr>
<td><form:label path="flightClass">Flight Class</form:label></td>
<td><form:select path="flightClass" name="flightClass"
items = "${flightClasses}" id="flightClass" /></td>
</tr>
<tr>
<td><form:label path="outputPreference">Output Preference</form:label></td>
<td><form:select path="outputPreference" name="outputPreference"
items = "${outputPreferences}" id="outputPreference" /></td>
</tr>
<tr>
<td></td>
<td align="left"><form:button id="search" name="search">Search</form:button>
</td>
</tr>
</table>
</form:form>
This is my controller :
#Controller
public class FlightSearchController {
#RequestMapping(value = "/welcome" ,method = RequestMethod.GET)
public ModelAndView showWelcomePage()
{
ModelAndView mav = new ModelAndView();
mav.addObject("flightSearch", new FlightSearch());
mav.setViewName("welcome.jsp");
return mav;
}
#RequestMapping(value = "/searchFlights" ,method = RequestMethod.POST)
public ModelAndView searchForFlights(#ModelAttribute("flightSearch") FlightSearch flightSearch)
{
ModelAndView mav = new ModelAndView();
mav.addObject("depLoc", flightSearch.getDepartureLocation());
mav.addObject("arrivalLocation", flightSearch.getArrivalLocation());
mav.addObject("flightDate",flightSearch.getFlightDate());
mav.setViewName("flightDetails.jsp");
return mav;
}
}
I have tried almost every solution mentioned here but could not solve the issue. I'm new to Spring, so please help if possible. Any help would be appreciated.
I think you need to add #SessionAttributes("flightSearch") on your controller.
The model object will be, behind the scene, bound to the session after the get, and can then be retrieved in the post.
You need to clean the session afterwards in the post method, using SessionStatus.setComplete (or something like that).
You just need to add SessionStatus to the post method parameters.
This is how you implement 'get and post' form workflow in spring mvc I think.
As You have mentioned in the comment you are redirecting.
Assuming that your above jsp code is 'welcome.jsp'
It seems Like you are redirecting it to jsp page instead of RequestMapping value
Try This:
ModelAndView mv=new ModelAndView();
mv.setViewName("redirect:welcome"); //Code Should added where you redirecting the login page to search page
I'm trying to make a CRUD application using Spring MVC, but whenever I click the edit button to update an entry in a row, my jsp page to edit an entry (wizardeditform.jsp) has the 'designation' and 'wand' inputs filled in from that entry with the correct values. I would like all the input boxes to have the default values from that row, not just the 'wand' and 'designation' input boxes. Does anyone have any idea why this is happening? (Ive been following this tutorial: http://www.javatpoint.com/spring-mvc-crud-example)
wizardeditform.jsp
<h1>Edit Witch or Wizard</h1>
<form:form method="POST" action="/WizardingWorld/editsave">
<table>
<tr>
<td></td>
<td><form:hidden path="id" /></td>
</tr>
<tr>
<td>First name :</td>
<td><form:input path="firstname"/></td>
</tr>
<tr>
<td>Last name :</td>
<td><form:input path="lastname" /></td>
</tr>
<tr>
<td>Designation :</td>
<td><form:input path="designation"/></td>
</tr>
<tr>
<td>School and house :</td>
<td><form:input path="schoolAndHouse" /></td>
</tr>
<tr>
<td>wand :</td>
<td><form:input path="wand" /></td>
</tr>
<tr>
<td>Blood Type</td>
<td><form:input path="bloodtype" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Save" /></td>
</tr>
</table>
</form:form>
Controller class
// displays form to input data, "command" is request attr. used to display
// object data into form
#RequestMapping("/wizardform")
public ModelAndView showform() {
return new ModelAndView("wizardform", "command", new Wizard());
}
// saves object into database. The #ModelAttribute puts request data into
// model object.
#RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(#ModelAttribute("wizard") Wizard wizard) {
dao.save(wizard);
return new ModelAndView("redirect:/viewwizard");// will redirect to
// viewwizard request
// mapping
}
// provides list of employees in model object
#RequestMapping("/viewwizard")
public ModelAndView viewwizard() {
List<Wizard> list = dao.getWizards();
return new ModelAndView("viewwizard", "list", list);
}
// It displays object data into form for the given id. The #PathVariable
// puts URL data into variable
#RequestMapping(value = "/editwizard/{id}")
public ModelAndView edit(#PathVariable int id) {
Wizard wizard = dao.getWizardById(id);
return new ModelAndView("wizardeditform", "command", wizard);
}
// updates model object
#RequestMapping(value = "/editsave", method = RequestMethod.POST)
public ModelAndView editsave(#ModelAttribute("wizard") Wizard wizard) {
dao.update(wizard);
return new ModelAndView("redirect:/viewwizard");
}
The first image is the jsp page to view all the table entries, and the second image is is the wizardeditform.jsp , right after clicking the edit button on the previous page with all the entries.
This is my customer JSP page in which the commandName is given as "customerForm":
<form:form method="POST" commandName="customerForm">
<table>
<tr>
<td>UserName : </td>
<td><form:input path="userName" /></td>
<td><form:errors path="userName" cssClass="error" /></td>
</tr>
<tr>
<td>Password : </td>
<td><form:password path="password" /></td>
<td><form:errors path="password" cssClass="error" /></td>
</tr>
</table>
</form:form>
This is my Controller class which is using the Customer POJO :
#RequestMapping(method = RequestMethod.POST)
public String processSubmit(
#ModelAttribute("customerForm") Customer customer,
BindingResult result, SessionStatus status) {
customerValidator.validate(customer, result);
if (result.hasErrors()) {
//if validator failed
return "CustomerForm";
} else {
status.setComplete();
//form success
return "CustomerSuccess";
}
}
#RequestMapping(method = RequestMethod.GET)
public String szdfsdf(ModelMap model){
Customer cust = new Customer();
model.addAttribute("customerForm", cust);
//return form view
return "CustomerForm";
}
Error am getting is :
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'customerForm' available as request attribute
When i have given CommandName="customer" it is working fine. even though the name of ModelAttribute and CommandName is different .
I asked a question earlier how to do this using Webflow, but it has proven to be impractical for my situation.
I am trying to have a walk through 3 screens which add to an object information and then require a confirm to add to the database at the end. [To maintain simplicity etc]
The first screen takes in username for example
then the next screen requires contact information
then the third screen shows a summary and asks to confirm
I am having trouble figuring out how to pass the same object through several screens. I understand how to pass information from one screen to next, but for some reason same technique doesn’t work through several screens.
Sample 3 pages:
AddUser.jsp
<div id="form">
<h2 >Step 1</h2>
<form action="AddUserContact" method="post">
<table>
<tr>
<td>User Name:</td>
<td><input type="text" id="username" name="username"/></td>
</tr>
<tr>
<td><input type="submit" value="Next"/></td>
</tr>
</table>
</form>
</div>
AddUserContact.jsp
<div id="form">
<h2 >Step 2</h2>
<form action="UserSummaryConfirm" method="post">
<table>
<tr>
<td>${user.username}</td>
</tr>
<tr>
<td>Address:</td>
<td><input type="text" id="address" name="address"/></td>
</tr>
<tr>
<td><input type="submit" value="Next"/></td>
</tr>
</table>
</form>
</div>
UserSummaryConfirm.jsp
<h2>Step 3</h2>
<form action="home" method="post">
<table>
<tr>
<td>User Name:</td>
<td>${user.username}</td>
</tr>
<tr>
<td>Address:</td>
<td>${address}</td>
</tr>
<tr>
<td>Confirm</td>
</tr>
</table>
</form>
I have a Controller for every page [its for me to understand better what is going on, Ill simplify it later]
AddUserController.java
#Controller
public class AddUserController{
#RequestMapping(value = "AddUser")
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
User user = new User();
ModelAndView mav = new ModelAndView("AddUser");
user.setUserName(request.getParameter("username"));
mav.addObject("user", user);
return mav;
}
}
AddUserContactController.java
#Controller
public class AddUserContactController{
#RequestMapping(value = "AddUserContact")
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("AddUserContact");
mav.addObject("user", request.getParameter("user"));
return mav;
}
}
AddUserConfirm.java
#Controller
public class AddUserConfirm{
#RequestMapping(value = "UserSummaryConfirm")
public ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView("UserSummaryConfirm");
mav.addObject("user", request.getParameter("user"));
mav.addObject("address", request.getParameter("address"));
return mav;
}
}
And then the User class is just a simple class with getters and setters.
The problem I am having is no matter what I have tried to pass the object, I cannot seem to figure out why the same technique doesnt work.
The address on the third screen is beeing displayed no problem, but the username is not displayed on any of the screens.
With the webflow the way I did it was created a UserBean that was global to all webflow screens. It was easy to add to the same object from any screen and display any information. How can I achieve the same result for this?
Thank you.
WORKING CODE:
Using SessionAttributes
AddUser.jsp
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<div id="form">
<h2 >Step 1</h2>
<form:form action="AddUserContact" commandName="user" method="POST">
<table>
<tr>
<td>User Name:</td>
<td><form:input type="text" id="username" path="username"/></td>
</tr>
<tr>
<td><input type="submit" value="Next"/></td>
</tr>
</table>
</form:form>
</div>
AssUserContact.jsp
<div id="form">
<h2 >Step 2</h2>
<form:form action="UserSummaryConfirm" commandName="user" method="post">
<table>
<tr>
<td>Address:</td>
<td><input type="text" id="address" path="address"/></td>
</tr>
<tr>
<td><input type="submit" value="Next"/></td>
</tr>
</table>
</form>
</div>
UserSummaryConfirm.jsp
<h2>Step 3</h2>
<form:form action="home" method="get">
<table>
<tr>
<td>User Name:</td>
<td><%=session.getAttribute("username")%></td>
</tr>
<tr>
<td>Address:</td>
<td><%=session.getAttribute("address")%></td>
</tr>
<tr>
<td>Confirm</td>
</tr>
</table>
</form:form>
AddUserController.java
#Controller
#SessionAttributes({ "username", "address" })
public class AddUserController{
User usr = new User();
#RequestMapping(value = "AddUser")
public String loadIndex(Model model, User user) {
model.addAttribute("User", user);
return "AddUser";
}
#RequestMapping(value = "AddUserContact")
public String processUserName(Model model, User user) {
usr.setUsername(user.setUsername());
model.addAttribute("User", user);
return "AddUserContact";
}
#RequestMapping(value = "UserSummaryConfirm")
public String processUserContact(Model model, User user) {
usr.setAddress(user.getAddress());
model.addAttribute("username", usr.getUsername());
model.addAttribute("address", usr.getAddress());
return "UserSummaryConfirm";
}
Because in second screen you are using
<tr>
<td>${user.username}</td>
</tr>
User input is not bind to any input so it will not be passed to controller with form data .
While you are using address as
<tr>
<td>Address:</td>
<td><input type="text" id="address" name="address"/></td>
</tr>
As it is bind to input (as you have assigned name="address" which is same as path="name") so its value will be send to controller.
If you want to pass the same object across 3 screens then it's better use #SessionAttribute instead of hiding it and passing again and again.
EDIT :
As you are using session attribute now, remove input element .(which is bind to username) from second screen. Just use instead
<td>session.getAttribute("username")%></td>
I have done a "wizard-style" form like this before. My solution used a single form bean that we put into session for the entire process, and included only the pieces in each page that needs to be added. Spring will not erase a value in the form bean unless you include an input for the given value. We don't use JSR-303, and I don't think this method would work if you are using it. Our validation uses a combination of BindingErrors and custom validation code, so I just setup the code to only validate portions at a time, corresponding to what page the form just submitted.
How to remove some of the "magic value" impression of "command" modelName parameter to create a ModelAndView ?
Example:
#RequestMapping(value = "/page", method = GET)
public ModelAndView render() {
return new ModelAndView("page", "command", new MyObject());
}
One hope was to use a spring constant such as
new ModelAndView("page", DEFAULT_COMMAND_NAME, new MyObject());
I found "command" in the 3 following classes of the spring-webmvc-3.0.5 sources jar:
$ ack-grep 'public.*"command"'
org/springframework/web/servlet/mvc/BaseCommandController.java
140: public static final String DEFAULT_COMMAND_NAME = "command";
org/springframework/web/servlet/mvc/multiaction/MultiActionController.java
137: public static final String DEFAULT_COMMAND_NAME = "command";
org/springframework/web/servlet/tags/form/FormTag.java
56: public static final String DEFAULT_COMMAND_NAME = "command";
The problem is :
BaseCommandController is deprecated
We don't use MultiActionController and FormTag
When you use on your jsp spring tag <form:form>
<form:form method="POST" action="../App/addCar">
<table>
<tr>
<td><form:label path="brand">Name</form:label></td>
<td><form:input path="brand" /></td>
</tr>
<tr>
<td><form:label path="year">Age</form:label></td>
<td><form:input path="year" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form:form>
you must write:
#RequestMapping(value = "/car", method = RequestMethod.GET)
public ModelAndView car() {
return new ModelAndView("car", "command", new Car());
}
Because the spring framework expects an object with name "command".
Default command name used for binding command objects: "command".
This name to use when binding the instantiated command class to the request.
http://static.springsource.org/spring/docs/1.2.9/api/org/springframework/web/servlet/mvc/BaseCommandController.html
But when you use html form <form> you can write:
#RequestMapping(value = "/car", method = RequestMethod.GET)
public ModelAndView car() {
return new ModelAndView("car", "YOUR_MODEL_NAME", new Car());
}
But on your page
<form method="POST" action="../App/addCar">
<table>
<tr>
<td><form:label path="YOUR_MODEL_NAME.brand">Name</form:label></td>
<td><form:input path="YOUR_MODEL_NAME.brand" /></td>
</tr>
<tr>
<td><form:label path="YOUR_MODEL_NAME.year">Age</form:label></td>
<td><form:input path="YOUR_MODEL_NAME.year" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
I wouldn't use the default name. If the object is a User call it user, if it's Item call it item. If you need a default (for example - for a generic framework), define your own constant.