JavaWeb项目自定义过滤器(字符集过滤器)

一个简单的字符集过滤器

此内容旨在记录JavaWeb项目中扩展过滤器的过程,并不能完全解决项目中的乱码问题

1、 自定义一个过滤器类
package com.jiuqi.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;

/**
 1. Title:CharacterFilter
2. Description: 字符集过滤器 3. 4. @author QiuChangjin 5. @version 2018年4月13日 */
public class CharacterFilter implements Filter { private String character; // 字符集编码类型 /** * Filter的初始化 */ @Override public void init(FilterConfig filterConfig) throws ServletException { // 读取web.xml中Filter配置的初始化参数 character = filterConfig.getInitParameter("character"); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { // 读取初始化的参数character servletRequest.setCharacterEncoding(character); servletResponse.setCharacterEncoding(character); servletResponse.setContentType("text/html; charset=UTF-8"); filterChain.doFilter(servletRequest, servletResponse); // 放行,转到下一个过滤器 } /** * 在Filter销毁前,完毕某些资源的回收 */ @Override public void destroy() { } }
2、WEB-INF目录下的web.xml中增加filter,过滤器加载是有顺序的

<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>MyTestdisplay-name>
    
    <filter>
        
        <filter-name>CharacterFilterfilter-name>
        
        <filter-class>com.jiuqi.filter.CharacterFilterfilter-class>
        
        <init-param>
            
            <param-name>characterparam-name>
            
            <param-value>utf-8param-value>
        init-param>
    filter>
    
    <filter-mapping>
        
        <filter-name>CharacterFilterfilter-name>
        
        <url-pattern>/*url-pattern>
    filter-mapping>
    <welcome-file-list>
        <welcome-file>index.jspwelcome-file>
    welcome-file-list>
web-app>
3、项目代码结构

JavaWeb项目自定义过滤器(字符集过滤器)_第1张图片

你可能感兴趣的:(JavaWeb项目自定义过滤器(字符集过滤器))