JavaWeb项目中的字符拦截器

来源:互联网 发布:jdk 7u9 windows i586 编辑:程序博客网 时间:2024/06/06 06:33

字符拦截器的目的是解决 JavaWeb项目中的乱码问题,我在做Java的时候通常都是将Eclipse的字符集设置为"UTF-8",配合字符拦截器,乱码问题几乎就在没遇到过,很简单的,进入主题了,O(∩_∩)O~

字符拦截器的源代码:

package com.STRUTSFRAMEWORK2.common.filter.character;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 CharacterFilter implements Filter {protected String encoding = null;protected FilterConfig filterConfig = null;protected boolean ignore = true;@Overridepublic void destroy() {this.encoding = null;this.filterConfig = null;}@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {if (ignore || (request.getCharacterEncoding() == null)) {String encoding = selectEncoding(request);if (encoding != null) {request.setCharacterEncoding(encoding);}}chain.doFilter(request, response);}@Overridepublic void init(FilterConfig filterConfig) throws ServletException {this.filterConfig = filterConfig;this.encoding = filterConfig.getInitParameter("encoding");String value = filterConfig.getInitParameter("ignore");if (value == null) {this.ignore = true;} else if (value.equalsIgnoreCase("true")) {this.ignore = true;} else if (value.equalsIgnoreCase("yes")) {this.ignore = true;} else {this.ignore = false;}}protected String selectEncoding(ServletRequest request) {return (this.encoding);}}

在web.xml文件中加入这个拦截器:

<?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_2_5.xsd" id="WebApp_ID" version="2.5"><display-name>STRUTS2</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>CharacterFilter</filter-name><filter-class>com.STRUTSFRAMEWORK2.common.filter.character.CharacterFilter</filter-class><init-param><param-name>encoding</param-name><param-value>UTF-8</param-value></init-param></filter><filter-mapping><filter-name>CharacterFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping></web-app>

结束了,O(∩_∩)O哈哈~