13

This is my web.xml file, it is located in WEB-INF/lib. It specifies session timeout at 1 minute, however it does not time the user out after 1 minute of activity.

Web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <servlet>
        <servlet-name>Login</servlet-name>
        <servlet-class>Login</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Login</servlet-name>
        <url-pattern>/Login</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>1</session-timeout>
    </session-config>
</web-app>

I used this line session.getMaxInactiveInterval() in my jsp file and it outputted 1800 (30 minutes) . Does anyone why it defaults to 30 rather than using the time specified in my web.xml file?

EDIT:

I've code on my jsp page which checks for session attribute and if it does exist redirects the user to the login page after a minute even on page refresh the user is not redirected.

if(session.getAttribute("username") != null){
                            out.println(session.getAttribute("username"));
                        }else{
                            response.setStatus(response.SC_MOVED_TEMPORARILY);
                            response.setHeader("Location", "index.jsp");
                        }

EDIT Full Code (Login.java):

package com.labs.xmlgenerator.controller.managesession;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.labs.xmlgenerator.model.dbconnection.*;
/**
 * Servlet implementation class Login
 */
@WebServlet(description = "Verifies Users Credentials", urlPatterns = { "/Login" })
public class Login extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private DbLoginQueries query = new DbLoginQueries();


    /**
     * @see HttpServlet#HttpServlet()
     */
    /*
    public Login() {
        super();
        // TODO Auto-generated constructor stub
    }*/

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            validateLoginCredentials(request.getParameter("liUsr"),request.getParameter("liPwd"),request,response);
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    private void validateLoginCredentials (String username, String password, HttpServletRequest request, HttpServletResponse response) throws IOException, ClassNotFoundException, SQLException{

        Boolean valid = true;
        int resultSize;
        HashMap<String, String> userDetails = null;
        HttpSession session = request.getSession(true);
        String location = "index.jsp";
        Cookie usernameErrorCookie;
        Cookie passwordErrorCookie;
        Cookie usernameCookie;

        if(username == null || username == ""){
            valid = false;
            usernameErrorCookie = new Cookie("liUsrErrCookie","Please enter a valid username");
            response.addCookie(usernameErrorCookie);
        }else{
            usernameCookie = new Cookie("liUsrCookie",username);
            response.addCookie(usernameCookie);
        }

        if(password == null || password == ""){
            valid = false;
            passwordErrorCookie = new Cookie("liPwdErrCookie","Please enter a valid password");
            response.addCookie(passwordErrorCookie);
        }

        if(valid == true){
            userDetails = query.loginQuery(username);
            resultSize = userDetails.size();
            if(resultSize < 4){
                valid = false;
                usernameErrorCookie = new Cookie("liUsrErrCookie","The username entered is not valid");
                response.addCookie(usernameErrorCookie);
            }
            else if(resultSize > 4){
                valid = false;
                usernameErrorCookie = new Cookie("liUsrErrCookie","The username is returning more than one result, please contact admin");
                response.addCookie(usernameErrorCookie);
            }
            else if(resultSize == 4){

                if(!userDetails.get("Password").equals(password)){
                    valid = false;
                    passwordErrorCookie = new Cookie("liPwdErrCookie","The entered password is incorrect");
                    response.addCookie(passwordErrorCookie);
                }
            }
        }


        if(valid == true){
            session.setAttribute("username", userDetails.get("Username"));
            session.setAttribute("permission", userDetails.get("AdminPermissions"));
            session.setAttribute("email", userDetails.get("Email"));
            location = "home.jsp";

        }else{
            location = "index.jsp#login";
        }

        response.setStatus(response.SC_MOVED_TEMPORARILY);
        response.setHeader("Location", location);

    }
}

home.jsp

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Home</title>
    <link rel="stylesheet" href="resources/css/Common.css" type="text/css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="resources/js/Common.js"></script>
</head>
<body>
    <header>
        <div id="actionsMenu">
            <ul id="actionLinks">
                <li><a class="linkButtons" id="userNameLink">
                                     <%
                        System.out.println(session.getMaxInactiveInterval());
                        if(session.getAttribute("username") != null){
                            out.println(session.getAttribute("username"));
                        }else{
                            out.println("no user");
                            /*
                            response.setStatus(response.SC_MOVED_TEMPORARILY);
                            response.setHeader("Location", "index.jsp");*/
                        }   
                    %>
                </a></li>
                <li><a class="linkButtons" href="Logout">Log Out</a></li>
                <li><a class="linkButtons"  href="#">Update</a></li>
            </ul>
        </div>
    </header>
    <nav class="tabs">
        <section id="generateSection">
            <h2 class="selectedTab" id="generateTab">
                <a id="gene" href="#generateXML">Generate XML</a>
            </h2>
            <div class="selectedContent" id="generateNav">
                <ul id="links">
                    <li><a class="navLink" href="#graphic">Graphic Interface</a></li>
                    <li><a class="navLink" href="#xml">XML Interface</a></li>
                </ul>
            </div>
        </section>
        <section id="adminSection">
            <h2 class="normalTab" id="adminTab">
                <a href="#admin">Admin</a>
            </h2>
            <div class="normalContent" id="adminNav">
                <ul id="links">
                    <li><a class="navLink" href="#images">Manage Images</a></li>
                    <li><a class="navLink" href="#keywords">Manage Keywords</a></li>
                    <li><a class="navLink" href="#users">Manage Users</a></li>
                </ul>
            </div>
        </section>
    </nav>  
    <div id="content">
        <noscript><p id="javascriptError">This website requires JavaScript to be enabled.</p></noscript>
    </div>
    <div id="updateUserDetails"></div>
    <div id="popup">
        <input type="button" value="X" id="exitButton">
        <p class="pageTitle" style="float:left; margin:0px;">Update Details</p>
        <form id="updateForm"  action="Update" onsubmit="return updateValidation()" method="post" >
            <p id="user">Username :</p>
            <p id="userNameUpdate"><%
                if(session.getAttribute("username") != null){
                    out.println(session.getAttribute("username"));
                }%></p>
            <p class="error" id="updCurrentPwdErr">
            <% 
                        Cookie[] currentPassEror = null;
                        currentPassEror = request.getCookies();
                        if(currentPassEror != null){
                            for(int i = 0; i < currentPassEror.length; i++){
                                 Cookie cookie = currentPassEror[i];
                                 if(cookie.getName().equals("updCurrentPwdErrCookie")){
                                     out.println(cookie.getValue());
                                     cookie.setMaxAge(0);
                                     response.addCookie(cookie);
                                 }
                             }
                        }
                        %>
            </p>
            <label for="updCurrentPwdLbl">Current Password :</label>
            <br />
            <input type="password" name="updCurrentPwd" id="updCurrentPwd">
            <br />
            <p class="error" id="updNewPwdErr">
            <% 
                        Cookie[] newPassCookies = null;
                        newPassCookies = request.getCookies();
                        if(newPassCookies != null){
                            for(int i = 0; i < newPassCookies.length; i++){
                                 Cookie cookie = newPassCookies[i];
                                 if(cookie.getName().equals("updNewPwdErrCookie")){
                                     out.println(cookie.getValue());
                                     cookie.setMaxAge(0);
                                     response.addCookie(cookie);
                                 }
                             }
                        }
            %></p>
            <label for="updNewPwdLbl">New Password :</label>
            <br />
            <input type="password" id="updNewPwd" name="updNewPwd">
            <br />
            <p class="error" id="updReNewPwdErr">
            <% 
                        Cookie[] reNewPassCookies = null;
                        reNewPassCookies = request.getCookies();
                        if(reNewPassCookies != null){
                            for(int i = 0; i < reNewPassCookies.length; i++){
                                 Cookie cookie = reNewPassCookies[i];
                                 if(cookie.getName().equals("updReNewPwdErrCookie")){
                                     out.println(cookie.getValue());
                                     cookie.setMaxAge(0);
                                     response.addCookie(cookie);
                                 }
                             }
                        }
            %>          
            </p>
            <label for="updReNewPwdLbl">Re-Enter New Password :</label>
            <br />
            <input type="password" id="updReNewPwd" name="updReNewPwd">
            <br />
            <p class="error" id="updEmailErr">
            <% 
                        Cookie[] emailErrCookies = null;
            emailErrCookies = request.getCookies();
                        if(emailErrCookies != null){
                            for(int i = 0; i < emailErrCookies.length; i++){
                                 Cookie cookie = emailErrCookies[i];
                                 if(cookie.getName().equals("updEmailErrCookie")){
                                     out.println(cookie.getValue());
                                     cookie.setMaxAge(0);
                                     response.addCookie(cookie);
                                 }
                             }
                        }
            %>
            </p>
            <label for="updEmailLbl">Email :</label>
            <br />
            <input type="text" id="updEmail" name="updEmail" value="<%
                    boolean foundEmailCookie = false;
                    Cookie[] emailCookies = null;
            emailCookies = request.getCookies();
                    if(emailCookies != null){
                        for(int i = 0; i < emailCookies.length; i++){
                             Cookie cookie = emailCookies[i];
                             if(cookie.getName().equals("updEmailCookie")){
                                 foundEmailCookie = true;
                                 out.println(cookie.getValue());
                                 cookie.setMaxAge(0);
                                 response.addCookie(cookie);
                             }
                         }
                    }
                    if(!foundEmailCookie){
                        if(session.getAttribute("email") != null){
                            out.println(session.getAttribute("email"));
                        }
                    }
            %>">
            <input type="hidden" id="updUrl" name="updUrl" value="">
            <br />
            <input type="submit" value="UPDATE">
        </form>
    </div>
</body>
</html>
Roman C
  • 47,329
  • 33
  • 60
  • 147
Colin747
  • 4,695
  • 15
  • 64
  • 108

4 Answers4

27

Session timeout hierarchy:

  • TOMCAT_HOME/conf/web.xml
  • WebApplication/webapp/WEB-INF/web.xml
  • Hardcoding your session timeout in Java : HttpSession.setMaxInactiveInterval(int)

The order of the session timeout configuration:

HttpSession.setMaxInactiveInterval(int) > $WebApplication/webapp/WEB-INF/web.xml > $TOMCAT_HOME/conf/web.xml

Each subsequent entry overrides the above configuration.

Best regards.

Hkachhia
  • 4,130
  • 5
  • 35
  • 71
Ahmed MANSOUR
  • 1,861
  • 1
  • 22
  • 32
14

The web.xml should be directly in WEB-INF, not in WEB-INF/lib.

Koshinae
  • 2,083
  • 2
  • 29
  • 35
8
  1. One minute is a ridiculously low session timeout. It should be several hours.

  2. The timeout happens after that much inactivity, not that much activity.

  3. The correct test is request.getSession(false) == null, or request.getSession(true).isNew().

user207421
  • 289,834
  • 37
  • 266
  • 440
  • 5
    I am aware it is inactivity. The ridiculously low time is so I can test it without having to wait a large amount of time. I will try you solution now. – Colin747 Nov 19 '12 at 22:36
  • Could you describe your solution in more detail? – Colin747 Nov 19 '12 at 22:50
  • 1
    @Colin747 The solution is in #3. I've even given you the code. Not sure what else you could possibly need. – user207421 Nov 20 '12 at 03:45
  • 3
    Several hours is a ridiculously high session timeout: 1) you will store so many more session contexts (use too much memory) for those users that simply close the tab instead of logging out. 2) it is a very bad idea in terms of security. 15 - 30 minutes is a good value – Anthony Jun 06 '14 at 18:42
  • @Anthony It is a pain in the neck for the user. I deal with a couple of major vendors, one of whose websites has a timeout of an hour or two, and I can assure you I use the other one whenever possible. – user207421 Mar 05 '15 at 23:25
  • Yet another case where one size does not fit all. I work in an environment where the timeout is 5 minutes in order to comply with certain security constraints. But I also agree with @EJP that "it is a pain in the neck for the user" - a several hour timeout might be the right value in other circumstances. It's a user experience/business value trade-off. – Kevin OMara Jul 01 '15 at 16:59
1

If your ogjective is to test session expiry, you don't have to wait at all. You application server may offer a way of expiring sessions manually. In Tomcat for example, you can do so through the manager application. Next to each application there's an "Expire sessions" button with a field next to it where you can specify the idle time threshold. All sessions that have been idle for a period above the threshold will be invalidated. To invalidate all sessions simply type in 0 and hit enter; all session will expire regardless of the value in web.xml.

If you're not using Tomcat, look at the documentation of your application server and you may find a way to do so through the administration console or command line.

Anthony
  • 504
  • 5
  • 19