search
Home类库下载java类库How to inject Service in Java Filter
How to inject Service in Java FilterNov 26, 2016 am 09:10 AM
filter

I encountered a problem in the project. Injecting Serivce into Filter failed and the injected service was always null. As shown below:

public class WeiXinFilter implements Filter{
@Autowired
private UsersService usersService;

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest)request ;
HttpServletResponse resp = (HttpServletResponse)response;
   Users users = this.usersService.queryByOpenid(openid);
}

The above usersService will report a null pointer exception.

Solution 1:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
 HttpServletRequest req = (HttpServletRequest)request;
 HttpServletRe sponse resp = (HttpServletResponse)response; ServletContext sc = req .getSession().getServletContext(); = null && usersService == null)
UsersService = (Usersservice) cxt.getBean ("UsersSservice");

Users used = this.usersservice.querybyopenid (openid);

Method 2:

public class WeiXinFilter implements Filter{

private UsersService usersService;

public void init(FilterConfig fConfig) throws ServletException {

ServletContext sc = fConfig.getServletContext( );

XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils. getWebApplicationContext(sc);                                                                                                                                                                                               getBean ('); }


Related principles:

1. How to get ServletContext:

1) Get it directly in javax.servlet.Filter
ServletContext context = config.getServletContext();

2) Get it directly in HttpServlet

this.getServletContext( )

3) In other methods, obtain

request.getSession().getServletContext();

2. WebApplicationContext and ServletContext (reprinted from: http://blessht.iteye.com/blog/2121845) through HttpServletRequest:

Spring's ContextLoaderListener is a listener that implements the ServletContextListener interface. When starting the project, the contextInitialized method will be triggered (this method mainly completes the creation of the ApplicationContext object). When the project is closed, the contextDestroyed method will be triggered (this method will perform the ApplicationContext cleanup operation). .

The process of loading the Spring context by ConextLoaderListener

①The contextInitialized method is triggered when starting the project. This method does one thing: creates a Spring context object through the initWebApplicationContext method of the parent class contextLoader.

②The initWebApplicationContext method does three things: creates a WebApplicationContext; loads the corresponding Spring file to create the Bean instance inside; and puts the WebApplicationContext into the ServletContext (which is the global variable of Java Web).

③createWebApplicationContext creates a context object and supports user-defined context objects, but they must inherit from ConfigurableWebApplicationContext, and Spring MVC uses ConfigurableWebApplicationContext as the implementation of ApplicationContext (it is just an interface) by default.

④configureAndRefreshWebApplicationContext method is used to encapsulate ApplicationContext data and initialize all related Bean objects. It will read the configuration named contextConfigLocation from web.xml, which is the spring xml data source setting, then put it into the ApplicationContext, and finally call the legendary refresh method to perform the creation of all Java objects.

⑤After completing the creation of the ApplicationContext, put it into the ServletContext and pay attention to the key value constant it stores.

Method 3:

Directly use HandlerInterceptor or HandlerInterceptorAdapter in spring mvc to replace Filter:

public class WeiXinInterceptor implements HandlerInterceptor {
   @Autowired    private UsersService usersService;  
   
   @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        // TODO Auto-generated method stub
       return false;
   }

   @Override    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)            throws Exception {        // TODO Auto-generated method stub        
   }

   @Override    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {        // TODO Auto-generated method stub        
   }
}

配置拦截路径:

   
       
           
           
       
   
   

 

Filter 中注入 Service 的示例:

public class WeiXinFilter implements Filter{    
   private UsersService usersService;    
   public void init(FilterConfig fConfig) throws ServletException {}    public WeiXinFilter() {}    public void destroy() {}    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       HttpServletRequest req = (HttpServletRequest)request;
       HttpServletResponse resp = (HttpServletResponse)response;
       
       String userAgent = req.getHeader("user-agent");        if(userAgent != null && userAgent.toLowerCase().indexOf("micromessenger") != -1){    // 微信浏览器
           String servletPath = req.getServletPath();
           String requestURL = req.getRequestURL().toString();
           String queryString = req.getQueryString();
           if(queryString != null){                if(requestURL.indexOf("mtzs.html") !=-1 && queryString.indexOf("LLFlag")!=-1){
                   req.getSession().setAttribute("LLFlag", "1");
                   chain.doFilter(request, response);                    return;
               }
           }
           
           String openidDES = CookieUtil.getValueByName("openid", req);
           String openid = null;            if(StringUtils.isNotBlank(openidDES)){                try {
                   openid = DesUtil.decrypt(openidDES, "rxxxxxxxxxde");    // 解密获得openid
               } catch (Exception e) {
                   e.printStackTrace();
               }    
           }
           // ... ...
           String[] pathArray = {"/weixin/enterAppFromWeiXin.json", "/weixin/getWeiXinUserInfo.json",                                    "/weixin/getAccessTokenAndOpenid.json", "/sendRegCode.json", "/register.json",
                                   "/login.json", "/logon.json", "/dump.json", "/queryInfo.json"};
           List pathList = Arrays.asList(pathArray);            
           String loginSuccessUrl = req.getParameter("path");
           String fullLoginSuccessUrl = "http://www.axxxxxxx.cn/pc/";            if(requestURL.indexOf("weixin_gate.html") != -1){
               req.getSession().setAttribute("loginSuccessUrl", loginSuccessUrl);
          // ... ...
           }
            ServletContext sc = req.getSession().getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
        
            if(cxt != null && cxt.getBean("usersService") != null && usersService == null)
               usersService = (UsersService) cxt.getBean("usersService");
        
            Users users = this.usersService.queryByOpenid(openid);
           // ... ...            if(pathList.contains(servletPath)){    // pathList 中的访问路径直接 pass
chain.doFilter(request, response);                                                                                                                                                                String llFlag = (String) req.getSession() .getAttribute("LLFlag");                    if(llFlag != null && llFlag.equals("1")){                                                                                                                                                     return;
                                                                                                     ..// 3. Get WeChat’s openid from Tencent server ,
                                                                                                                                                                                                                                                                             // Already logged in                       // 4. Already Treatment when logging in a chain.dofilter (request, response);
Return;
}}} else {// non -WeChat browser chain.dofilter (request, response);
}}}








Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
解决“[Vue warn]: Failed to resolve filter”错误的方法解决“[Vue warn]: Failed to resolve filter”错误的方法Aug 19, 2023 pm 03:33 PM

解决“[Vuewarn]:Failedtoresolvefilter”错误的方法在使用Vue进行开发的过程中,我们有时候会遇到一个错误提示:“[Vuewarn]:Failedtoresolvefilter”。这个错误提示通常出现在我们在模板中使用了一个未定义的过滤器的情况下。本文将介绍如何解决这个错误并给出相应的代码示例。当我们在Vue的

Springboot中filter的原理与注册方法是什么Springboot中filter的原理与注册方法是什么May 11, 2023 pm 08:28 PM

1、filter先看下web服务器的filter所处的位置。filter是一个前后连接的链,前面处理完成之后传递给下一个filter处理。1.1filter的接口定义publicinterfaceFilter{//初始化方法,整个生命周期中只执行一次。//在init方法成功(失败如抛异常等)执行完前,不能提供过滤服务。//参数FilterConfig用于获取初始化参数publicvoidinit(FilterConfigfilterConfig)throwsServletException;//

Filter在java中如何过滤Filter在java中如何过滤Apr 18, 2023 pm 11:04 PM

说明1、如果Lambda参数生成true值,则filter(能够生成boolean结果的Lambda)将生成元素;2、生成false时,就不再使用此元素。实例创建一个List集合:ListstringCollection=newArrayList();stringCollection.add("ddd2");stringCollection.add("aaa2");stringCollection.add("bbb1");stringC

CSS 视觉属性解析:box-shadow,text-shadow 和 filterCSS 视觉属性解析:box-shadow,text-shadow 和 filterOct 20, 2023 pm 12:51 PM

CSS视觉属性解析:box-shadow,text-shadow和filter引言:在网页设计和开发中,使用CSS可以为元素添加各种视觉效果。本文将重点介绍CSS中的box-shadow,text-shadow和filter这三个重要属性,包括其使用方法和效果展示。下面我们分别详细解析这三个属性。一、box-shadow(盒子阴影)box-shado

CSS 模糊属性详解:filter 和 backdrop-filterCSS 模糊属性详解:filter 和 backdrop-filterOct 20, 2023 pm 04:48 PM

CSS模糊属性详解:filter和backdrop-filter导语:在设计网页时,我们常常需要一些特效来增加页面的视觉吸引力。而模糊效果是其中一种常见的特效之一。CSS提供了两种模糊属性:filter和backdrop-filter,它们分别用于对元素内容以及背景内容进行模糊处理。本文将详细介绍这两个属性,并提供一些具体的代码示例。一、filt

怎么在SpringBoot2中整合Filter怎么在SpringBoot2中整合FilterMay 16, 2023 pm 02:46 PM

首先定义一个统一访问URL拦截的Filter。代码如下:publicclassUrlFilterimplementsFilter{privateLoggerlog=LoggerFactory.getLogger(UrlFilter.class);@OverridepublicvoiddoFilter(ServletRequestrequest,ServletResponseresponse,FilterChainchain)throwsIOException,ServletException{H

Java 8中的Optional类:如何使用filter()方法过滤可能为空的值Java 8中的Optional类:如何使用filter()方法过滤可能为空的值Aug 01, 2023 pm 05:27 PM

Java8中的Optional类:如何使用filter()方法过滤可能为空的值在Java8中,Optional类是一个非常有用的工具,它允许我们更好地处理可能为空的值,避免了NullPointerException的发生。Optional类提供了许多方法来操作潜在的空值,其中一个重要的方法是filter()。filter()方法的作用是,如果Option

Vue中如何利用filter对数据进行格式化和处理Vue中如何利用filter对数据进行格式化和处理Oct 15, 2023 pm 03:50 PM

Vue中利用filter对数据进行格式化和处理在Vue中,我们可以通过使用filter来对数据进行格式化和处理。Filter是一种可以在模板中直接调用的函数,它可以对要显示的数据进行处理并返回处理后的结果。在本文中,我们将介绍如何使用filter来格式化和处理数据,并提供具体的代码示例。注册filter在Vue实例中,我们需要先注册一个filter,以便在模

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)