概述
使用包装设计模式对request进行增强
Servlet API 中提供了一个request对象的Decorator设计模式的默认实现类++HttpServletRequestWrapper++,以避免用户在对request对象进行增强时需要实现request接口中的所有方法。
package com.kexin.web.filter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
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;
import javax.servlet.http.HttpServletResponse;
public class CharacterEncodingFilter1 implements Filter {
private FilterConfig config;
private String defaultCharset = "utf-8";
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
throws IOException, ServletException {
String charset = this.config.getInitParameter("charset");
if(charset==null){
charset = defaultCharset;
}
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
request.setCharacterEncoding(charset);
response.setCharacterEncoding(charset);
response.setContentType("text/html;charset="+charset);
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
this.config = arg0;
}
}
class MyRequest extends HttpServletRequestWrapper{
private HttpServletRequest request;
public MyRequest(HttpServletRequest request) {
super(request);
this.request = request;
}
@Override
public String getParameter(String name) {
String value = this.request.getParameter(name);
if(!request.getMethod().equalsIgnoreCase("get")){
return value;
}
if(value==null){
return null;
}
try {
return value = new String(value.getBytes("iso8859-1"),request.getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
}
最后
以上就是重要朋友为你收集整理的Servlet——使用Filter设置全局的字符编码的全部内容,希望文章能够帮你解决Servlet——使用Filter设置全局的字符编码所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复