在JSP页面及servlet的doGet()方法中处理汉字乱码的问题

在doPost()方法中使用过滤器(所有编码方式为过滤器中设置的编码方式),在doget()方法中使用iso-8859方法

doGet及在页面中处理乱码的方法

1.EncodString.java 处理乱码的类


package commons;

import java.io.UnsupportedEncodingException;

public class EncodString {
public static String trans(String in) {
   try {
    in = new String(in.getBytes("ISO-8859-1"), "UTF-8");
   } catch (UnsupportedEncodingException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   return in;
}
}

2.在页面或doGet()方法中进行转换

    String n=request.getParameter("name");

     String name=EncodString.trans(n);

doPost()方法中处理乱码的方法

1.过滤器EncodeFilter.java

package com.xuyue.exp.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 EncodeFilter implements Filter {

private String encoding="";

public void destroy() {
   // TODO Auto-generated method stub

}

public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException {
   // TODO Auto-generated method stub
   request.setCharacterEncoding(encoding);
   chain.doFilter(request, response);
}

public void init(FilterConfig config) throws ServletException {
   // TODO Auto-generated method stub
   encoding=config.getInitParameter("encoding");
}
}

2.在web.xml中配置过滤器

<filter>
<filter-name>encoding</filter-name>
<filter-class>com.xuyue.exp.filter.EncodeFilter</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>
</filter-mapping>

3.项目中所有的编码方式改为utf-8

你可能感兴趣的:(java,xml,jsp,Web,servlet)