Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading a spring controller method with the same request mapping

I have a session attribute : user, and I have a url that I want to be viewed by both logged in users and publically by people not logged in as a user.

So what I want to do is this :

@Controller("myController")
@SessionAttributes({"user"})
public class MyController {

@RequestMapping(value = "/MyPage/{id}", method = RequestMethod.GET)
public ModelAndView getPage(@PathVariable Integer id) {
   return modelandview1;
}

@RequestMapping(value = "/MyPage/{id}", method = RequestMethod.GET)
public ModelAndView getPage(@PathVariable Integer id, @ModelAttribute User user){
  return modelandview2;
}

However, I have a feeling its not going to work ... suggestions very welcome.

like image 591
NimChimpsky Avatar asked Feb 02 '26 20:02

NimChimpsky


2 Answers

You only need the second method, the one that takes the User agument as well. When it's called without request attributes available to populate the User model, you'll just get a User instance with all null (or all default) field values, then in the body of the method you treat each situation accordingly

like image 169
Shivan Dragon Avatar answered Feb 04 '26 09:02

Shivan Dragon


I don't think it's a right case for @SessionAttributes. This annotation is usually used to keep original instance of a form-backing object, to avoid passing irrelevant parts of its state via hidden form fields.

Your sceanrio is completely different, thus it would be better to use HttpSession explicitly:

@RequestMapping(value = "/MyPage/{id}", method = RequestMethod.GET)
public ModelAndView getPage(@PathVariable Integer id, HttpSession session) {
    User user = (User) session.getAttribute(...);
    if (user != null) {
        ...
    } else {
        ...
    }
}

Also note that @ModelAttribute is a subject to data binding - user can change its fields by passing request parameters. You definitely don't want it in this case.

like image 35
axtavt Avatar answered Feb 04 '26 09:02

axtavt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!