首页 > 代码库 > Filter 字符编码Filter 一
Filter 字符编码Filter 一
使用字符编码Filter
package com.helloweenvsfei.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 CharacterEncodingFilter implements Filter { private String characterEncoding; private boolean enabled; @Override public void init(FilterConfig config) throws ServletException { characterEncoding = config.getInitParameter("characterEncoding"); enabled = "true".equalsIgnoreCase(characterEncoding.trim()) || "1".equalsIgnoreCase(characterEncoding.trim()); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (enabled || characterEncoding != null) { request.setCharacterEncoding(characterEncoding); response.setCharacterEncoding(characterEncoding); } chain.doFilter(request, response); } @Override public void destroy() { characterEncoding = null; }}
web.xml 配置如下
<filter> <filter-name>characterEncodingFilter</filter-name> <filter-class> com.helloweenvsfei.filter.CharacterEncodingFilter </filter-class> <init-param><!-- 编码方式 --> <param-name>characterEncoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param><!-- 是否使用编码 --> <param-name>enable</param-name> <param-value>true</param-value> </init-param></filter><filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern></filter-mapping>
注意:页面编码方式必须一致。另外如果使用GET表单提交。需要修改Tomcat /conf/server.xml 里的URIEncoding 修改代码如下
<Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding = "UTF-8"/>
基本所有的javaWeb程序都用该Filter。
附:characteEncoding.jsp验证编码器
1 <%@ page language="java" contentType="text/html; charset=UTF-8"%> 2 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 3 <html> 4 <head> 5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 6 <title>Insert title here</title> 7 <style> 8 body, input, textarea { 9 font-size: 12px; 10 }11 textarea {12 width: 400px; 13 height: 50px; 14 }15 </style>16 </head>17 <body>18 <pre>19 <b>您输入了</b>:20 ${ param.text }21 </pre>22 <form action="${ param.request.requestURL }" method="post"><textarea23 name="text">${ param.text }</textarea> <br />24 <input type="submit"></form>25 26 </body>27 </html>
Filter 字符编码Filter 一
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。