在Spring MVC中为自定义参数注入请求映射方法

时间:2013-07-15 14:33:46

标签: spring spring-mvc dependency-injection

在Spring MVC中,我可以使用我的方法连接会话。没关系。

@RequestMapping(value = "/{cid}/read")
public @ResponseBody
boolean markAsRead(@PathVariable("cid") Comment comment, HttpSession session) {
    User user = ((User) session.getAttribute("user"));
    ... }

我可以将上述用户定义连接到方法定义吗?我的意思是代替布线会话

@RequestMapping(value = "/{cid}/read")
public @ResponseBody
boolean markAsRead(@PathVariable("cid") Comment comment, User user) {
    //No need to inject HttpSession and 
    //no need to call user = ((User) session.getAttribute("user"));
    ... }

1 个答案:

答案 0 :(得分:0)

您应该能够使用@ModelAttribute标记检索它,并以这种方式将用户注释为会话属性:

@SessionAttributes("user")
public class MyController {
    @RequestMapping(value = "/{cid}/read")
    public @ResponseBody
    boolean markAsRead(@PathVariable("cid") Comment comment, @ModelAttribute("user") User user) {
        //No need to inject HttpSession and 
        //no need to call user = ((User) session.getAttribute("user"));
    ... }
}