简体   繁体   中英

session management in servlet jsp

I'm currently developing a middle level web-app in J2EE using servlets and JSP. It is just like a Content Management System. My website is working very similar according to my needs, but there are some Questions about the best practices and the bad practices for using MVC in J2EE.

Code for user to log-in to app is:

<c:choose>
    <c:when test="${not empty sessionScope.admin}">
    <a href="/context/controller?action=add-content"> + Add a Content</a>
    </c:when>
    <c:otherwise>
    <a href="/context/controller?action=log-in"> Admin Login</a>
    </c:otherwise>
</c:choose>

Java code in controller servlet is:

if (userDAO.isUser(request.getParameter("uname"), request.getParameter("upass"))) {             
    request.getSession().setAttribute("admin", request.getParameter("uname"));  
    request.getRequestDispatcher("/admin.jsp").forward(request, response);
} else {
    request.getSession().setAttribute("admin", "");
    request.getRequestDispatcher("/content.jsp").forward(request, response);
}

For log-out:

<a href="/context/controller?action=log-out">Logout</a>

Java code in controller servlet is:

if (action != null && action.equals("log-out")) {
        HttpSession session = request.getSession(false);
        if(session != null){
            session.invalidate();
        }
        request.getRequestDispatcher("index.jsp").forward(
                request, response);
    }

I want to know is above logic for log-in, log-out and session management is correct?

And I'm also unable to preventing the user go back to secure page after he is logged-out, how can I set that?

You could get an understanding of session management in j2ee using this blog post.

http://thisara.me/2015/12/21/session-management-in-j2ee/

And to avoid go back after sign-off you need to invalidate the current session using session.invalidate() on jsp or request.getSession().invalidate() on HttpServlet.

Further you can try adding a NoCache filter, where you will need to create the filter as below and configure the filter on the web.xml.

@WebFilter
public class NoCacheFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;

        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");  // HTTP 1.1
        response.setHeader("Pragma", "no-cache");  // HTTP 1.0
        response.setDateHeader("Expires", 0);  // Proxies.

        chain.doFilter(req, res);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM