出现java.lang.IllegalStateException: Cannot create a session after the response has been committed异常

男娘i 2022-12-10 07:05 267阅读 0赞

在使用@SessionAttributes注解后销毁session域中的session时出现java.lang.IllegalStateException: Cannot create a session after the response has been committed错误,相关部分代码如下:

  1. package xyz.newtouch.controller;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.stereotype.Controller;
  4. import org.springframework.ui.Model;
  5. import org.springframework.web.bind.annotation.*;
  6. import org.springframework.web.bind.support.SessionStatus;
  7. import org.springframework.web.servlet.ModelAndView;
  8. import xyz.newtouch.pojo.User;
  9. import xyz.newtouch.service.UserService;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. import java.io.IOException;
  13. import java.util.LinkedHashMap;
  14. import java.util.Map;
  15. /** * @author xxx */
  16. @SessionAttributes(names = { "user"})
  17. @RequestMapping("/user")
  18. @Controller
  19. public class UserController {
  20. UserService userService;
  21. @Autowired
  22. public void setUserService(UserService userService) {
  23. this.userService = userService;
  24. }
  25. @ResponseBody
  26. @GetMapping("/ajaxCheckUser/{username}")
  27. protected Map<String, Boolean> ajaxCheckUser(@PathVariable("username") String username) {
  28. boolean userStatus = userService.checkUserStatus(username);
  29. Map<String, Boolean> result = new LinkedHashMap<>();
  30. result.put("userStatus", userStatus);
  31. return result;
  32. }
  33. @PostMapping("/login")
  34. protected ModelAndView login(User loginUser, Model model) {
  35. User user = userService.checkPassword(loginUser);
  36. ModelAndView modelAndView = new ModelAndView();
  37. if (user != null) {
  38. modelAndView.addObject("msg", "login successful");
  39. model.addAttribute("user", user);
  40. modelAndView.setViewName("/pages/user/login_success.jsp");
  41. } else {
  42. modelAndView.addObject("msg", "Invalid username or password");
  43. modelAndView.setViewName("/pages/user/login.jsp");
  44. }
  45. return modelAndView;
  46. }
  47. @GetMapping("/loginOut")
  48. protected String loginOut(HttpServletRequest request) throws IOException {
  49. request.getSession().invalidate();
  50. return "redirect:/client/page";
  51. }
  52. }

当登录成功后再调用loginOut时就会出现java.lang.IllegalStateException: Cannot create a session after the response has been committed错误,提示在response提交之后不能操作session,原因是使用@SessionAttributes后不能再使用request.getSession().invalidate();方式销毁session数据,要解决此问题可以将request.getSession().invalidate();操作交给SessionStatus来做,使用示例:

  1. @GetMapping("/loginOut")
  2. protected String loginOut(SessionStatus sessionStatus) throws IOException {
  3. sessionStatus.setComplete();
  4. return "redirect:/client/page";
  5. }

发表评论

表情:
评论列表 (有 0 条评论,267人围观)

还没有评论,来说两句吧...

相关阅读