java web过滤器处理乱码
我们在servlet页面中读取前台的数据时 经常会出现乱码问题
而自己每次都要在servlet中使用
String encoding="utf-8"; request.setCharacterEncoding(enconding); response.setCharacterEncoding(enconding);
来进行编码的转换 会很麻烦
所以使用过滤器 我们可以避免这些重复的工作
web.xml配置
<filter> <filter-name>encodingFilter</filter-name> <filter-class>com.scx.filter.Filter</filter-class> <!-- 初始化参数 --> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <!-- filter映射关系 --> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Filter
package com.scx.filter; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class Filter implements javax.servlet.Filter{ //读取过滤器配置文件 private FilterConfig config; public void destroy() { // TODO Auto-generated method stub } public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest request=(HttpServletRequest) arg0; HttpServletResponse response=(HttpServletResponse) arg1; String encoding=config.getInitParameter("encoding"); if(encoding==null||"".equals(encoding)){ encoding="utf-8"; } request.setCharacterEncoding(encoding); response.setCharacterEncoding(encoding); chain.doFilter(request, response); } public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub config=arg0; } }
这样的话 在servlet里面读取到的数据就不会出现乱码的情况了
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持我们!
赞 (0)