Spring MVC 3 Command Object values โ€‹โ€‹get lost between GET and POST operations

My domain object does not store values โ€‹โ€‹that are not explicitly specified in the JSP file between the GET and the POST operation on the same controller. Below is an example with error checking error

I have a domain object.

class foo { private int fieldA; private String fieldB; // .. getters and setters omitted } 

controller

 @Controller public class MyController { @Autowired private IDaoService daoService; @RequestMapping(value = "/display", method = RequestMethod.GET) public String newForm(@RequestParam("id") Long id, Model model, Principal principal) throws Exception { // check that the user has permissions ... // get the object Foo foo = daoService.read(id); // at this point foo.fieldA is equal to the input id model.addAttribute("foo", foo); // return the JSP path } @RequestMapping(value="/update", method = RequestMethod.POST) public String update(@ModelAttribute("foo") Foo foo, BindingResult result, Principal principal, Model model) throws Exception { // ERROR - at this point, fieldA is null } } 

Jsp

  <form:form method="post" commandName="foo"> <fieldset> <legend>Invest</legend> <div class="fm-req"> <label for="fm-name">Field B</label> <spring:bind path="fieldB"> <input id="fm-name" type="text" name="${status.expression}" value="${status.value}" ></input> </spring:bind> </div> <div id="fm-submit" class="fm-req"> <INPUT type="submit" value="Submit" name="Submit" /> </div> </fieldset> </form:form> 

I would think that the JSP gets an object created in newForm that has a set of fieldA (and possibly field B). The user has the option to change field B, and then click submit. I read Spring docs a lot and checked websites, but can't find out why foo.fieldA is null for the update method in the controller.

From what I understand about Spring MVC, this is a standard template, but please feel free to correct me.

Thanks in advance,

+4
source share
2 answers

This is the expected behavior.

Both instances (in newForm and update ) of the foo object (in java class names must begin with upper case) are completely independent of each other.

So, fighter create a hidden field or place it in a session. I would recommend a hidden field:

0
source

You can use one of the following options:

  • Use the Ralph hidden field method.
  • Change type Foo.fieldA to private Integer Foo

Cause Maybe: Foo.fieldA creates a problem because NULL is set to an intA type.

+1
source

Source: https://habr.com/ru/post/1389473/


All Articles