案例:编写jsp 输入用户名,在Servlet中获取用户名,将用户名输出到浏览器上
处理请求post乱码代码
request.setCharacterEncoding("utf-8");
设置响应编码集代码
response.setContentType("text/html;charset=utf-8");
处理请求post乱码代码
request.setCharacterEncoding("utf-8");
设置响应编码集代码
response.setContentType("text/html;charset=utf-8");
经常会使用,而过滤器可以在目标资源之前执行,将很多程序中处理乱码公共代码,提取到过滤器中 ,以后程序中不需要处理编码问题了
示例代码:
package com.oterman.filter;
/**
*
* 设计一个request的包装类,重写获取请求参数的三个方法,在三个方法中解决乱码;
* 注意得须在web.xml中注册过滤器
*
*/
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;
/**
<init-param>
<param-name>charset</param-name>
<param-value>utf-8</param-value>
</init-param>
*
*/
public class EncodeFilter implements Filter {
private FilterConfig config=null;//用于获取字符集配置参数信息
private HttpServletRequest request=null;
private String charset=null;
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
this.request=(HttpServletRequest) request;
//解决post提交乱码问题;
// request.setCharacterEncoding("utf-8");
//解决输出中文乱码问题;
response.setContentType("text/html;charset=utf-8");
//传入自定义的包装的request对象;
chain.doFilter(new MyRequest((HttpServletRequest) request), response);
}
public void init(FilterConfig config) throws ServletException {
this.config=config;
this.charset=config.getInitParameter("charset");//获取配置参数中的字符集信息;
System.out.println("charset:"+charset);
}
//包装类,重写三个获取请求参数值的构造方法;
class MyRequest extends HttpServletRequestWrapper{
private boolean isNotEncode=true;
public MyRequest(HttpServletRequest request){
super(request);
}
@Override
public Map getParameterMap() {
//解决post方式乱码;
if(request.getMethod().equals("POST")){
try {
request.setCharacterEncoding(charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return request.getParameterMap();
}else{//解决get方式乱码;
if(request.getMethod().equals("GET")&&isNotEncode){
Map<String,String[]> map=request.getParameterMap();
for(Map.Entry<String, String[]> entry:map.entrySet()){
String[] values=entry.getValue();
for(int i=0;i<values.length;i++){
try {
values[i]=new String(values[i].getBytes("iso8859-1"),charset);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
isNotEncode=false;
return map;
}else{
return request.getParameterMap();
}
}
}
@Override
public String[] getParameterValues(String name) {
return (String[]) getParameterMap().get(name);
}
@Override
public String getParameter(String name) {
String[] vs=getParameterValues(name);
return vs==null? null:vs[0];
}
}
}