HttpServletRequestWrapper的使用
老大给了一个很实际的需求:有段程序,使用Http的方式与合作商交互,而且是明文传输数据。我方的代码已经打包放在服务器上运行了很长时间,这时合作商突然要求修改数据传输的方式,要求加密后再传输,而我方的原有的代码不能改变,以防止引发其它问题。
问:如何在不修改我方现有的代码的前提下,满足合作商的要求?
可能大家都想到了,只要加上一个过滤器Filter不就可以了吗?事实就是这样的,采用Filter+HttpServletRequestWrapper就可以解决这个问题。
首先:在filter中拦截到加密后的请求,将参数解密,然后组装成一个新的明文请求串。
然后:重写HttpServletRequestWrapper中的getInputStream()方法,让其返回过滤器解析后的明文串即可。
具体代码解释如下。
首先我写了两个一摸一样的servlet,一个用来直接接收合作商的明文请求并打印;一个用来接收Filter处理后的合作商的请求并打印(Filter中将合作商加密后的参数解密再传给这个Servlet)。
- @WebServlet("/SiServlet")
- public class SiServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
- /**
- * @see HttpServlet#HttpServlet()
- */
- public SiServlet() {
- super();
- }
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doGet(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- this.doPost(request, response);
- }
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
- * response)
- *
- */
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- String bizBindMsg = IOUtils.toString(request.getInputStream(), "UTF-8");
- bizBindMsg = URLDecoder.decode(bizBindMsg.toString(), "UTF-8");
- System.out.println("SiServlet接收到请求为: " + bizBindMsg);
- response.getWriter().write("==========success=========");
- }
- }
- @WebServlet("/SiServletNormal")
- public class SiServletNormal extends HttpServlet {
- private static final long serialVersionUID = 1L;
- /**
- * @see HttpServlet#HttpServlet()
- */
- public SiServletNormal() {
- super();
- }
- /**
- * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
- * response)
- */
- protected void doGet(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- this.doPost(request, response);
- }
- /**
- * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
- * response)
- *
- */
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- String bizBindMsg = IOUtils.toString(request.getInputStream(), "UTF-8");
- bizBindMsg = URLDecoder.decode(bizBindMsg.toString(), "UTF-8");
- System.out.println("SiServletNormal接收到请求为: " + bizBindMsg);
- response.getWriter()
- .write("==========SiServletNormal Success=========");
- }
- }
然后我使用HttpClient模拟了一下合作商发送明文和密文请求的过程,加密使用Base64简单模拟一下。
- public class AdcClient {
- private HttpPost httpPost = null;
- private HttpClient client = null;
- private List<NameValuePair> pairs = null;
- public AdcClient() {
- httpPost = new HttpPost("http://localhost:8080/filtertest/SiServlet");
- client = new DefaultHttpClient();
- }
- /**
- * 发送明文消息
- *
- */
- public void sendMsg() {
- try {
- httpPost = new HttpPost(
- "http://localhost:8080/filtertest/SiServletNormal");
- pairs = new ArrayList<NameValuePair>();
- pairs.add(new BasicNameValuePair(("param1"), "obama没加密"));
- pairs.add(new BasicNameValuePair(("param2"), "男没加密"));
- pairs.add(new BasicNameValuePair(("param3"), "汉没加密"));
- pairs.add(new BasicNameValuePair(("param4"), "山东没加密"));
- httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
- // httpPost.setHeader("Cookie", "TOKEN=1234567890");
- HttpResponse response = client.execute(httpPost);
- HttpEntity entity = response.getEntity();
- BufferedReader br = new BufferedReader(new InputStreamReader(
- entity.getContent()));
- String line = null;
- StringBuffer result = new StringBuffer();
- while ((line = br.readLine()) != null) {
- result.append(line);
- line = br.readLine();
- }
- System.out.println("来自SiServletNormal的响应为:" + result.toString());
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * 发送加密后的消息
- */
- public void sendEncryptMsg() {
- try {
- pairs = new ArrayList<NameValuePair>();
- pairs.add(new BasicNameValuePair(("param1"), Base64EnDecrypt
- .base64Encode("obama")));
- pairs.add(new BasicNameValuePair(("param2"), Base64EnDecrypt
- .base64Encode("男")));
- pairs.add(new BasicNameValuePair(("param3"), Base64EnDecrypt
- .base64Encode("汉")));
- pairs.add(new BasicNameValuePair(("param4"), Base64EnDecrypt
- .base64Encode("山东")));
- HttpEntity reqEntity = new UrlEncodedFormEntity(pairs, "UTF-8");
- httpPost.setEntity(reqEntity);
- // httpPost.setHeader("Cookie", "TOKEN=1234567890");
- HttpResponse response = client.execute(httpPost);
- /**
- * 获取响应信息
- */
- HttpEntity entity = response.getEntity();
- BufferedReader br = new BufferedReader(new InputStreamReader(
- entity.getContent()));
- String line = null;
- StringBuffer result = new StringBuffer();
- while ((line = br.readLine()) != null) {
- result.append(line);
- line = br.readLine();
- }
- System.out.println("来自SiServlet的响应为:" + result.toString());
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * @param args
- * @throws UnsupportedEncodingException
- */
- public static void main(String[] args) throws UnsupportedEncodingException {
- new AdcClient().sendMsg();
- new AdcClient().sendEncryptMsg();
- }
- }
重点是下面的这个HttpServletRequestWrapper,我重写了它的getInputStream()方法,这个方法返回包含明文的ServletInputStream
- public class MyRequestWrapper extends HttpServletRequestWrapper {
- private HttpServletRequest request;
- public MyRequestWrapper(HttpServletRequest request) {
- super(request);
- this.request = request;
- }
- /**
- * 先解密,获取明文;然后将明文转化为字节数组;然后再去读取字节数组中的内容
- */
- @Override
- public ServletInputStream getInputStream() {
- String bizBindMsg = null;
- ServletInputStream stream = null;
- try {
- stream = request.getInputStream();
- bizBindMsg = IOUtils.toString(stream, "UTF-8");
- } catch (IOException e) {
- e.printStackTrace();
- }
- try {
- bizBindMsg = URLDecoder.decode(bizBindMsg.toString(), "UTF-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- System.out.println("MyRequestWrapper接收到的请求为: " + bizBindMsg);
- /**
- * 获取加密的值进行解密
- */
- final StringBuffer reqStr = new StringBuffer();
- reqStr.append("param1=").append(
- Base64EnDecrypt.base64Decode(bizBindMsg.substring(
- bizBindMsg.indexOf("param1=") + 7,
- bizBindMsg.indexOf("param2="))));
- reqStr.append("&");
- reqStr.append("param2=").append(
- Base64EnDecrypt.base64Decode(bizBindMsg.substring(
- bizBindMsg.indexOf("param2=") + 7,
- bizBindMsg.indexOf("param3="))));
- reqStr.append("&");
- reqStr.append("param3=").append(
- Base64EnDecrypt.base64Decode(bizBindMsg.substring(
- bizBindMsg.indexOf("param3=") + 7,
- bizBindMsg.indexOf("param4="))));
- reqStr.append("&");
- reqStr.append("param4=").append(
- Base64EnDecrypt.base64Decode(bizBindMsg.substring(bizBindMsg
- .indexOf("param4=") + 7)));
- System.out.println("********MyRequestWrapper接收到的解密后的请求为*********");
- System.out.println(reqStr.toString());
- /**
- * 将解密后的明文串放到buffer数组中
- */
- byte[] buffer = null;
- try {
- buffer = reqStr.toString().getBytes("UTF-8");
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- final ByteArrayInputStream bais = new ByteArrayInputStream(buffer);
- ServletInputStream newStream = new ServletInputStream() {
- @Override
- public int read() throws IOException {
- return bais.read();
- }
- };
- return newStream;
- }
- }
最后是简单的Filter,在这里将加密后的ServletRequest重新包装,交给SiServlet进行处理
- public class EncryptFilter implements Filter {
- @Override
- public void destroy() {
- }
- @Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- chain.doFilter(new MyRequestWrapper((HttpServletRequest) request),
- response);
- }
- @Override
- public void init(FilterConfig arg0) throws ServletException {
- }
- }
我的web.xml中是这样配置的
- <filter>
- <filter-name>encryptFilter</filter-name>
- <filter-class>com.test.filter.EncryptFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>encryptFilter</filter-name>
- <url-pattern>/SiServlet</url-pattern>
- </filter-mapping>
确保过滤器entyptFilter只拦截到SiServlet的请求即可。
运行AdcClient,可以看到下面的结果
这里的重点是MyRequestWrapper中重写的getInputStream()方法。大家可以看看API中关于HttpServletRequest的用法http://tomcat.apache.org/tomcat-5.5-doc/servletapi/index.html。
HttpServletRequestWrapper的使用的更多相关文章
- 使用HttpServletRequestWrapper在filter修改request参数
javax.servlet.ServletRequest中的 Map<String, String[]> parameterMap = request.getParameterMap(); ...
- 关于 preHandle 重写和添加参数问题,重写HttpServletRequestWrapper和Filter
由于 preHandle 中HttpServletRequest 只有setAttribute而没有setParameter 也没有 add 方法 所以是没办法直接添加参数的.从网上查了很多资料,基本 ...
- HttpServletRequestWrapper使用技巧(自定义session和缓存InputStream)
一.前言 javax.servlet.http.HttpServletRequestWrapper 是一个开发者可以继承的类,我们可以重写相应的方法来实现session的自定义以及缓存InputStr ...
- 【转】HttpServletRequestWrapper 实现xss注入
这里说下最近项目中我们的解决方案,主要用到commons-lang3-3.1.jar这个包的org.apache.commons.lang3.StringEscapeUtils.escapeHtml4 ...
- HttpServletRequestWrapper 是HttpServletRequest的包装类 ·关系相当于 int 与integer的关系
HttpServletRequestWrapper 是HttpServletRequest的包装类 ·关系相当于 int 与integer的关系
- 使用HttpServletRequestWrapper修改请求参数 和 使用HttpServletResponseWrapper截获响应数据
Servlet规范中的Filter引入了一个功能强大的拦截模式.Filter能在request到达servlet的服务方法之前拦截request对象,而在服务方法转移控制后又能拦截response对象 ...
- HttpServletRequestWrapper模拟实现分布式Session
HttpSession的内容都放在一个单独的Map中,模拟远程分布式Session. 1.使用HttpServletRequestWrapper创建自定义Request2.使用动态代理包装自定义Req ...
- 利用Filter和HttpServletRequestWrapper实现请求体中token校验
先说一下项目的背景,系统传参为json格式,token为其中一个必传参数,此时如果在过滤器中直接读取request,则后续controller中通过RequestBody注解封装请求参数是会报stre ...
- HttpServletRequestWrapper 类&过滤指定文字
HttpServletWrapper 和 HttpServletResponseWrapper 1). Servlet API 中提供了一个 HttpServletRequestWrapper 类来包 ...
随机推荐
- [大牛翻译系列]Hadoop(8)MapReduce 性能调优:性能测量(Measuring)
6.1 测量MapReduce和环境的性能指标 性能调优的基础系统的性能指标和实验数据.依据这些指标和数据,才能找到系统的性能瓶颈.性能指标和实验数据要通过一系列的工具和过程才能得到. 这部分里,将介 ...
- Nginx的平滑重启和平滑升级
一,Nginx的平滑重启如果改变了Nginx的配置文件(nginx.conf),想重启Nginx,可以发送系统信号给Nginx主进程的方式来进行.在重启之前,要确认Nginx配置文件的语法是正确的. ...
- Extjs combox的详解
Extjs combox的详解 写了哈extjs当中的combox,第一次写,照着网上的例子抄.在上次的例子中,是实现了,可是有一个重大的错误.也就是自己根本没有理解combox从远程服务器获取数据, ...
- SQL Server 读取CSV中的数据
测试: Script: create table #Test ( Name ), Age int, T ) ) BULK INSERT #Test From 'I:\AAA.csv' with( fi ...
- 【netstream】探索数据传输对象1
什么是“从当前流中读取一个字符串.字符串有长度前缀,一次 7 位地被编码为整数.” 来探索一下: 写一段简单的程序: FileStream fs= new FileStream("d:\\q ...
- 与MySQL交互(felixge/node-mysql)
目录 简介和安装 测试MySQL 认识一下Connection Options MYSQL CURD 插入 更新 查询 删除 Nodejs 调用带out参数的存储过程,并得到out参数返回值 结束数据 ...
- MVC学习系列——Model验证扩展
MVC中,实现了前端后端的验证. 前端验证.步骤: web.config这两个得开启: <add key="ClientValidationEnabled" value=&q ...
- ThinkPHP学习笔记 实例化模型的四种方法
创建Action类 [php] <?php class NewObjectAction extends Action{ public function index(){ ...
- .NET操作JSON
http://www.cnblogs.com/txw1958/archive/2012/08/01/csharp-json.html JSON文件读入到内存中就是字符串,.NET操作JSON就是生成与 ...
- SOLID architecture principles using simple C# examples
转:http://www.codeproject.com/Articles/703634/SOLID-architecture-principles-using-simple-Csharp?msg=4 ...