javaweb开发之解决全站乱码
当我们开发web网站的时候偶尔会出现乱码问题,出现问题之原因是出现中文字符。
不解释了直接上代码
import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Map; import javax.servlet.Filter; 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.HttpServletRequestWrapper; public class EncodingFilter implements Filter { FilterConfig config = null; String encode = "utf-8"; @Override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { response.setContentType("text/html;charset="+encode); //--解决响应乱码 chain.doFilter(new MyHttpServletRequest((HttpServletRequest) request), response);//--包装改造request中和获取请求参数相关的方法解决请求参数乱码 } @Override public void init(FilterConfig filterConfig) throws ServletException { this.config = filterConfig; encode = config.getInitParameter("encode"); } class MyHttpServletRequest extends HttpServletRequestWrapper { HttpServletRequest request; public MyHttpServletRequest(HttpServletRequest request) { super(request); this.request = request; } @Override public Map<String, String[]> getParameterMap() { Map<String, String[]> map = request.getParameterMap(); try { for (Map.Entry<String, String[]> entity : map.entrySet()) { String[] value = entity.getValue(); for (int i = 0; i < value.length; i++) { value[i] = new String(value[i].getBytes("iso8859-1"), encode); } } return super.getParameterMap(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } @Override public String[] getParameterValues(String name) { return (String[]) getParameterMap().get(name); } @Override public String getParameter(String name) { return getParameterValues(name)[0]==null?null:getParameterValues(name)[0]; } } }
web.xml 配置如下
<filter> <description>全站乱码过滤器</description> <filter-name>encodeFilter</filter-name> <filter-class>com.cbd.filter.EncodingFilter</filter-class> <init-param> <param-name>encode</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodeFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>