web项目中使用过滤器防止中文乱码问题

来源:互联网 发布:熊猫采集软件下载 编辑:程序博客网 时间:2024/04/29 20:32

方法一:普通的方法

新建一个过滤器的类

package com.zb.web.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 {@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {request.setCharacterEncoding("UTF-8"); /* * 他的作用是将请求转发给过滤器链上下一个对象。这里的下一个指的是下一个filter,如果没有filter那就是你请求的资源。  * 一般filter都是一个链,web.xml 里面配置了几个就有几个。一个一个的连在一起            request -> filter1 -> filter2 ->filter3 -> .... -> request resource.         */chain.doFilter(request, response);}@Overridepublic void destroy() {// TODO Auto-generated method stub}@Overridepublic void init(FilterConfig filterConfig) throws ServletException {// TODO Auto-generated method stub}}


然后在web.xml中配置,,配置方法类似于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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">  <display-name></display-name>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list>  <filter>  <!--配置stuts2的初始化文件  -->  <filter-name>struts2</filter-name>    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  </filter>  <filter-mapping>    <filter-name>struts2</filter-name>    <url-pattern>/*</url-pattern>  </filter-mapping> <!-- 指定spring的配置文件,默认从web根目录寻找配置文件,通过spring提供的classpath:前缀指定从类路径下寻找              如果spring配置文件被命名为applicationContext.xml,并且放在WEB-INF目录下,则不需要配置<context-param>,              可以直接配listener              因为ContextLoaderListener默认在WEB-INF目录下寻找名为applicationContext.xml的文件。              若存在多个Spring配置文件,则在<param-value>中依次列出,之间以逗号隔开。  --> <context-param>   <param-name>contextConfigLocation</param-name>   <param-value>classpath:beans.xml</param-value> </context-param> <!-- 对Spring容器进行实例化 --> <listener>   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener><!--配置自己的乱码过滤器  --><filter >  <filter-name>MyFilter</filter-name>  <filter-class>com.zb.web.filter.MyFilter</filter-class></filter><filter-mapping>  <filter-name>MyFilter</filter-name>  <url-pattern>/*</url-pattern></filter-mapping> </web-app>

方法二:使用spring提供的过滤器:

<filter><filter-name>encoding</filter-name><filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>encoding</filter-name><url-pattern>/*</url-pattern>



原创粉丝点击