【问题标题】:How to get a session variable in a Spring Controller?如何在 Spring Controller 中获取会话变量?
【发布时间】:2013-07-29 16:40:17
【问题描述】:

我在 Spring 上配置了一个控制器,我必须通过它锻炼一个数据库连接来调用 DAO 操作。

这个连接实际上是在一个会话变量中可用的,由于它不是HttpServlet继承的,因此Spring Controller暂时无法访问它。

这个控制器访问会话变量的正确方法是什么?我必须实现从 HttpServlet 继承的方法 doGet 和 doPost 来操作请求对象吗?它可以让 Spring 控制类吗?

感谢您的回复。

@Controller
public class SpringController {

    @RequestMapping("/create")
    public String form(MyCar myCar) {
                /*That's where I have to retrieve hibernateSession from
                * HttpSession and pass to DAO class do its work.
                */
                MyCarDAO myCarDao = new MyCarDAO(session);
                myCarDao.saveOrUpdate(myCar);
        return "WEB-INF/views/projeto/novo.jsp";
    }
}

【问题讨论】:

  • 你可以注入HttpServletRequest对象:private @Autowired HttpServletRequest request;它解决了你的问题吗?

标签: spring hibernate servlets


【解决方案1】:

您可以在方法中添加HttpSession 参数:

@RequestMapping("/create")
public String form(MyCar myCar, HttpSession session) {
   ...
}

Spring会在调用方法时自动添加session参数。

查看RequestMapping 的文档了解可能的参数

【讨论】:

    【解决方案2】:

    假设您声明了 3 个会话属性,但在处理程序方法参数中只使用了其中的 1 个,所以:

    @SessionAttributes({ "abc", "def", "ghi" })
    public class BindingTestController {
    
        @ModelAttribute("abc")
        public String createABC() {
            return "abc";
        }
    
        @RequestMapping(method = RequestMethod.GET)
        public void onGet(@ModelAttribute("abc") String something) {
            // do nothing :)
        }
    
        @RequestMapping(method = RequestMethod.POST)
        public void onPost(@ModelAttribute("abc") String something, BindingResult bindingResult, SessionStatus sessionStatus) {
            sessionStatus.setComplete();
        }
    
    }
    

    如果在 google 中点击有很多例子

    【讨论】:

      【解决方案3】:

      IMO 正确的方法应该是将连接存储在会话范围的 bean 中,而不是会话变量中。

      使用 @Scope(value = "会话")

      (参见http://static.springsource.org/spring/docs/3.0.0.M3/reference/html/ch04s04.html

      【讨论】:

        猜你喜欢
        • 2023-01-11
        • 1970-01-01
        • 1970-01-01
        • 2012-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-03
        • 2010-09-25
        相关资源
        最近更新 更多