11

I have an User object stored in the session with @SessionAttributes. And a straight-forward method decorated with @ModelAttribute in order to initialize it whenever the session's value is null.

User class:

@Entity
@Table( name="USER")
public class User implements java.io.Serializable {

    private Long id;
    private String username;
    private String password;
    ....

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name ="ID")
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
    ...

Controller:

@RequestMapping("/item")
@Controller
@SessionAttributes({"user"})
public class MyController {

@ModelAttribute method:

@ModelAttribute("user")
    public User createUser(Principal principal) {
        return userService.findByUsername(principal.getName());
    }

It all seems to work as expected except in this particular method:

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String showItem(@PathVariable("id") Long id, @ModelAttribute("user") User user,
            Model uiModel) {
   ...    
}

The problem is that User.id is being set with @PathVariable("id"). I believe I ran into this with @RequestParam too. I'm assuming that's because both have the same name and type. After reading Spring's documentation (see below) I'm assuming this is expected behavior:

The next step is data binding. The WebDataBinder class matches request parameter names — including query string parameters and form fields — to model attribute fields by name. Matching fields are populated after type conversion (from String to the target field type) has been applied where necessary.

However, I would think this scenario is fairly common, how are other people handling this? If my findings are correct and this is expected behavior (or bug), this seems to be very error prone.

Possible solutions:

  1. Change @PathVariable("id") to @PathVariable("somethingElse"). Works but it's not as straightforward with @RequestParam (e.g. I don't know how to change jqgrid's request parameter id to something else but this is another issue).
  2. Change @PathVariable("id") type from Long to Int. This will make User.id and id types differ but the cast to Long looks ugly :)
  3. Don't use @ModelAttribute here and query the DB for User again. Not consistent with other methods and involves redundant DB calls.

Any suggestions?

3
  • A hack 4th option, what if you change the order - @ModelAttribute first and then @PathVariable. Jul 23, 2012 at 20:07
  • The result was the same, it was worth the try though.
    – Ulises
    Jul 23, 2012 at 22:23
  • Yes, actually realized later that the matching properties of User will be matched from uri variables. Your approaches look good, I have added one more as answer. Jul 24, 2012 at 0:18

2 Answers 2

5

How about this approach -

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String showItem(@PathVariable("id") Long id,
            Model uiModel) {
       User user = (User)uiModel.asMap().get("user");
   ...    
}
3
  • Not bad. It's a small change and it works. Quick question, I didn't see getAttribute() on Model, should I just do (User)uiModel.asMap().get("user")?
    – Ulises
    Jul 24, 2012 at 1:26
  • +1 I like your answer, before I mark it though I'd like to see if I hear more. Thank you very much for your help.
    – Ulises
    Jul 24, 2012 at 1:36
  • I had the same problem and use the method of changing the name of the id request parameter. I searched many hours for the cause of the issue and IMHO this matching is unwanted and unexpected and is a bug (and not a feature) of SpringMVC.
    – klausch
    Sep 4, 2015 at 8:28
0

use @SessionAttribute

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String showItem(@PathVariable("id") Long id, @SessionAttribute("user") User user,
            Model uiModel) {
   ...    
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.