【问题标题】:Pass paremeter into controller method in Spring MVC将参数传递给 Spring MVC 中的控制器方法
【发布时间】:2012-06-13 09:29:18
【问题描述】:

我有一个用控制器实例化的特殊实体。在请求期间应该将它传递给处理程序的参数:

@Controller
@Scope("session")
public class HomeController {
    @Autowired
    Context context; // this thing should be passed into request.
    //context field from controller should be passed into request parameter
    //in order to set request attributes properly.
    //The instance of CommonRequest class should have reference to the context during
    //mapping HTTP request into CommonRequest object.
    @RequestMapping(value = "/do_smth", method = RequestMethod.POST)
    public void doSmth(CommonRequest request) {

    }
}

有没有办法做到这一点?

【问题讨论】:

    标签: spring controller code-injection


    【解决方案1】:
    public void doSmth(CommonRequest request) {
        //context field from controller should be passed into request parameter.
        request.setAttribute("context",context); // if you want to get context back, use Context context = (Context)request.getAttribute("context");
    }
    

    【讨论】:

    • 请求属性设置器需要正确设置上下文对象。所以这个对象应该在spring解析请求对象之前传递。
    • @user1453239 : 没看懂,你想达到什么目的?
    • 每个 HomeController 实例都有上下文对象作为字段。它包含不同的应用程序数据。我也有具有 getter 和 setter 的 CommonRequest 类。 CommonRequest 的 setter 方法有 void setId(int id){this.id = id;值 = context.getElementById(id); }。当 Spring 将传入请求映射到参数时,此对象应包含对上下文的引用。
    • @user1453239 每个 HomeController 实例??在 Spring 中,bean 默认是单例的。即,如果您不指定,您的 HomeController 是单例的。此外,您正在自动装配上下文,这也是单例。
    • 我是 Spring 新手,但我知道每个会话都有一个控制器实例。 @Scope("Session") 属性对此负责。
    猜你喜欢
    • 2015-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多