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

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).

Related

How does Spring bind form values into class variables?

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.

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 to control two operations for same url in Spring mvc?

Consider the following problem.
The user has chosen to create a document by clicking on the Create document and then he writes data into the document. The url for creating the document is /document/save.
For the subsequent write up, the existing document must be saved instead of creating a new one.
Here is my code for that.
#Controller
public MyController implements Controller, TemplateTypeAware
{
#RequestMapping("/document/save")
public String saveOrCreateDocument(#ModelAttribute DocumentWrapper wrapper, ModelAndView m)
{
if(m.getModel().get("document_id")==null)
{
Document doc=createDocument(wrapper);
m.addObject("document_id",doc.getId());
}
else
{
saveDocument(m.getModel().get("document_id"), wrapper);
}
return documentView;
}
}
Template:
<form>
<input type="hidden" name="document_id" th:value="*{document_id}"/>
<!-- other fields -->
</form>
The problem here is, I am getting document_id always null. Is there any work around for this problem?
Thanks in advance. Hope you will reply as soon as possible.
Form fields will be automatically bound to your DocumentWrapper fields if they have matching names, that means DocumentWrapper needs a field named document_id, otherwise the document_id request parameter won't be bound to your object.
Model attributes will be exposed to the view, at this point the model will be empty, you can add attributes in your handler method and they will become in your view, but request parameters won't be in the model. That explains why you always get null.
If you just need the document_id parameter, use #RequestParam:
#RequestMapping("/document/save")
public String saveOrCreateDocument(#RequestParam("document_id") Long documentId, Model m) {
...
}
Please refer to the binding section of Spring MVC: http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/mvc.html#mvc-ann-requestparam

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.

What, exactly, does a modelbinder do? How to use it effectively?

I was researching something and came across this blog post at buildstarted.com about model binders. It actually works pretty darn well for my purposes but I am not sure exactly whats going on behind the scenes. What I did was create a custom ModelBinder called USerModelBinder:
public class UserModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
ValueProviderResult value = bindingContext.ValueProvider.GetValue("id");
MyEntities db = new MyEntities();
User user = db.Users.SingleOrDefault(u => u.UserName == value.AttemptedValue);
return user;
}
}
Then in my Global.asax.cs I have:
ModelBinders.Binders.Add(typeof(User), new UserModelBinder());
My understanding is that using the model binder allows me to NOT have to use the following lines in every controller action that involves a "User". So instead of passing in an "id" to the action, the modelbinder intercepts the id, fetches the correct "item"(User in my case) and forwards it to the action for processing.
MyEntities db = new MyEntities();
User user = db.Users.SingleOrDefault(u => u.UserName == value.AttemptedValue);
I also tried using an annotation on my User class instead of using the line in Global.asax.cs:
[ModelBinder(typeof(UserModelBinder))]
public partial class User
{
}
I'm not looking for a 30 page white paper but I have no idea how the model binder does what it does. I just want to understand what happens from when a request is made to the time it is served. All this stuff "just working" is not acceptable to me, lol. Also, is there any difference between using the annotation versus adding it in Global.asax.cs? They seem to work the same in my testing but are there any gotchas?
Usually the Model Binder (in MVC) looks at you Action method and sees what it requires (as in, the objects types). It then tries to find the values from the HTTP Request (values in the HTTP Form, QueryString, Json and maybe other places such as cookies etc. using ValueProviders). It then creates a new object with the parameters that it retrieves.
IMO What you've done is not really "model binding". In the sense that you've just read the id and fetched the object from the DB.
example of usual model binding:
// class
public class SomeClass
{
public int PropA {get;set;}
public string PropB {get;set;}
}
// action
public ActionResult AddSomeClass(SomeClass classToBind)
{
// implementation
}
// pseudo html
<form action="">
<input name="PropA" type="text" />
<input name="PropB" type="text" />
</form>
if you post a form that contains the correct values (lets say you post a form with PropA and PropB ) the model binder can identify that you've sent those values in the form and build a SomeClass object.
If you really want to create a real working example you should use a strongly typed View and use HtmlHelper's EditorFor (or EditorForModel) to create all the correct names that MVC needs.
--
for reference MVC's default binder is the DefaultModelBinder, and some (there are more, you can look around in the System.Web.Mvc namespace) ValueProviders that it uses by default are the FormValueProvider and the QueryStringValueProvider
So, as I already said, how this basically works is that the default model binder reads the model that the action is recieving (say SomeClass in the example) reads what are the values that it can read (say PropA and PropB) and asks the ValueProviders for the correct values for the properties.
Also, if I recall correctly, you can also see the value providers in runtime using the ValueProviderFactories static class.
A ModelBinder looks at the arguments of the selected Controller action's method signature, then converts the values from the ValueProviders into those arguments.
This happens when the ControllerActionInvoker invokes the action associated with the ControllerContext, because the Controller's Execute() method told it to.
For more about the ASP.NET MVC execution process, see Understanding the MVC Application Execution Process

Resources