且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

单击注销按钮,终止会话并重定向到登录页面

更新时间:2023-09-28 23:36:10

为了杀死当前会话,你基本上需要调用 HttpSession #invalidate() 并执行重定向到登录页面或主页面。此代码应放在 servlet的 doPost()方法中由POST请求调用。

In order to kill the current session, you basically need to call HttpSession#invalidate() and perform a redirect to the login or main page. This code is supposed to be placed in doPost() method of a servlet which is invoked by a POST request.

例如

<form action="${pageContext.request.contextPath}/logout" method="post">
    <input type="submit" value="Logout" />
</form>

with

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath() + "/LoginPage.html");
    }

}






无关到具体问题,您的用户名检查代码不在正确的位置。您不应该在每个JSP页面上复制相同的代码。您应该在 servlet过滤器中的单个位置执行此作业。 JSP文件中的Java代码应尽可能避免


Unrelated to the concrete problem, your username checking code is not at the right place. You shouldn't be copypasting the same code over every single JSP page. You should be performing this job in a single place in a servlet filter. Java code in JSP files should be avoided as much as possible.

此外,当最终用户使用浏览器的后退按钮导航回历史记录时,还有另一个潜在的问题。默认情况下,浏览器将缓存所有响应,因此后退按钮可能会显示浏览器缓存中的页面,而不是从服务器请求全新的响应。为了解决这个问题,请参阅此相关问题防止用户在注销后看到以前访问过的受保护页面

Further, there's another potential problem when the enduser uses the browser's back button to navigate back in history. By default, the browser will cache all responses and thus the back button might display the page from the browser cache instead of requesting a brand new straight from the server. In order to fix this, see this related question Prevent user from seeing previously visited secured page after logout

最后但并非最不重要的是,你有一些非常奇怪的HTML。使用 onClick 进行导航的按钮?用户和SEO如何不友好。请改用普通的< a> 链接。对于按钮look'n'feel,扔一些CSS。

Last but not least, you've there some quite strange HTML. Buttons with onClick to navigate? How user and SEO unfriendly. Use normal <a> links instead. For the button look'n'feel, throw in some CSS.