一款简单实用的请求过滤以及session超时处理

本文介绍了一种权限验证过滤器的实现方式,该过滤器同时处理请求拦截与乱码纠正功能。通过设置HTTP请求和响应对象,实现了对特定路径的访问控制,并利用session进行登录状态验证,防止未授权访问。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码源于网络共享起初只是针对请求的拦截后来我给加上了session验证

package com.ifan.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionMapping;
import org.json.simple.JSONObject;

/**
 * 权限验证过滤器,副业是乱码纠
 */
public class VerificationFilter implements Filter{
    
    /**
     * HttpServletRequest对象
     */
    private HttpServletRequest thisRequest;
    /**
     * HttpServletResponse对象
     */
    private HttpServletResponse thisResponse;
    /**
     * The default character encoding to set for requests that pass through
     * this filter.
     */
    protected String encoding = null;
    /**
     * The filter configuration object we are associated with.  If this value
     * is null, this filter instance is not currently configured.
     */
    protected FilterConfig filterConfig = null;
    /**
     * Should a character encoding specified by the client be ignored?
     */
    protected boolean ignore = true;
    /**
     * init
     */
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
        String value = filterConfig.getInitParameter("ignore");
        if (value == null){
            this.ignore = true;
        }else if (value.equalsIgnoreCase("true")){
            this.ignore = true;
        }else if (value.equalsIgnoreCase("yes")){
            this.ignore = true;
        }else{
            this.ignore = false;
        }
    }
    /**
     * destroy
     */
    public void destroy() {
        this.encoding = null;
        this.filterConfig = null;
    }
    /**
     * doFilter
     */
    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
        // Conditionally select and set the character encoding to be used
        if (ignore || (request.getCharacterEncoding() == null)) {
            String encoding = selectEncoding(request);
            if (encoding != null){
                request.setCharacterEncoding(encoding);
            }
        }
        thisRequest = (HttpServletRequest)request;
        thisResponse = (HttpServletResponse)response;
        String loginType=loginType=thisRequest.getParameter("loginType")==null?"":thisRequest.getParameter("loginType");
        if(loginType.equals("2")){

         //这是获取action请求的
            String path = thisRequest.getRequestURI()+"?"+thisRequest.getQueryString();

     //这里拦截是不是登录或者注销方法 除了这2个方法其余的都要验证
            if(!path.contains("user.php?users=loginByAcount") && !path.contains("user.php?users=logout")&& !path.contains("user.php?users=loginTimeOut")){
     //下面这段很简单了 就是判断如果session不存在了 那就是登录超时   由于配合试用dwz框架 所以反悔的数据格式是json 大家可以改成返回一个页面       

        HttpSession session=thisRequest.getSession(true);
                String admin=(String)session.getAttribute("uacount");
                if(admin==null||admin==""){
                    String relId=thisRequest.getParameter("relId");
                    try {
                          String resultStr="{\"statusCode\":\"301\",\"message\":\"当前会话已超时,请重新登录!\",\"navTabId\":\" \",\"callbackType\":\" \",\"forwardUrl\":\" \"}";
                          thisResponse.setContentType("text/json;charset=utf-8");
                          thisResponse.getWriter().print(resultStr);      
                              return ;
                        } catch (IOException e) {
                            e.printStackTrace();                  
                   }
                }
            }
                         

        }
        chain.doFilter(thisRequest,thisResponse);
    }
    /**
     * return this.encoding
     * @param request
     * @return
     */
    protected String selectEncoding(ServletRequest request) {
        return (this.encoding);
    }
}

<think>我们正在处理关于在SpringBoot中设置Tomcat接口请求超时时间的问题。根据引用,我们需要配置超时时间,但要注意SpringBoot版本的影响。引用[1]提到通过application.properties配置Tomcat参数,例如`server.tomcat.connection-timeout`(但注意,这个属性在较新版本中可能已改变)。引用[2]指出SpringBoot2.0以上版本配置方式有变化。引用[4]提到在SpringBoot2后,配置session超时使用`server.servlet.session.timeout`,这暗示了配置前缀的变化。引用[5]展示了一个yaml配置示例,其中使用了`tomcat.connection-timeout`,但同时也出现了`connection-timeout`(不带`tomcat`)的写法,这可能是笔误?实际上,根据引用[5]的配置,它是在`server.tomcat`下配置`connection-timeout`。现在,我们关心的是接口请求超时时间,即连接超时(connectiontimeout)还是请求处理超时(requestprocessingtimeout)?通常,Tomcat涉及两种超时:1.连接超时(connection-timeout):建立TCP连接后,等待客户端发送请求时间(也称为连接保持超时)。2.请求处理超时:从接收到请求到完成响应的最大时间。在SpringBoot中,默认内嵌Tomcat,我们通常配置的是连接超时(connection-timeout)。但是,对于接口请求超时(即请求处理超时),Tomcat本身没有直接提供一个配置项来设置每个请求处理超时。通常,请求处理超时由应用逻辑控制(例如,在业务代码中设置超时)或使用异步请求超时(Asynctimeout)配置。然而,根据引用[3]和[5],我们看到的配置都是关于连接超时和线程池的配置。用户的问题明确是“接口请求超时时间”,可能指的是请求处理超时。但是,Tomcat本身并不提供请求处理超时的全局配置。通常,我们可以在以下层面控制:-在应用代码中,使用异步请求(@Async)时,可以设置超时。-使用熔断机制(如Hystrix)或超时拦截器。-在Web服务器层面,如果是Tomcat,连接超时(connection-timeout)是指连接建立后等待请求时间,而不是请求处理超时。但是,引用[1]、[3]、[5]中提到的`server.tomcat.connection-timeout`实际上是连接超时,它定义的是连接建立后,等待请求数据的超时时间(单位毫秒)。例如,如果客户端在建立连接后很长时间不发送请求,超过这个时间则关闭连接。那么,如何设置请求处理超时?在Tomcat中,请求处理时间由工作线程处理,没有直接设置整个请求处理超时的参数。但我们可以通过以下方式间接控制:1.配置线程池的最大线程数(max-threads)和任务队列大小(accept-count),当所有线程都在处理请求且队列已满时,新请求将被拒绝,这可以防止积压过多请求导致响应时间过长。2.在业务层面,使用异步Servlet并设置超时,或者使用SpringMVC的异步请求并设置超时。但是,如果用户希望设置的是每个请求从接收到响应的最大时间,那么Tomcat本身没有提供这样的配置。通常,我们会在应用层面使用过滤器或拦截器来实现超时控制。然而,我们注意到引用[4]中提到了`server.servlet.session.timeout`,这是会话超时,与请求超时无关。因此,我们需要澄清用户的需求:-如果用户想要设置的是连接超时(即等待客户端发送请求数据的超时),则配置`server.tomcat.connection-timeout`(单位毫秒)。-如果用户想要设置的是请求处理超时(即从接收到请求到完成处理时间),则SpringBoot内嵌Tomcat没有直接配置,需要采用其他方式。根据引用[5]的配置示例,它配置了`tomcat.connection-timeout`,所以我们可以确定连接超时的配置方式。由于问题中明确提到“接口请求超时时间”,我们假设用户可能指的是连接超时,因为这是Tomcat可配置的常见超时。如果是请求处理超时,则需要采用编程方式。因此,我们给出两种情况的解决方案:1.连接超时(ConnectionTimeout):在SpringBoot2.x中,使用以下配置(properties格式):server.tomcat.connection-timeout=20000#单位毫秒在yaml格式中:server:tomcat:connection-timeout:200002.请求处理超时(RequestProcessingTimeout):内嵌Tomcat不支持直接配置。替代方案:a.使用异步Servlet,并设置异步超时(async-timeout)。b.使用SpringWeb的异步请求(如Callable或DeferredResult)并设置超时。c.使用熔断器(如Hystrix)或限流组件(如Resilience4j)来设置超时。d.在业务逻辑中控制超时,例如使用Future.get(timeout,unit)或使用超时相关的注解。另外,引用[5]中有一个配置示例同时配置了`connection-timeout`和`max-connections`等,说明连接超时是直接可配置的。因此,针对用户的问题,我们首先提供连接超时的配置方法(因为这是Tomcat直接支持的),然后说明请求处理超时需要其他方法。注意:在SpringBoot1.x中,配置连接超时的属性是`server.connection-timeout`(不带tomcat),但在2.x中改为`server.tomcat.connection-timeout`。因此,版本很重要。根据引用[2],SpringBoot2.x的配置方式变化,所以我们必须使用`server.tomcat.connection-timeout`。总结回答:在SpringBoot(2.x版本)中设置Tomcat的连接超时(即接口请求超时中的连接超时)可以通过在application.properties或application.yml中配置`server.tomcat.connection-timeout`属性,单位为毫秒。示例(application.properties):server.tomcat.connection-timeout=20000示例(application.yml):server:tomcat:connection-timeout:20000如果是请求处理超时,则需要采用编程方式,例如使用异步请求并设置超时。最后,生成相关问题。</think>### 在Spring Boot中设置Tomcat接口请求超时时间 在Spring Boot应用中配置Tomcat的接口请求超时时间,主要涉及**连接超时(connection-timeout)** 的设置。该配置控制Tomcat等待客户端发送请求的最长时间,超过该时间未收到完整请求将关闭连接。具体配置方法如下: #### 配置步骤(Spring Boot 2.x及以上版本) 1. **修改配置文件** 在 `application.properties` 或 `application.yml` 中添以下配置: **properties格式**: ```properties # 设置连接超时时间为20秒(单位:毫秒) server.tomcat.connection-timeout=20000 ``` **yaml格式**: ```yaml server: tomcat: connection-timeout: 20000 # 单位:毫秒 ``` 2. **关键参数说明** - `connection-timeout`: 定义Tomcat等待客户端发送HTTP请求的**最大空闲时间**。例如: - 值 `20000` 表示20秒 - 若客户端在20秒内未发送完整请求,Tomcat将主动关闭连接 - **默认值**:`60000`(60秒) 3. **版本注意事项** - **Spring Boot 2.x
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值