Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 531|回复: 0

eclipse Filter web.xml 问题解决 异步请求@WebServlet

[复制链接]
  • TA的每日心情
    奋斗
    2024-11-24 15:47
  • 签到天数: 804 天

    [LV.10]以坛为家III

    2053

    主题

    2111

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    726782
    发表于 2021-9-2 13:27:46 | 显示全部楼层 |阅读模式

     

    <filter>  
       <filter-name>AsynServlete</filter-name>     
       <filter-class>com.kad.app.action.AsynServletT</filter-class> 
        <async-supported>true</async-supported>
         <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
    </filter>
    <filter-mapping>  
        <filter-name>AsynServlete</filter-name>
       <url-pattern>/</url-pattern> 
    </filter-mapping>

    http://localhost:8080/AppService/asyncServlet/testAsyn?  

    用上边地址请求, 爆错, 

    严重: Servlet.service() for servlet [applicationContext] in context with path [/AppService] threw exception [Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.FilterChain]: Specified class is an interface] with root cause
    org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.FilterChain]: Specified class is an interface
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:99)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveModelAttribute(HandlerMethodInvoker.java:778)
        at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:371)

    奇怪了这个异步以前用着很正常的, 就因为我注释了一下再 打开, 出了问题......这个问题磨蹭到下午..............

    起先是部署到resin 里边,程序爆错. 中间担心resin 的支持servlet 3.0 跟tomcat 有区别. 我想换成另一种不在web.xml  filter 的方式,  
    @WebServlet(asyncSupported=true,urlPatterns="/asyncComplete")   这种多方便 不用一个个写过滤的, 结果这种方式也也需要继承一个接口HttpServlet.

    还是换成webserlet的方式吧... 

    后来发现web filter 过滤的方式,过滤url-pattern 后边的/需要加上*号   .还是建议 用webservlet的方式

    这种异步有两种实现方式,一个是另起一个异步线程,另一种是线程池,请求过来的链接放到线程池里边处理,这种一般应用于并发比较大的情况.

    为了保留过滤的方式 在此记录上过滤的方式  先配置web.xml 设置一条过滤规则 

    com.kad.app.action.AsynServlet  这个是项目内接受异步请求的类
    <filter>  
       <filter-name>AsynServlete</filter-name>     
       <filter-class>com.kad.app.action.AsynServlet</filter-class> 
        <async-supported>true</async-supported>
         <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
    </filter>
    <filter-mapping>  
        <filter-name>AsynServlete</filter-name>
       <url-pattern>/*</url-pattern> 
    </filter-mapping>

    还得把servlet 下加上

    <servlet>
    <servlet-name>applicationContext</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-common.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    <async-supported>true</async-supported>
    </servlet>

    下边

    /*package com.kad.app.action;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.AsyncContext;
    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.annotation.WebServlet;
    
    import org.springframework.context.event.EventListener;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import com.google.common.eventbus.Subscribe;
    import com.google.gson.Gson;
    import com.kad.app.action.eventregservice.MessageEventReg;
    import com.kad.app.redis.impl.RedisImpl;
    import com.kad.dev.manage.DevNoOne;
    import com.kad.guavaevents.messge.RTUnLockMessage;
    import com.kad.netty.service.kdNettyServer;
    
    @Controller
    @RequestMapping("/asyncServlet")
    public class AsynServlet implements Filter 
    {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            // TODO Auto-generated method stub
            
        }
     @RequestMapping(value="/testAsyn")
      @Override
        public void doFilter(ServletRequest request, ServletResponse response,
                FilterChain chain) throws IOException, ServletException {
      request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
        //    System.out.println("start");
                PrintWriter out = response.getWriter();         
                AsyncContext asyncContext = request.startAsync();        
                asyncContext.setTimeout(5000);            
                asyncContext.addListener(new MyAsyncListener());
                Work work=new Work(asyncContext,request);         
                new Thread(work).start();
                   response = asyncContext.getResponse();
                // PrintWriter  out1 = response.getWriter();
              
               out.print("异步执行中");        
        }
        @Override
        public void destroy() {    
       }
    
    class Work  implements Runnable
    {
    
        private AsyncContext asyncContext;
        private ServletRequest request;
        public Work(AsyncContext asyncContext,ServletRequest request)
        {
            this.asyncContext = asyncContext;
            this.request = request;
          //  EventBusCenter.register(this);
        }
     
        @Override
        public void run()
        {
            
              ServletResponse   response = asyncContext.getResponse();
                 PrintWriter out;
                try {
                    out = response.getWriter();
                     out.println("后台线程执行完成");
                        out.close();
                } catch (IOException e2) {
                    // TODO Auto-generated catch block
                    e2.printStackTrace();
                }
                   
            
            String devid =request.getParameter("devid");
                
            //   PrintWriter  out = response.getWriter();
                    boolean sign=false;
                    DevNoOne dev=    DevNoOne.devone;
                     RedisImpl redis =new RedisImpl();
                while(true){                 
                   try {
                     //  out.println("后台线程执行完成");
                    Thread.sleep(100);
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                   String mess=null;
                   mess=    redis.get(devid);
                   if(mess!=null) {
                        if(request.getAsyncContext() != null && asyncContext.getTimeout()>0){
                           // try {
                             ServletResponse   response = asyncContext.getResponse();
                             PrintWriter  out = response.getWriter();
                                out.println("后台线程执行完成");
                                out.close();
                        //    } catch (IOException e) {
                            //    e.printStackTrace();
                          //  }
                            asyncContext.complete();
                            break;
                               }
                    }
              } 
        }
    }
    }
    
        
    
    
    
    */

    这种似乎是一种土方子....  中间还必须加


    一下是第二种方式 简单明了,继承 extends HttpServlet ,重写doGet 或doPost 也就是你用get方法请求就重写doget ,用post 就重写dopost
    下边程序异步work类里边逻辑没写好,不影响测试.最后的报错跟异步无关.先写上来.调试过程中间有个报错 用post方式请求. 半道出家基础不牢靠啊...
     Status 405 - HTTP method POST is not supported by this URL

    这是指重写了doget 没重写dopost导致......

    package com.kad.app.action;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.AsyncContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.springframework.stereotype.Controller;
    
    
    @WebServlet(asyncSupported=true,urlPatterns="/asyncweb")
    public class AsynWebServlet  extends HttpServlet{
    
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        
    /*    @Override
        public void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException{
            // request.setAttribute("org.apache.catalina.ASYNC_SUPPORTED", true);
            System.out.println("start");
                PrintWriter out = response.getWriter();
        
                AsyncContext asyncContext = request.startAsync();
                asyncContext.setTimeout(500000);            
                asyncContext.addListener(new MyAsyncListener());
                Work work=new Work(asyncContext,request);       
                new Thread(work).start();
                out.print("异步执行中");
                
        }*/
        @Override
         protected void doPost(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException
                {
            System.out.println("start");
            PrintWriter out = response.getWriter();
    
            AsyncContext asyncContext = request.startAsync();
            asyncContext.setTimeout(500000);            
            asyncContext.addListener(new MyAsyncListener());
            Work work=new Work(asyncContext,request);       
            new Thread(work).start();
            out.print("异步执行中");
                }
        
        class Work implements Runnable
        {
    
            private AsyncContext asyncContext;
            private ServletRequest request;
    
            public Work(AsyncContext asyncContext,ServletRequest request)
            {
                this.asyncContext = asyncContext;
                this.request = request;
            }
        
            @Override
            public void run() {      
            
                if(request.getAsyncContext() != null && asyncContext.getTimeout()>0){
                    try {
                         ServletResponse   response = asyncContext.getResponse();
                         PrintWriter  out = response.getWriter();
                        out.println("后台线程执行完成");
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    asyncContext.complete();
                }
          
              }
        }
    
    
    }

     周日传到服务器上

    出现了500 错误,

    HTTP Status 500 – Internal Server Error
    
    
    Type Exception Report
    
    Message Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection
    
    Description The server encountered an unexpected condition that prevented it from fulfilling the request.
    
    Exception
    org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection
        org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
        org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
        org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
        javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal

    服务器内部错误, 最终是因为 本地测试用的数据库的表名与线上的表名名字大小写存在不同...linux 对大小写很敏感....

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-12-22 19:20 , Processed in 0.064082 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表