How does Spring bind form values into class variables? - spring

If I use a form:form object in Spring, I can use the commandName in order to let Spring inject the class variable values.
However, I wonder, how does the controller catch this value?
#RequestMapping(method = RequestMethod.POST, value = "/form")
public String postForm(#ModelAttribute("item") Item item, ModelMap model)
{
return "result";
}
In the above code, the Item is injected. However, even changing the name of this variable (or removing the modelattribute), doesn't affect that this variable is injected with the form values.
Will spring just inject the values in the first model class found, from the form? How does Spring know that it has to inject the form into the Item item parameter?
At first I thought the variable in the controller (POST) should have the name of commandName of the form, but it does work with other names as well, strangely enough.

There is a dedicated section in the Spring Documentation describing the usage of #ModelAttribute on method arguments.
This process is known as Data Binding on submit and is following some conventions:
If #ModelAttribute is explicitely declared with a name on an argument (your case). In this case the submitted data of the form are copied over automatically under this name. You can check yourself that it is already there in your ModelMap model by invoking/inspecting model.get("item").
If there is no #ModelAttribute argument annotation at all, then the attribute name is assumed from the type essentially in your case type Item converts to attribute name item (camelCase notation) that is created for you holding a new Item with the form data-bind'ed fields. That is also there in the ModelMap (same check as above: model.get("item"))
Key point to realise is in all these cases DataBinding occurs before hitting your Post form RequestMapping.

Related

#ModelAttribute for form parameter in Spring post handler: is already an attribute?

There's this Spring behaviour that I can't explain from the documentation.
I have a form, which sends a name parameter. Name is a simple bean with a value property.
The handler looks something like this:
#PostMapping("/hello")
public String onSubmit(Name name, Model model) { // 1
// public String onSubmit(#ModelAttribute Name name, Model model) { // 2
// .. stuff
return "helloView";
}
Whether I add the #ModelAttribute annotation (commented line 2) or not (line 1) doesn't make a difference: both a unit test and a JSP page indicate the name attribute is there.
Is there some default behaviour which automatically forwards incoming attributes (from the form) to the model?
For what it's worth: I can use the annotation to change the attribute name. For example: #ModelAttribute("theName") Name name would no longer provide the attribute under the name key, but instead under the theName key (as you would pretty much expect).

How to correctly initialize an object that have to contain the data retrieved by 2 methods of my controller in this Spring MVC application?

I am pretty new in Spring MVC and I have the following doubt about how correctly achieve the following task.
I am working on a web application that implement a user registration process. This registration process is divided into some consecutive steps.
For example in the first step the user have to insert a identification code (it is a code that identify uniquely a user on some statal administration systems) and in the second step it have to compile a form for his personal data (name, surname, birth date, and so on).
So, actually I have the following controller class that handle these steps:
#Controller
public class RegistrazioneController {
#Autowired
private LoadPlacesService loadPlacesService;
#RequestMapping(value = "/iscrizioneStep1")
public String iscrizioneStep1(Model model) {
return "iscrizioneStep1";
}
#RequestMapping(value = "/iscrizioneStep2", method=RequestMethod.POST)
public String iscrizioneStep2(Model model, HttpServletRequest request, #RequestParam("cf") String codicFiscale) {
System.out.println("INTO iscrizioneStep2()");
//String codicFiscale = request.getParameter("cf");
System.out.println("CODICE FISCALE: " + codicFiscale);
model.addAttribute("codicFiscale", codicFiscale);
return "iscrizioneStep2";
}
#RequestMapping(value = "/iscrizioneStep3", method=RequestMethod.POST)
public String iscrizioneStep3(#ModelAttribute("SpringWeb")Step2FormCommand step2Form, ModelMap model, HttpServletRequest request) {
System.out.println("INTO iscrizioneStep3()");
System.out.println("NOME: " + step2FormCommand.getName());
return "iscrizioneStep3";
}
Into the iscrizioneStep2() it is retrieved the first code (#RequestParam("cf") String codicFiscale).
Into the iscrizioneStep3() it is retrieved a command object containing the data inserted into the form of the view in which this form was submitted, this one:
#ModelAttribute("SpringWeb")Step2FormCommand step2FormCommand
It works fine.
Now my problem is that I have another object named Step3View that have to be initialized with the aggregation of the #RequestParam("cf") String codicFiscale object retrieved into the iscrizioneStep2() method and the #ModelAttribute("SpringWeb")Step2FormCommand step2FormCommand retrieved into the iscrizioneStep3() method.
This Step3View class simply contain the String codicFiscale and all the fields of the Step2FormCommand class.
Now my doubts are: what is the best way to handle this situation? Where have I to declare this Step3View object? at controller level? (so I can use it in all my controller methods?). Have I to annotate this class with #Component (or something like this) to inject it in my controller?
What is the best solution for this situation?
I think in order to get an answer you need to understand the question and ask the right question. I think your question is "how do I pass a parameter from one page to another page in SpringMVC?". You specifically want to know how to pass the "cf" param, but readers here will tend to pass over questions that are too specific because it takes too much time to figure out what you want.
In answer to that, see Spring MVC - passing variables from one page to anther as a possible help.
Also, there are many good answers about this question for JSP in general, which can be worked into the SpringMVC architecture. See How to pass value from one jsp to another jsp page? as a possible help.

How we assingn value to spring form fields from reference data method on loading

I have one spring form name UpdateStock.jsp
<form:form........>
<form:input path="compAmount"/>
............
</form:form>
My intent is initialize the above spring form text box by some default values from database. So I have form text tag to
<form:input path="compAmount" value=${compamount}/>
Here ${compamount} is one of the value returned from referenceData() method.
But the problem is value=${compamount} is invalid.
So I leave it and do the next thing as below:
that is initialize Object command object in reference_Data() method as below. But it is not working.
protected Map reference_Data(HttpServletRequest request, Object command,Errors errors, int page) throws Exception {
UpdateStockBean bean=new UpdateStockBean();//which is correspond to UpdateStock.jsp page
bean.setCompAmount(300);//this do not change the value of corresponding field
command=new Object();
command=(Object)bean;
}
Can you suggest solution!
It sounds like you want to some default values for some text fields of your form. If you are using SimpleFormController you can simply override the method protected Object formBackingObject(HttpServletRequest request) to populate your form with some default data in the fields of your form.
You should not use protected Map referenceData(HttpServletRequest request) method for this purpose. Because referenceData is used for providing list data for checkboxes or radio buttons. This is nicely explained in this nice article of mkyoung.
If you are using AbstractWizardFormController, still you have the methods protected Object formBackingObject(HttpServletRequest request) and protected Map referenceData(HttpServletRequest request). Because AbstractWizardFormController is a subclass of AbstractFormController, which eventually holds the above mentioned methods. Here is a sample demonstration of using AbstractWizardFormController with form baking object.
Cheers!
you can try somethig like this, you are using Map Collection:
Map yourname = new HashMap();
yourname.put("compamount", bean.getCompAmount());
So a here ${compamount} is one of the value returned from reference_Data() method.
I hope help you :)

Spring form backing object issue

I'm struggling with the way Spring handles form backing object during a POST. ScreenObject property that has a corresponding input tag in the html form survives the post, as expected. But if a property does not have an input tag, two scenarios occur:
If property is passed in as a request parameter, it survives the post.
If property is not passed in as a request parameter, it does not survive the post.
Here's my code.
screen object
private Integer hostSiteSectionId; // no input tag but survives if passed as a request param
private String name; // input tag so survives
private String orderFactor; // input tag so survives
private Integer hostSiteId; // no input tag but survives if passed as a request param
private String hostSiteName; // no input tag and not passed as request param so does not survive
GET
#RequestMapping(method=RequestMethod.GET)
public ModelAndView edit(#RequestParam(value="hostSiteId", required=false) Integer hostSiteId, #RequestParam(value="hostSiteSectionId", required=false) Integer hostSiteSectionId, Locale locale) {
HostSiteSectionHeaderEditScreenObject screenObject=new HostSiteSectionHeaderEditScreenObject();
initializeScreenObject(hostSiteId, hostSiteSectionId, screenObject, locale, true);
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("screenObject", screenObject);
modelAndView.setViewName(WebView.HOST_SITE_SECTION_HEADER_EDIT_PAGE.getViewName());
return modelAndView;
}
POST with CANCEL
#RequestMapping(method=RequestMethod.POST, params="cancel")
public String cancel(#ModelAttribute("screenObject") HostSiteSectionHeaderEditScreenObject screenObject) {
// logic that returns redirect
}
My initializeScreenObject() method only sets properties of the screenObject. It doesn't operate on the model. I don't see how it would interfere, so I'm not posting it's basic code.
Within this post, and it works the same in other posts, screenObject has the following:
All input provided by user in the form via input tags is present. No issue.
hostSiteId (no input tag) is present in the screenObject only if getter url included it as parameter (edit?hostSiteId=2 for example)
hostSiteSectionId (no input tag) is present in the screenObject only if getter url included it as parameter (edit?hostSiteSectionId=2 for example)
All other properties that have no corresponding input tags and are not passed in as request params are null.
To illustrate further #4. I have a screenObject.hostSiteName property which is set in initializeScreenObject() method. The view is rendered properly with <td>${screenObject.getHostSiteName()}</td>. Now I click Cancel submit control. When controller takes over the submit, this property is null.
Please explain if this is expected or not. If expected, please explain how to go about it. I figured, I could add hidden form fields for those properties that need to survive the post but it's a bit of a hack. I hope there are better answers. And how does original request parameter come into focus within the post operation..?
It sounds like expected behavior. The HostSiteSectionHeaderEditScreenObject instance passed as an argument to the POST handler method is not the same instance as the one you put in the model in the GET handler method. By default it's a new instance that Spring creates. Spring will bind values to the object's fields based on what parameters are present in the request for the POST. So if a parameter isn't present in the POST (e.g. because you didn't put an input in the HTML form for it) that field will not be set by Spring, it will just be whatever the default initial value is for the field.
It sounds like maybe what you want is to have initializeScreenObject() applied to your screen object then have the request parameter values applied after that? There are a couple ways to go about that. One would be to have a controller method annotated with #ModelAttribute:
#ModelAttribute("screenObject")
public HostSiteSectionHeaderEditScreenObject initScreenObject(#RequestParam(value="hostSiteId", required=false) Integer hostSiteId, #RequestParam(value="hostSiteSectionId", required=false) Integer hostSiteSectionId, Locale locale) {
HostSiteSectionHeaderEditScreenObject screenObject=new HostSiteSectionHeaderEditScreenObject();
initializeScreenObject(hostSiteId, hostSiteSectionId, screenObject, locale, true);
}
http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib-methods
If you do that, your GET handler method could be simplified to just return a view name.

Can #RequestParam be used on non GET requests?

Spring documentation says:
Use the #RequestParam annotation to bind request parameters to a
method parameter in your controller.
AFAIK, request parameters are variables retrieved from query strings if the request method is GET. They are also the variables retrieved from the form values when the request method is POST. I've verified this using a simple JSP that displays request parameters through method request.getParameter("key").
But it seems to me that #RequestParam only works on GET method requests. It can only get values from query strings.
Is this a bug in the documentation? Can someone please cite me some documentation that describes exactly what #RequestParam is used for, what it cannot be used for, and how it gets populated?
Can I use #RequestParam for POST methods to get the form values? If I can't use #RequestParam, what else can I use? I'm trying to avoid calling request.getParameter("key").
It works with posts too. Can you post your method body and you html?
Yes it works perfectly with post method too. you can mention the method attribute of #RequestParam as RequestMethod=POST. Here is the code snippet
#RequestMapping(value="/register",method = RequestMethod.POST)
public void doRegister
(
#RequestParam("fname") String firstName,
#RequestParam("lname")String lastName,
#RequestParam("email")String email,
#RequestParam("password")String password
)
Instead of #RequestParam which binds to a single form value, you can use #ModelAttribute annotation and bind to the whole object. But it should be used in conjunction with form or bind Spring's JSTL.
Example:
- controller that calls JSP-page, it should add objects to a Model:
#RequestMapping(value="/uploadForm", method=RequestMethod.GET)
public String showUploadForm(Model model) {
Artist artist = new Artist();
Track track = new Track();
model.addAttribute("artist", artist);
model.addAttribute("track", track);
return "uploadForm";
}
JSP might look something like that:
Track Title *:
Controller that processes form submission;
#RequestMapping(value="/uploadToServer", method=RequestMethod.POST)
public String uploadToServer(#ModelAttribute("artist") Artist artist, #ModelAttribute("track") Track track) { .... }
Here I found a good explanation of using #ModelAttribute annotation - krams915.blogspot.ca

Resources