Home PC Games Linux Windows Database Network Programming Server Mobile  
  Home \ Programming \ Java filter     - Forgot Linux root password (Linux)

- Linux LVM Logical Volume Management to resize partitions (Linux)

- Linux Platform Oracle 11g Single Instance Installation Deployment Configuration Quick Reference (Database)

- Configuring s3c-linux- appears Unable to find the QT3 installation (Linux)

- Android application simulates the phone keypad (Programming)

- CentOS 7.0 local address and configure yum source address priority (Linux)

- Storm how to assign tasks and load balancing (Programming)

- Ubuntu achieve initialization iptables (Linux)

- Zabbix using Omsa monitor hardware information of Dell server (Server)

- Use Vagrant build cross-platform development environment for Python (Server)

- Add a custom encryption algorithm in OpenSSL (Linux)

- To install Xen in Ubuntu 12.04 (Linux)

- Use Visual Studio 2015 to develop Android program (Programming)

- Google open source TCP team repaired the Linux kernel TCP flaw (Linux)

- CentOS Linux Optimization and real production environment (Linux)

- MySQL composite partition (Database)

- Postgres-X2 deployment steps (Database)

- ORA-12154: TNS: could not resolve the connect identifier specified solve (Database)

- High-performance open-source http accelerator Varnish introduce (Server)

- MariaDB 10.0.X, the dynamic column support JSON format to obtain data (Database)

  Java filter
  Add Date : 2017-04-13      
  Read catalog

First, filter overview
Second, a simple filter implementation process
Third, the deployment of the filter
Fourth, the filter Application examples

First, filter overview

Java Web filter is one of the three components, it is very similar to the Servlet. For Web applications, the filter is a Web that resides on the server side component, it can intercept requests and responses between the client and the resources and the information filtered. It will filter paper and the implementation mechanism and application of a simple summary.

When the Web container receives a request for resources, it is determined whether a filter is associated with this resource, so if there is a request to the filter container for processing.

In the web application can be deployed to form a plurality of filters filter chain, in the resource request, the filter chain filter will in turn process the request (order execution order is deployed in web.xml file), and the request is passed to the next filter, until the target resource. When sending the response, it is the reverse order of the response process, until the client.

Filter scenarios have a few main points:

Do preprocessing before performing the target resource, such as setting the encoding
Whether through conditional release, for example, check whether the current user has logged in
After the target resources for the implementation of the follow-up to do some processing, such as the output data of the target resource is processed
Second, a simple filter implementation process

Write a filter is to write a class, and the class to achieve Filter interface. Filter interface defines three methods, init (), doFilter () and destory (). They constitute the implementation of the filter life cycle.

init (FilterConfig): will be created when the server starts Filter instance, and each type of Filter to create only one instance, no longer create! After creating Filter instance, will immediately call the init () method to complete initialization, this method is executed only once;
 doFilter (ServletRequest req, ServletResponse res, FilterChain chain): this method each time the user access the "target resource (< url-> pattern> index.jsp < / url-pattern>)" is executed, if you need to "release" then you need to call the FilterChain doFilter (ServletRequest, ServletResponse) method, if you do not call the FilterChain doFilter () method, then the target resource can not be performed;
destroy (): Filter server After you create an object, the Filter into the cache has been used, usually does not destroy it. General Filter object will be destroyed when the server is shut down, the object before destroying Filter server calls the Filter object destory () method.
The following code is not only a realization of the Filter interface filters:

public class FilterDemo1 implements Filter
    public void init (FilterConfig filterConfig) throws ServletException
    public void doFilter (ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException
        response.setContentType ( "text / html; charset = GB2312");
        PrintWriter out = response.getWriter ();
        out.println ( "filter to intercept you!");
        chain.doFilter (request, response);
        out.close ();
    public void destroy ()
After the write filter through the web.xml file to configure them, a method similar to the configuration of the Servlet.

< ? Xml version = "1.0" encoding = "UTF-8"?>
< Web-app xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns = "http://java.sun.com/xml/ns/javaee" xsi: schemaLocation = "http : //java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "id =" WebApp_ID "version =" 2.5 ">
  < Display-name> day_0701 < / 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> FilterDemo1 < / filter-name>
    < Filter-class> com.test.filter.FilterDemo1 < / filter-class>
  < / Filter>
  < Filter-mapping>
    < Filter-name> FilterDemo1 < / filter-name>
    < Url-pattern> /1.jsp < / url-pattern>
  < / Filter-mapping>
< / Web-app>
Then under WebContent directory, create a jsp file:

< % @ Page language = "java" contentType = "text / html; charset = UTF-8" pageEncoding = "UTF-8"%>
< ! DOCTYPE HTML PUBLIC "- // W3C // DTD HTML 4.01 Transitional // EN">
< Html>
    < Head>
        < Title> Here insert the title < / title>
    < / Head>
    < Body>
        This is a test page!
    < / Body>
< / Html>
When a request to access the file 1.jsp

Analysis: Because the filter is associated with 1.jsp file, so the web container request prior to filter processing, the output "filter to intercept you", the filter on request "release", it is also output "this is a test page."

Third, the deployment of the filter

The filter is deployed in the < filter> and < filter-mapping> element to complete.

3.1 filters intercept way

There are four ways to intercept filters, namely: REQUEST, FORWARD, INCLUDE, ERROR.

REQUEST: execution filter direct access to the target resource. Including: direct access to the address bar, the form is submitted, hyperlinks, redirection, as long as the address bar, you can see the path of the target resource is REQUEST;
FORWARD: Forwarding access enforcement filters. Including RequestDispatcher # forward () method, < jsp: forward> tag are forwarded access;
INCLUDE: contains access to perform the filter. Including RequestDispatcher # include () method, < jsp: include> tags are contained visit;
ERROR: When the target resource is configured as < error-page> in web.xml when, and really appeared abnormal, when forwarded to the target resource, executes the filter.
Intercepting Mode is < dispatcher> < / dispatcher> set, the default is REQUEST way.

3.2 Setting the target resource

Can be set by < url-pattern> or < servlet-name> of the target resource, specify the URL style filter link in the < url-pattern>; and the < servlet-name> Specifies the filter specified Servlet, users visit < resources or < servlet-name url-pattern> element specifies the URL on> Servlet element when specified, the filter will be invoked by the container.

 < Filter-mapping>
    < Filter-name> LoginFilter < / filter-name>
    < Url-pattern> /2.jsp < / url-pattern>
    < Servlet-name> DemoServlet < / servlet-name>
  < / Filter-mapping>
Fourth, the filter Application examples

Through the filter can solve the garbage problem page, the code is as follows:

public class EncodingFilter implements Filter {
    public void destroy () {
    public void doFilter (ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        // Handle post requests coding problems
        request.setCharacterEncoding ( "utf-8");
        HttpServletRequest req = (HttpServletRequest) request;
        / *
         * Processing coding problems GET requests
         * Packet transfer request
         * 1. Write a request for decoration
         * 2. When released, using our own request
         * /
        if (req.getMethod (). equals ( "GET")) {
            EncodingRequest er = new EncodingRequest (req);
            chain.doFilter (er, response);
        } Else if (req.getMethod (). Equals ( "POST")) {
            chain.doFilter (request, response);
    public void init (FilterConfig fConfig) throws ServletException {

/ **
 * Decoration reqeust
 * /
public class EncodingRequest extends HttpServletRequestWrapper {
    private HttpServletRequest req;
    public EncodingRequest (HttpServletRequest request) {
        super (request);
        this.req = request;
    public String getParameter (String name) {
        String value = req.getParameter (name);
        // Deal with encoding issues
        try {
            value = new String (value.getBytes ( "iso-8859-1"), "utf-8");
        } Catch (UnsupportedEncodingException e) {
            throw new RuntimeException (e);
        return value;
- Use backup-manager system backup on Linux (Linux)
- Tomcat installation under Linux (Server)
- Oracle 11g em start newspaper site's security certificate has a solution to the problem (Database)
- Keepalived + HAProxy high availability load balancing (Server)
- The formatted Linux hard drive and mount (Linux)
- Python is not C (Programming)
- Ubuntu 14.04.02 LTS startup items erroneous writing / dev / sda1 (win 7 loader) Repair (Linux)
- RHEL 6.6 install GNOME desktop environment (Linux)
- Linux Network Programming --TCP and UDP datagram type Explanation (Programming)
- Compare Swift achieve rapid sorting and sorted Methods (Programming)
- Using PHP MySQL library (Programming)
- Oracle archive log size than the size of the online journal of the much smaller (Database)
- Java object serialization and deserialization (Programming)
- Linux command execution judge sentences -;, &&, || (Linux)
- Install Open vSwitch under CentOS 6.5 (Linux)
- Sublime Text - Opens the current file in a browser (Linux)
- How to configure MongoDB replica set (Database)
- Live Wallpaper for Linux release adds dynamic background (Linux)
- On event processing browser compatibility notes (Programming)
- Install Java JDK 8 in CentOS 7 / 6.5 / 6.4 (Linux)
  CopyRight 2002-2020 newfreesoft.com, All Rights Reserved.