2013-07-29 24 views
0

我有一个在Spring上配置的控制器,我必须通过它来调用数据库连接来调用DAO操作。如何在Spring Controller中获取会话变量?

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

本控制器访问会话变量的正确方法是什么?我必须实现从HttpServlet继承的方法doGet和doPost,以便操纵请求对象吗?它可以在课堂上使用弹簧控制吗?

感谢您的回复。

@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"; 
    } 
} 
+0

,你可以注入'HttpServletRequest'对象:'私人@Autowired HttpServletRequest的请求;'它解决问题了吗? – acdcjunior

回答

0

打您可以将HttpSession参数添加到您的方法中:

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

弹簧将在调用方法时自动添加session参数。

检查的RequestMapping可能的参数

+0

它工作正常。谢谢! – Alex

0

假设你申报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(); 
    } 

} 

有很多的例子,如果在谷歌

相关问题