Servlet & JSP - Decorating Requests and Responses
Servlet API 提供了四个包装类:ServletRequestWrapper、ServletResponseWrapper、HttpServletRequestWrapper、HttpServletReponseWrapper。这些包装类使用的频率很小,但却很有用。当 servlet 接收到请求,service 方法被调用时,我们可以使用这些包装类来包装 servlet 容器传递过来的 request 和 response 对象以改变 request 和 response 的行为。例如,当 HTTP 请求的参数包含中文字符时,不想在每个 servlet 里面都对其转换编码,可以使用过滤器去拦截请求,然后使用 HttpServletRequestWrapper 去装饰该请求,覆盖 getParameter、getParameterValues 等方法,使这些方法返回的参数是转换过编码的。
应用示例
自定义的 HttpServletRequestWrapper:
package com.huey.hello.wrapper; import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper; public class CharsetServletRequestWrapper extends HttpServletRequestWrapper { private HttpServletRequest request;
private String oldCharset;
private String newCharset; public CharsetServletRequestWrapper(HttpServletRequest request, String oldCharset, String newCharset) {
super(request);
this.request = request;
this.oldCharset = oldCharset;
this.newCharset = newCharset;
} @Override
public String getParameter(String name) {
return convertCharset(request.getParameter(name));
} @Override
public String[] getParameterValues(String name) {
return convertCharset(request.getParameterValues(name));
} @Override
public Map<String, String[]> getParameterMap() {
final Map<String, String[]> parameterMap = request.getParameterMap();
Map<String, String[]> newMap = new Map<String, String[]>() {
@Override
public int size() {
return parameterMap.size();
} @Override
public boolean isEmpty() {
return parameterMap.isEmpty();
} @Override
public boolean containsKey(Object key) {
return parameterMap.containsKey(key);
} @Override
public boolean containsValue(Object value) {
return parameterMap.containsValue(value);
} @Override
public String[] get(Object key) {
return convertCharset(parameterMap.get(key));
} @Override
public String[] put(String key, String[] value) {
return parameterMap.put(key, value);
} @Override
public String[] remove(Object key) {
return parameterMap.remove(key);
} @Override
public void putAll(Map<? extends String, ? extends String[]> m) {
parameterMap.putAll(m);
} @Override
public void clear() {
parameterMap.clear();
} @Override
public Set<String> keySet() {
return parameterMap.keySet();
} @Override
public Collection<String[]> values() {
return convertCharset(parameterMap.values());
} @Override
public Set<Map.Entry<String, String[]>> entrySet() {
return convertCharset(parameterMap.entrySet());
}
}; return newMap;
} private String convertCharset(String str) {
String newStr;
try {
newStr = new String(str.getBytes(oldCharset), newCharset);
} catch (UnsupportedEncodingException e) {
newStr = str;
}
return newStr;
} private String[] convertCharset(String[] strs) {
String[] newStrs = null;
if (strs != null) {
newStrs = new String[strs.length];
for (int i = 0; i < newStrs.length; i++) {
newStrs[i] = convertCharset(strs[i]);
}
}
return newStrs;
} private Collection<String[]> convertCharset(Collection<String[]> valueCollection) {
Collection<String[]> newCollection = new ArrayList<String[]>();
for (String[] values : valueCollection) {
newCollection.add(convertCharset(values));
}
return newCollection;
} private Set<Entry<String, String[]>> convertCharset(Set<Map.Entry<String, String[]>> entrySet) {
Set<Map.Entry<String, String[]>> newSet = new HashSet<Map.Entry<String, String[]>>();
for (final Map.Entry<String, String[]> entry : entrySet) {
Map.Entry<String, String[]> newEntry = new Map.Entry<String, String[]> () {
@Override
public String getKey() {
return entry.getKey();
}
@Override
public String[] getValue() {
return convertCharset(entry.getValue());
}
@Override
public String[] setValue(String[] value) {
return entry.setValue(value);
}
};
newSet.add(newEntry);
}
return newSet;
} }
过滤器:
package com.huey.hello.filters; 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;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest; import com.huey.hello.wrapper.CharsetServletRequestWrapper; @WebFilter(filterName="charsetFilter", urlPatterns = {"/*"},
initParams = {
@WebInitParam(name = "oldCharset", value = "ISO-8859-1"),
@WebInitParam(name = "newCharset", value = "UTF-8"),
})
public class CharsetFilter implements Filter { private String oldCharset;
private String newCharset; @Override
public void init(FilterConfig filterConfig) throws ServletException {
oldCharset = filterConfig.getInitParameter("oldCharset");
newCharset = filterConfig.getInitParameter("newCharset");
} @Override
public void destroy() {
} @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding(newCharset);
response.setContentType("text/plain;charset=" + newCharset); HttpServletRequest httpRequest = (HttpServletRequest) request;
CharsetServletRequestWrapper requestWrapper = new CharsetServletRequestWrapper(httpRequest, oldCharset, newCharset);
chain.doFilter(requestWrapper, response);
} }
Servlet & JSP - Decorating Requests and Responses的更多相关文章
- NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config
今天调试SSM框架项目后台JSOn接口,报出来一个让人迷惑的错误:NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config 上网查了一下别人的博 ...
- MVC开发模式之Servlet+jsp+javaBean
Servlet+jsp+JavaBean组合开发是一种MVC开发模式,控制器Controller采用Servlet.模型Model采用JavaBean.视图View采用JSP. 1.Web开发的请求- ...
- springMVC: java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config
springMVC开发web的时候,报错:java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config 原因:未引入jstl ...
- Struts框架——(一)用Servlet + JSP演示Struts基本原理
一. 用Servlet + JSP演示Struts基本原理 struts是开源项目.它通过采用 Java Servlet/JSP 技术,实现了基于Java EE Web应用的MVC的应用框架.Stru ...
- Javabean+servlet+JSP(html)实例应用
大家都知道Javabean+servlet+JSP是最简单的MVC模式.的确,在一个小型的项目中,这个模式完全够用. 它优雅并且简洁.加上jQueryui的完美展示效果,让这个模式看起来非常合适.当然 ...
- 报错:严重: Servlet.service() for servlet [jsp] in context with path [/20161116-Struts2-6] threw exception [/index.jsp (line: 13, column: 20) No tag "textfiled" defined in tag library imported with prefix
严重: Servlet.service() for servlet [jsp] in context with path [/20161116-Struts2-6] threw exception [ ...
- servlet+jsp+java实现Web 应用
servlet+jsp+java实现Web 应用 用java来构建一个web应用是特别容易的事情,jsp和php很像,可以嵌套在html中.程序的结构很简单,也很清楚,本文主要记录下大概的开发过程和环 ...
- javaweb学习总结(二十二)——基于Servlet+JSP+JavaBean开发模式的用户登录注册
一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp ...
- 在Eclipse中配置Tomcat 创建和运行Servlet/JSP
在Eclipse中配置Tomcat 创建和运行Servlet/JSP 步骤一:在Eclipse中配置Tomcat(注意下载Eclipse IDE for Java EE Developers) (1) ...
随机推荐
- php加速缓存Xcache的安装与配置
安装环境:centos 6.5 32bit php5.5.7 nginx1.6.0 [root@localhost opt]# wget http://xcache.lighttpd.net/pub ...
- OpenXml操作Word的一些操作总结. - 天天不在
OpenXml相对于用MS提供的COM组件来生成WORD,有如下优势: 1.相对于MS 的COM组件,因为版本带来的不兼容问题,及各种会生成WORD半途会崩溃的问题. 2.对比填满一张30多页的WOR ...
- Android中TextView输入字数统计和限制
在Android开发应用的时候,文本编辑框中最多输入140个字,经常会显示还剩多少字以限制用户输入的字数, EditText content;//定义一个文本输入框 TextView hasnum;/ ...
- iframe 处理
import java.io.File; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org ...
- Fiddler On Linux
参考链接: http://www.development-cycle.com/2013/08/debugging-web-applications-with-fiddler-on-linux/ htt ...
- 【转】由DFT推导出DCT
原文地址:http://blog.sina.com.cn/s/blog_626631420100xvxd.htm 已知离散傅里叶变换(DFT)为: 由于许多要处理的信号都是实信号,在使用DFT时由于傅 ...
- bzoj 1951 [Sdoi2010]古代猪文(数论知识)
[题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1951 [思路] 一道优(e)秀(xin)的数论题. 首先我们要求的是(G^sigma{ ...
- NOIP2002 字串变换
题二 字串变换 (存盘名: NOIPG2) [问题描述]: 已知有两个字串 A$, B$ 及一组字串变换的规则(至多6个规则): A1$ -> B1$ A2$ -> B2$ 规则的含义为: ...
- 100个常用的linux命令
1,echo “aa” > test.txt 和 echo “bb” >> test.txt //>将原文件清空,并且内容写入到文件中,>>将内容放到文件的尾部 2 ...
- js关键字
这已经是我第二次遇到这个问题了..关于关键字,用来做函数的命名,,,在高清上没问题,标清上秒死...页面都出不来...wtf...做个记录.. js关键字http://www.itxueyuan.or ...