声纳抱怨局部变量的无用分配

2024-01-10

我的程序中有以下代码,在与 Maven 集成后,我正在运行 SonarQube 5 对其进行代码质量检查。

然而,声纳要求删除对局部变量“session”的无用分配。

@RequestMapping(value = "/logoff", method = RequestMethod.GET)
public String getLogoffPage(HttpServletRequest request, HttpServletResponse response) {
    logger.info(" Before Log Offf........ " + request.getSession().getId() );
    HttpSession session =request.getSession(true);
    request.getSession().invalidate();
    myApplication.logout();
    SecurityContextHolder.clearContext();
    session=null;                   
    return "login";
}

假设问题是“为什么”:

你实际上做什么do with session?没有什么。

HttpSession session =request.getSession(true);  // session assigned
request.getSession().invalidate();         // session NOT used
myApplication.logout();
SecurityContextHolder.clearContext();
session=null;                            // session re-assigned

也许你的意思是这个?

HttpSession session =request.getSession(true);
session.invalidate();
myApplication.logout();
SecurityContextHolder.clearContext();

顺便说一句,我已经放弃了session = null因为 Java 中没有理由这样做(C 则另当别论)。

当然,代码还可以更简洁:

request.getSession().invalidate();
myApplication.logout();
SecurityContextHolder.clearContext();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

声纳抱怨局部变量的无用分配 的相关文章

随机推荐