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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With