【servlet】 过滤器模板

EncodingFilter.java

package 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 EncodingFilter implements Filter {

    private String encode;

    

    public void destroy(){

        this.encode = null;

    }

    

    public void doFilter(ServletRequest req,ServletResponse resp,FilterChain chain)

    throws ServletException,IOException{

        if(encode != null){

            req.setCharacterEncoding(encode);

            resp.setCharacterEncoding(encode);

        }

        chain.doFilter(req,resp);

    }

    

    public void init(FilterConfig config)throws ServletException{

        encode = config.getInitParameter("encode");

        System.out.println("CharacterEncoding=" + encode );

        

    }

    

    

}

 

 

 

 

web.xml 配置(WebRoot下的 WEB-INF下的 web.xml)

servlet的配置可忽略(仅保持完整性),主要看Filter的配置

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

<web-app version="3.0"

    xmlns="http://java.sun.com/xml/ns/javaee"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

  

  

  

  <filter>

      <filter-name>encode</filter-name>

      <filter-class>Filter.EncodingFilter</filter-class>

      <init-param>

          <param-name>encode</param-name>

          <param-value>utf-8</param-value>

      </init-param>

  </filter>

  

  <filter-mapping>

      <filter-name>encode</filter-name>

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

  </filter-mapping>

  

  

  <servlet>

    <servlet-name>helloyt</servlet-name>

    <servlet-class>day01.Helloyt</servlet-class>

  </servlet>



  <servlet-mapping>

    <servlet-name>helloyt</servlet-name>

    <url-pattern>/helloyt</url-pattern>

  </servlet-mapping>



</web-app>

 

你可能感兴趣的:(servlet)