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

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

package xyz.newtouch.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;
import xyz.newtouch.pojo.User;
import xyz.newtouch.service.UserService;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author xxx
 */
@SessionAttributes(names = {"user"})
@RequestMapping("/user")
@Controller
public class UserController {
    UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @ResponseBody
    @GetMapping("/ajaxCheckUser/{username}")
    protected Map<String, Boolean>  ajaxCheckUser(@PathVariable("username") String username) {
        boolean userStatus = userService.checkUserStatus(username);
        Map<String, Boolean> result = new LinkedHashMap<>();
        result.put("userStatus", userStatus);
        return result;
    }

    @PostMapping("/login")
    protected ModelAndView login(User loginUser, Model model) {
        User user = userService.checkPassword(loginUser);
        ModelAndView modelAndView = new ModelAndView();
        if (user != null) {
            modelAndView.addObject("msg", "login successful");
            model.addAttribute("user", user);
            modelAndView.setViewName("/pages/user/login_success.jsp");
        } else {
            modelAndView.addObject("msg", "Invalid username or password");
            modelAndView.setViewName("/pages/user/login.jsp");
        }
        return modelAndView;
    }

    @GetMapping("/loginOut")
    protected String loginOut(HttpServletRequest request) throws IOException {
        request.getSession().invalidate();
        return "redirect:/client/page";
    }
}

当登录成功后再调用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来做,使用示例:

@GetMapping("/loginOut")
protected String loginOut(SessionStatus sessionStatus) throws IOException {
    sessionStatus.setComplete();
    return "redirect:/client/page";
}
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:设计师小姐姐 返回首页