Javaweb-Filter-1- Quick Start

Filter Quick Start

Filter start learning this knowledge, the word is the role of filters and interceptors. Filter is the filter Javaweb, can block all requests to access a web resource or response action. Filter this knowledge is very important, in javaweb development, this is one we need to focus on mastering knowledge.


1. Scene

The main scenario is to use Filter intercept determine whether the login, rights management, for example, different roles are different rights, requesting operate outside of this role will be blocked. Another usage scenario is global to all projects servlet are set to UTF-8 encoding to prevent Chinese garbled situation.

Here, we look at online products, one company's login interception, use the Filter, we look at the results.

This article comes from 51CTO blog author Kaige Java (Micro Signal: kaigejava), shall not be reproduced without consent

Browser opens

image1.png

Click the image above, the structural formula of the red circle to retrieve see login interception effect.

image2.png

Immediately let you go to log in, this is a typical use Filter scene.

Here is simple to analyze this interception process:

1)  the user is not logged in, click structural formula retrieval request

2)  send the request to the corresponding server S ervlet before being processed F. ILTER to intercept

3)  In the F. ILTER code start S ession extracted user data to see whether the user is present

4)  If the user is the n- ULL , instructions are not logged in, you need to intercept

5)  If the user is in the user database, release the interception, so that a request to continue

Next, we come to a quick start Filter exercises, understand what this intercept and release process.



2 . The Filter Quick Start steps

1) create a class that implements the Filter interface

2) interface method override, doFilter is true filtration.

3) configuration in web.xml


Filter in the method of doFilter If no chain.doFilter (request, response), then the resources will not be accessible to.


Getting exercise 3.Filter

Creating a web project

image3.png

Create a Servlet class, would be to use, we simulated the structural formula above retrieve the corresponding Servlet.

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


public class ServletDemo1 extends HttpServlet {


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        System.out.println ( "ServletDemo1 run");

    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request, response);

    }

}





新建一个Filter类,实现Filter接口

image4.png


重写doFilter方法

package com.kaigejava.filter;


import java.io.IOException;


import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;


public class MyFilter implements Filter {


    @Override

    public void destroy() {

        

    }


    @Override

    public void doFilter(ServletRequest requestServletResponse responseFilterChain chain)

            throws IOExceptionServletException {

        System.out.println("doFilter执行了");

    }


    @Override

    public void init(FilterConfig filterConfigthrows ServletException {

    }


}




编辑web.xml,添加filter配置

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

 <display-name>FilterDemo</display-name>

 <welcome-file-list>

   <welcome-file>index.html</welcome-file>

   <welcome-file>index.htm</welcome-file>

   <welcome-file>index.jsp</welcome-file>

   <welcome-file>default.html</welcome-file>

   <welcome-file>default.htm</welcome-file>

   <welcome-file>default.jsp</welcome-file>

 </welcome-file-list>

 

 <filter>

     <filter-name>MyFilter</filter-name>

     <filter-class>com.anthony.filter.MyFilter</filter-class>

 </filter>

 

 <filter-mapping>

     <filter-name>MyFilter</filter-name>

     <url-pattern>/*</url-pattern>

 </filter-mapping>

 

 <servlet>

   <description></description>

   <display-name>ServletDemo1</display-name>

   <servlet-name>ServletDemo1</servlet-name>

   <servlet-class>com.anthony.servlet.ServletDemo1</servlet-class>

 </servlet>

 <servlet-mapping>

   <servlet-name>ServletDemo1</servlet-name>

   <url-pattern>/servletDemo1</url-pattern>

 </servlet-mapping>

</web-app>


运行测试一下

添加到tomcat服务器管理,启动服务,浏览器访问下

发现只在控制台输出“doFilter执行了“,并没有执行/servlet/Demo1中的打印语句,这是为什么呢?

这里解释下,我们当前代码只做了拦截,请求无法往下走,所以servlet中的打印语句没有输出,这个时候,如果想要输出打印语句,就需要放行拦截。具体代码如下。

package com.kaigjava.filter;


import java.io.IOException;


import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;


public class MyFilter implements Filter {


    @Override

    public void destroy() {

        

    }


    @Override

    public void doFilter(ServletRequest requestServletResponse responseFilterChain chain)

            throws IOExceptionServletException {

        System.out.println("doFilter执行了");

        // 放行

        chain.doFilter(requestresponse);

    }


    @Override

    public void init(FilterConfig filterConfigthrows ServletException {

    }


}


注意上面chain.doFilter(request, response)这行代码,如果不写这行,就一直拦截,请求没法往下走。这个就像我们上面登录验证拦截一样,没有登录就没有放开拦截。

继续部署上面代码,再来访问测试下,控制台输出如下内容。

doFilter执行了

ServletDemo1运行了


4.FilterChain

上面我们在web.xml中配置的Filter中过滤url设置是/*,也就是全部请求都进行拦截。在代码放行中,出现了FilterChain对象,这里我们简单来了解下这个过滤链对象。

FilterChain是servlet容器为开发任意提供的对象,它提供了对某一资源的已经过滤请求调用链的视图。过滤器使用FilterChain调用链中的下一个过滤器。如果调用的过滤器是链中的最后一个过滤器,则调用链末尾的资源。


怎么可以形成一个Filter链?只要多个Filter对同一个资源进行拦截就可以形成Filter链?

怎么确定Filter的执行顺序?由<filter-mapping>中不同Filter写的先后顺序来决定。

image5.png

这个过滤链中不同的Filter过滤先后顺序取决于,开发人员在web.xml中的<filter-mapping>写的先后顺序来决定,上面这个图就是先执行MyFilter这个过滤器,然后再执行MyFilter2这个过滤器.


Summary, Filter browser and server is in the middle position, you can intercept response to any request from the browser to the server and any.


Guess you like

Origin blog.51cto.com/kaigejava/2426917