Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
279 views
in Technique[技术] by (71.8m points)

java - @ModelAttribute in a method

Imagine a code like this one:

@RequestMapping(value="/users", method=RequestMethod.GET)
public String list(Model model) {
    ...
}

@InitBinder("user")
public void initBinder(WebDataBinder binder) {
    binder.setDisallowedFields("password"); // Don't allow user to override the value
}

@ModelAttribute("user")
public User prepareUser(@RequestParam("username") String username){
    ...
}

@RequestMapping(value="/user/save", method=RequestMethod.POST)
public String save(@ModelAttribute("user") User user, Model model) {        
    ...
}

I use an init binder to avoid that a field can be binded and I mark a method (prepareUser()) with @ModelAttribute to prepare my User object before it is binded. So when I invoke /user/save initBinder() and prepareUser() are executed.

I have set "user" in both @InitBinder and @ModelAttribute so Spring-MVC could understand that this methods should only be applied before executing a method with @ModelAttribute("user").

The problem is that the method annotated with @ModelAttribute("user") is executed before every mapped method of this controller. For example if I invoke /users prepareUser is executed before list() method. How can I make that this preparer is only executed before save() method having all the methods in the same controller?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's not really what @ModelAttribute is for. If you use it as a method parameter, it puts the annotated parameter into the model (that's fine). If you put it on a method, it's called every time to provide reference data that every method in the controller should have access to.

If you want to take control of building up your User object, you have several options. The two that are most obvious to me are:

  1. Use your InitBinder method to add a new custom editor (a PropertyEditor class) for building User objects,
  2. Use the conversion service in Spring 3 to convert string usernames to User objects.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...