其他分享
首页 > 其他分享> > springmvc在使用@ModelAttribute注解获取Request和Response会产生线程并发不安全问题(续)

springmvc在使用@ModelAttribute注解获取Request和Response会产生线程并发不安全问题(续)

作者:互联网

通过前面的文章:https://blog.csdn.net/hanjun0612/article/details/103421903

我们知道  由于@ModelAttribute 导致的线程不安全问题,

引起了 session 混乱。

 

我这里有个实际情况,原先(错误例子)的代码如下:

我在基类中,获取了全局变量的 SysUser curUser;

public class SuperBaseController {
    protected HttpServletRequest request;
    protected HttpServletResponse response;
    private SysUser curUser;
    @Value("${isDebug}")
    protected Boolean  isDebug;
    
    @ModelAttribute
    public void setLang(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.getCurUser() = WebUtil.getCurrentUser(isDebug, request);
    }
}

在我通过JMeter,通过2个账号测试,发觉session混乱。

 

解决方案:

现在改成如下代码,则是可以的!

改动:

1  增加了@Autowired

2 设置curUser为private,并且封装成属性:getCurUser()

public class SuperBaseController {
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;
    private SysUser curUser;
    @Value("${isDebug}")
    protected Boolean  isDebug;
    
    @ModelAttribute
    public void setLang(HttpServletRequest request, HttpServletResponse response) {
        this.sysHostUrl = this.request.getAttribute(ComContants.SYSHOSTURL).toString();
        this.sysHost = this.request.getAttribute(ComContants.SYSHOST).toString();
    }
 
    public SysUser getCurUser() {
        curUser=WebUtil.getCurrentUser(isDebug, request);
        return curUser;
    }
    
}

 

标签:springmvc,Request,request,public,curUser,isDebug,protected,ModelAttribute,respon
来源: https://www.cnblogs.com/hanjun0612/p/11996729.html