Tomcat Session Timeout web.xml

时间:2012-11-19 21:59:48

标签: java jsp tomcat web.xml session-timeout

这是我的web.xml文件,它位于WEB-INF/lib。它指定1分钟的会话超时,但是在活动1分钟后用户不会计时。

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>

我在我的jsp文件中使用了这行session.getMaxInactiveInterval()并输出了1800(30分钟)。有人为什么默认为30而不是使用我的web.xml文件中指定的时间?

编辑:

我的jsp页面上的代码检查会话属性,如果确实存在,则会在一分钟后将用户重定向到登录页面,即使在页面刷新时也不会重定向用户。

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

编辑完整代码(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>

4 个答案:

答案 0 :(得分:25)

会话超时层次结构:

  • TOMCAT_HOME / CONF / web.xml中
  • WebApplication的/ web应用/ WEB-INF / web.xml中
  • 在Java中硬编码会话超时:HttpSession.setMaxInactiveInterval(int)

会话超时配置的顺序:

HttpSession.setMaxInactiveInterval(int) > $WebApplication/webapp/WEB-INF/web.xml&gt; $ TOMCAT_HOME / CONF / web.xml中

每个后续条目都会覆盖上述配置。

最好的问候。

答案 1 :(得分:14)

web.xml应该直接在WEB-INF中,而不是在 WEB-INF / lib 中。

答案 2 :(得分:7)

  1. 一分钟是一个非常低的会话超时。它应该是几个小时。

  2. 超时发生在那么多不活动之后,没有那么多活动。

  3. 正确的测试是request.getSession(false) == nullrequest.getSession(true).isNew()

答案 3 :(得分:1)

如果你的目标是测试会话到期,你根本不必等待。您的应用程序服务器可能会提供手动使会话过期的方法。例如,在Tomcat中,您可以通过管理器应用程序执行此操作。每个应用程序旁边都有一个“Expire sessions”按钮,旁边有一个字段,您可以在其中指定空闲时间阈值。所有闲置超过阈值的会话将被无效。要使所有会话无效,只需输入0并按Enter;无论web.xml中的值如何,所有会话都将过期。

如果您没有使用Tomcat,请查看应用程序服务器的文档,您可以通过管理控制台或命令行找到一种方法。