【问题标题】:Injecting custom parameter to request mapping method in Spring MVC在 Spring MVC 中将自定义参数注入请求映射方法
【发布时间】:2013-07-13 11:12:25
【问题描述】:

在 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"));
    ... }

【问题讨论】:

标签: spring spring-mvc dependency-injection


【解决方案1】:

您应该能够使用@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"));
    ... }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 2016-01-04
    • 1970-01-01
    相关资源
    最近更新 更多