当前位置: 首页 > 知识库问答 >
问题:

Tomcat会话超时web。xml

宗政深
2023-03-14

这是我的网站。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>

共有3个答案

融宏伟
2023-03-14
匿名用户

>

  • 一分钟的会话超时低得离谱。应该要几个小时。

    超时发生在那么多不活动之后,而不是那么多活动之后。

    正确的测试是请求。getSession(false)==null,或请求。getSession(true)。isNew()。

  • 郭彬郁
    2023-03-14

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

    燕砚文
    2023-03-14

    会话超时层次结构:

    • TOMCAT_HOME/conf/web。xml

    会话超时配置的顺序:

    HttpSession。setMaxInactiveInterval(int)

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

    顺致敬意,

     类似资料:
    • 我有一个Web应用程序,它的web.xml超时为1分钟,但它从未超时过这个值。它对其他值(如5,9,10或25分钟)超时,但从未超时1分钟。这是Tomcat 8的最小会话超时限制吗?

    • 在 HTTP 协议中,当客户端不再处于活动状态时没有显示的终止信号。这意味着当客户端不再处于活跃状态时可以使用的唯一机制是超时时间。 Servlet 容器定义了默认的会话超时时间,且可以通过 HttpSession 接口的 getMaxInactiveInterval 方法获取。开发人员可以使用HttpSession 接口的 setMaxInactiveInterval 方法改变超时时间。这些方法

    • 问题内容: 我在用户登录时创建会话,如下所示: 如何在X分钟的会话上指定超时,然后在达到X分钟后让它执行功能或页面重定向? 编辑:我忘了提及由于不活动,我需要会话超时。 问题答案: 首先,存储用户最后一次发出请求的时间 在后续请求中,检查他们多久之前提出了请求(在此示例中为10分钟)

    • 问题内容: Tomcat5.5上部署的Web应用程序的默认会话超时是多少?它是特定于浏览器的吗?在我的Web应用程序中,默认超时没有在代码中或代码中提及。 问题答案: 打开并找到这个 所有Web应用程序都隐式继承自此默认Web描述符。您可以覆盖session-config以及在web.xml中定义的其他设置。 这实际上来自我的Tomcat 7(Windows),但我认为5.5 conf差别不大

    • 部署在Tomcat5.5上的Web应用程序的默认会话超时是多少?它是浏览器特定的吗?在我的Web应用程序中,默认超时在和代码中都没有提到。

    • 我有一个问题发生在我坐在空闲的时候,没有接触网络浏览器,vaadin在点击vaadin应用程序中的任何内容之后,就会抛出红色的通信问题错误消息。 我已经通过30分钟不接触浏览器进行了测试。之后,当我单击vaadin应用程序中的一个按钮时,它会抛出通信错误消息。 我有两个应用服务器,它们位于Rackspace的负载均衡器后面。我还启用了“粘性会话”... vaadin可能有自己的超时吗?