"command" modelName magic value in spring MVC 3 - java

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.

Related

Neither BindingResult nor plain target object for bean name 'flightSearch' available as request attribute

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

Spring MVC/Hibernate/MySQL 400 Bad Request Error

I'm building a blog in Java using Spring and Hibernate. I can't seem to figure out what is going on but I keep running into a Bad Request error when I try to add (save) a post and I can't figure out where I am wrong in my mapping.
Error message:
Controller:
#Controller
#RequestMapping("/blog")
public class IndexController {
#Autowired
private PostService postService;
#RequestMapping("/list")
public String showPage (Model theModel) {
// get posts from DAO
List<Post> thePosts = postService.getAllPosts();
// add the posts to the model
theModel.addAttribute("allPosts", thePosts);
return "allPosts";
}
#GetMapping("/showFormForAdd")
public String showFormForAdd(Model theModel) {
//create model attribute to bind form data
Post thePost = new Post();
theModel.addAttribute("post", thePost);
return "postSuccess";
}
#PostMapping("/savePost")
public String savePost(#ModelAttribute("post") Post thePost) {
// save the post using our service
postService.savePost(thePost);
return "allPosts";
}
Form snippet:
<div class="table" id="container">
<form:form action="savePost" modelAttribute="post"
method="POST">
<table>
<tbody>
<tr>
<td><label>Title:</label></td>
<td><form:input path="title" /></td>
</tr>
<tr>
<td><label>Author:</label></td>
<td><form:input path="author" /></td>
</tr>
<tr>
<td><label>Date:</label></td>
<td><form:input path="date" /></td>
</tr>
<tr>
<td><label>Post:</label></td>
<td><form:input path="post" /></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="Save"></td>
</tr>
</tbody>
</table>
</form:form>
<div style="clear: both;"></div>
<p>
Back to Home Page
</p>
</div>
All other pages are working correctly so far, just can't add an actual blog post. Any help is greatly appreciated.
I figured this out and it is similar to another spring issue I had in the past.
I don't think this really follows a lot of conventional function/design theory, but I added some code into the controller and it now works. I can add a post easily.
First thing was, I removed the #ModelAttribute tag from my "savePost" method. Then I added #RequestParam to my method parameters. Added a little bit of logic and now it saves to the database and then appears on the blog. Good stuff.
Code:
#PostMapping("/savePost")
public String savePost(#RequestParam("author") String author,
#RequestParam("title") String title, #RequestParam("date") String date,
#RequestParam("post") String post) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date theDate = sdf.parse(date);
// save the customer using our service
Post thePost = new Post();
thePost.setAuthor(author);
thePost.setDate(theDate);
thePost.setTitle(title);
thePost.setPost(post);
postService.addPost(thePost);
System.out.println(thePost.toString()); //testing
return "success";
}
jsp:
<form:form action="savePost" modelAttribute="post" method="POST">
<table>
<tbody>
<tr>
<td><label>Title:</label></td>
<td><input id="title" type="text" name="title"></td>
</tr>
<tr>
<td><label>Author:</label></td>
<td><input id="author" type="text" name="author"></td>
</tr>
<tr>
<td><label>Date:</label></td>
<td><input id="date" type="text" name="date"></td>
</tr>
<tr>
<td><label>Post:</label></td>
<td><textarea id="post" type="text"
name="post"></textarea></td>
</tr>
<tr>
<td><label></label></td>
<td><input type="submit" value="Save"></td>
</tr>
</tbody>
</table>
</form:form>

Set a default value inside an input box, crud application using spring

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.

Spring MVC pass model to view then to controller

I'm stuck with my code, I'm trying to pass the info of the object "Student". My scenario is like this:
Registration Form (fill the details then press submit button go to next page)
From this view the model will be printed out then press the next button again.
This third page will just show the information again.
Q: How can i pass the same object and display it to other views?
My code is like this.
Registration view:
<form action="/HamburgerProject/stuSubmitAdmissionForm.html" method="post">
<table>
<tr>
<td>Name:</td> <td><input type="text" name="studentName"></td></tr>
<tr>
<td>Age:</td> <td><input type="text" name="studentAge"></td></tr>
<tr>
</table>
<input type="submit" value="submit this">
</form>
First Information View:
<form action="/HamburgerProject/stuSubmitAdmissionForm.html" method="post">
<table>
<tr>
<td>Student's Name :</td>
<td>${student.studentName}</td>
</tr>
<tr>
<td>Student's Age :</td>
<td>${student.studentAge}</td>
</tr>
</table>
<input type="submit" value="send"/>
</form>
Second Information View:
<table>
<tr>
<td>Student's Name :</td>
<td>${student.studentName}</td>
</tr>
<tr>
<td>Student's Age :</td>
<td>${student.studentAge}</td>
</tr>
</table>
My Controller:
#RequestMapping(value="/stuAdmissionForm.html", method = RequestMethod.GET)
public ModelAndView getStudentAdmissionForm() {
ModelAndView model = new ModelAndView("AdmissionForm");
return model;
}
#RequestMapping(value="/stuSubmitAdmissionForm.html", method = RequestMethod.POST)
public ModelAndView submitModelAttributeAnnotationAdmissionForm(#ModelAttribute("student") Student student) {
ModelAndView model = new ModelAndView("AdmissionSuccess");
return model;
}
#RequestMapping(value="/stuDisplayForm.html", method = RequestMethod.POST)
public ModelAndView getStudent(Student student) {
ModelAndView model = new ModelAndView("NewForm");
model.addObject(student);
return model;
}
In attempting to re-display the information from second view to third view the object Student is not being passed.
There are no fields to submit in your fist information view. You have to add the values to hidden fileds:
<form action="/HamburgerProject/stuSubmitAdmissionForm.html" method="post">
<table>
<tr>
<td>Student's Name :</td>
<td>${student.studentName}</td>
</tr>
<tr>
<td>Student's Age :</td>
<td>${student.studentAge}</td>
</tr>
</table>
<input type="hidden" name="studentName" value="${student.studentName}">
<input type="hidden" name="studentAge" value="${student.studentAge}">
<input type="submit" value="send"/>
</form>

Default value in select still there after submit

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.

Categories

Resources