我想基于与Spring MVC的会话构建一个简单的计数器,当我重新加载页面时该计数器增加一。下面是我到目前为止尝试过的代码:
@Controller
@SessionAttributes("counter")
public class DemoController {
@RequestMapping(value="/", method=RequestMethod.GET)
public ModelAndView home(@ModelAttribute Counter c) {
System.out.println(c);
c.setCounter(c.getCounter+1);
ModelAndView mv = new ModelAndView();
mv.addObject("counter", c);
mv.setViewName("home");
return mv;
}
}
但是我总是得到0 ..
如果我使用HttpServletRequest
和HttpSession
,则在Spring MVC中,尝试访问会话属性时会出错。
@RequestMapping(value="/", method=RequestMethod.GET)
public ModelAndView home(HttpServletRequest req) {
if (req.getSession().isNew()) {
req.getSession().setAttribute("counter", new Integer(1));
} else {
// java.lang.NullPointerException: null
int counter = (int) req.getSession().getAttribute("counter");
System.out.println(counter);
}
谢谢
编辑:以下代码有效:
@RequestMapping(value="/", method=RequestMethod.GET)
public ModelAndView home(@CookieValue(value="counter", defaultValue="0") Long counter, HttpServletResponse res) {
counter++;
Cookie cookie = new Cookie("counter", counter.toString());
res.addCookie(cookie);
ModelAndView mv = new ModelAndView();
mv.addObject("messaggio", "hellooo "+counter);
mv.setViewName("home");
return mv;
}