使用ServletAPI对象作为入参遇到的问题
@RequestMapping(value="/login",method = RequestMethod.POST)
public String login(@RequestParam(value="username",defaultValue="")String username,
@RequestParam(value="password",defaultValue="")String password,
ModelMap model,
HttpSession session) {
String viewName;
User user;
try {
user = service.login(username,password);
user.setPassword(null);
session.setAttribute(Constants.USER, user);
session.setAttribute(Constants.ERROR, null);
viewName = "redirect:http://localhost:8080/book/index.jsp";
} catch (ParameterException e) {
viewName = "redirect:http://localhost:8080/book/login.jsp";
session.setAttribute(Constants.ERROR, e.getMessage());
session.setAttribute(Constants.USER, new User(username, ""));
e.clear();
} catch (ServiceException e) {
viewName = "redirect:http://localhost:8080/book/login.jsp";
session.setAttribute(Constants.ERROR, e.getMessage());
session.setAttribute(Constants.USER, new User(username, ""));
}
return viewName;
}
注意事项
当在处理方法中需要用setAttribute()方法向HttpSession中放置键值对,需要将HttpSession对象作为方法参数传入,然后再设置键值对;如果传入的是HttpServletRequest对象,调用getSession()方法获取HttpSession,然后设置键值对,这种方式下,前端无法通过EL表达式获取到该键值对。