Is it possible to access Spring MVC annotated sess

2019-03-30 13:45发布

问题:

I have a web app running Spring 3.0 and using Spring-MVC. I have a few controllers set up like this:

@Controller
@RequestMapping("/admin")
@SessionAttributes({"clientLogin", "selectTab", "user", "redirectUrl"})
public class AdminController {
...
}

@Controller
@SessionAttributes({"clientLogin", "selectTab", "user", "redirectUrl"})
public class PublicController {
....
}

I can add the annotated variables into the ModelMap with something like

map.addAttribute("user", "Bob");

That works fine to persist the variable in the current controller; I can access the var from the modelMap from any other method in that controller. But when the user hits a page in another Controller, even though the same variable is listed in the @SessionAttributes, it's not available in the second controller.

Is it possible to access these annotated variables across multiple controllers using the annotations?

回答1:

No it isn't possible - SessionAttributes are badly named in my opinion.

If you want to share these attributes across different controllers, you can explicitly put them into the session using:

session.setAttribute()



回答2:

You can have a parent class BaseController which need not be a @Controller class and use the variable @SessionAttibutes({"clientLogin", "selectTab", "user", "redirectUrl"}) over there. Remember that this class should fall in the scan package of MVC. Then when you need to use this in your actual controllers use as shown below.

public String getAllDetails(@ModelAttributes("clientLogin") Client client){
    client.getName();
    return "somejsp";
}