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 .
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.
I am having some issues with my form validation.
Controller:
#RequestMapping(value = REGISTER_URL, method = RequestMethod.POST)
public String registerPost(#Valid RegisterForm registerForm,
BindingResult result) {
if (result.hasErrors()) {
return REGISTER_VIEW;
}
System.out.println(registerForm.getPassword());
return LOGIN_VIEW;
}
View:
<form:form action="register" commandName="registerForm" method="post">
<table>
<tr>
<td>Username:</td>
<td><form:input path='username' /></td>
<td><form:errors path="username"/></td>
</tr>
<tr>
<td>Password:</td>
<td><form:password path='password'/></td>
<td><form:errors path="password"/></td>
</tr>
<tr>
<td>Repeat password:</td>
<td><form:password path='repeatedPassword'/></td>
<td><form:errors path="repeatedPassword"/></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"> <input name="reset" type="reset"></td>
</tr>
</table>
</form:form>
Form:
public class RegisterForm {
#Size(min = 3, max = 15)
private String username;
#Size(min = 5)
private String password;
#Size(min = 5)
private String repeatedPassword;
// getters and setters omitted
}
When i enter empty values (username, password and repeatedPassword) then no errors occurs (i have checked it using debugger). So it looks like no validation is performed. Binding values from view is ok (checked using debugger) Any ideas what might be wrong?
Add following content into your context:
<mvc:annotation-driven />
<context:component-scan base-package="xxx.xxx.xxx" />
In the guide, they use "#SpringBootApplication"
http://spring.io/guides/gs/validating-form-input/
The #SpringBootApplication annotation is equivalent to using #Configuration, #EnableAutoConfiguration and #ComponentScan with their default attributes:
http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html
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.
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.