java 编码过滤器



首先在web.xml中配置监听,如下:

<?xml version="1.0" encoding="UTF-8"?>
02 <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
03     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
04     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
05     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
06     <display-name></display-name>
07
08     <filter>
09         <filter-name>encodingFilter</filter-name>
10         <filter-class>com.cqcet.filter.EncodeFilter</filter-class>
11         <init-param>
12             <param-name>encoding</param-name>
13             <param-value>UTF-8</param-value>
14         </init-param>
15     </filter>
16     <filter-mapping>
17         <filter-name>encodingFilter</filter-name>
18         <url-pattern>/*</url-pattern>
19         <dispatcher>FORWARD</dispatcher>
20         <dispatcher>REQUEST</dispatcher>
21     </filter-mapping>
22 </web-app>




然后在src下编写过滤器:
      package com.cqcet.filter;
02
03 import java.io.IOException;
04
05 import javax.servlet.Filter;
06 import javax.servlet.FilterChain;
07 import javax.servlet.FilterConfig;
08 import javax.servlet.ServletException;
09 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 //实现字符编码过滤
12 public class EncodeFilter implements Filter {
13     protected String encoding = null;
14     protected FilterConfig filterConfig = null;
15
16     public void destroy() {
17         System.out.println("过滤器销毁!");
18         this.encoding = null;
19         this.filterConfig = null;
20
21     }
22
23     public void doFilter(ServletRequest request, ServletResponse response,
24             FilterChain chain) throws IOException, ServletException {
25         String encoding = this.encoding;
26         if (encoding != null) {
27             request.setCharacterEncoding(encoding);
28         else {
29             request.setCharacterEncoding("UTF-8");
30         }
31         chain.doFilter(request, response);// 传递过滤链
32
33     }
34
35     public void init(FilterConfig config) throws ServletException {
36         System.out.println("过滤器初始化!");
37         this.filterConfig = config;
38         this.encoding = filterConfig.getInitParameter("encoding");// 获取传递过来的初使化编码
39
40     }
41
42 }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值