原文地址:http://liwx2000.iteye.com/blog/1542431

原文作者:liwx2000

为了提高项目安全性,拦截非法访问,要给项目增加了一个过滤器,拦截所有的请求,校验是否有不安全因素。

这个过程就遇到了一个问题:ServletRequest的getReader()和getInputStream()两个方法只能被调用一次,而且不能两个都调用。那么如果Filter中调用了一次,在Controller里面就不能再调用了。没办法,就去网上搜罗了一通,发现了一个超赞的解决方法。为了记录备案,无耻的转了过来,原文地址在上,内容在下。

1. 查看了下ServletRequest的说明,如下:

/**
* Retrieves the body of the request as binary data using
* a {@link ServletInputStream}. Either this method or
* {@link #getReader} may be called to read the body, not both.
*
* @return a {@link ServletInputStream} object containing
* the body of the request
*
* @exception IllegalStateException if the {@link #getReader} method
* has already been called for this request
*
* @exception IOException if an input or output exception occurred
*
*/ public ServletInputStream getInputStream() throws IOException; /**
* Retrieves the body of the request as character data using
* a <code>BufferedReader</code>. The reader translates the character
* data according to the character encoding used on the body.
* Either this method or {@link #getInputStream} may be called to read the
* body, not both.
*
*
* @return a <code>BufferedReader</code>
* containing the body of the request
*
* @exception UnsupportedEncodingException if the character set encoding
* used is not supported and the
* text cannot be decoded
*
* @exception IllegalStateException if {@link #getInputStream} method
* has been called on this request
*
* @exception IOException if an input or output exception occurred
*
* @see #getInputStream
*
*/ public BufferedReader getReader() throws IOException;

两个方法都注明方法只能被调用一次,由于RequestBody是流的形式读取,那么流读了一次就没有了,所以只能被调用一次。既然是因为流只能读一次的原因,那么只要将流的内容保存下来,就可以实现反复读取了。byte数组允许被多次读取,而不会丢失内容。下面使用byte数组将流的内容保存下来。

2.  工具方法:

先将RequestBody保存为一个byte数组,然后通过Servlet自带的HttpServletRequestWrapper类覆盖getReader()和getInputStream()方法,使流从保存的byte数组读取。然后再Filter中将ServletRequest替换为ServletRequestWrapper。

代码如下:

BodyReaderHttpServletRequestWrapper类包装ServletRequest,将流保存为byte[],然后将getReader()和getInputStream()方法的流的读取指向byte[]。

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader; import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper; import jodd.JoddDefault;
import jodd.io.StreamUtil; public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper { private final byte[] body; public BodyReaderHttpServletRequestWrapper(HttpServletRequest request)
throws IOException {
super(request);
// body = StreamUtil.readBytes(request.getReader(), JoddDefault.encoding);
     // 因为http协议默认传输的编码就是iso-8859-1,如果使用utf-8转码乱码的话,可以尝试使用iso-8859-1
     body = StreamUtil.readBytes(request.getReader(), "iso-8859-1");
} @Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(getInputStream()));
} @Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream bais = new ByteArrayInputStream(body);
return new ServletInputStream() { @Override
public int read() throws IOException {
return bais.read();
}
};
} }

3. 在Filter中的使用:

在Filter中将ServletRequest替换为ServletRequestWrapper

public class HttpServletRequestReplacedFilter implements Filter {  

    @Override
public void init(FilterConfig filterConfig) throws ServletException {
//Do nothing
} @Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
ServletRequest requestWrapper = null;
if(request instanceof HttpServletRequest) {
requestWrapper = new BodyReaderHttpServletRequestWrapper((HttpServletRequest) request);
}
if(null == requestWrapper) {
chain.doFilter(request, response);
} else {
chain.doFilter(requestWrapper, response);
} } @Override
public void destroy() {
//Do nothing
} }

ServletRequest中getReader()和getInputStream()只能调用一次的解决办法(转)的更多相关文章

  1. ServletRequest中getReader()和getInputStream()只能调用一次的解决办法

    转载:http://blog.sina.com.cn/s/blog_870cd7b90101fg58.html 最近使用spring mvc做项目,数据格式是json,有一个功能是实现记录请求的参数, ...

  2. 关于springmvc时request的getReader()和getInputStream()只能调用一次的解决办法

    最近准备在原有的SSM项目的基础上添加完善的日志分析,由于是APP的后台系统,之前在规划APP的时候,并没有在APP上做埋点的处理,而如果想要进行埋点处理的话,对于未能新升级的APP用户来说,就是去了 ...

  3. 拦截器中,request中getReader()和getInputStream()只能调用一次,构建可重复读取inputStream的request.

    由于 request中getReader()和getInputStream()只能调用一次 在项目中,可能会出现需要针对接口参数进行校验等问题. 因此,针对这问题,给出一下解决方案 实现方法:先将Re ...

  4. es6 Object.assign ECMAScript 6 笔记(六) ECMAScript 6 笔记(一) react入门——慕课网笔记 jquery中动态新增的元素节点无法触发事件解决办法 响应式图像 弹窗细节 微信浏览器——返回操作 Float 的那些事 Flex布局 HTML5 data-* 自定义属性 参数传递的四种形式

    es6 Object.assign   目录 一.基本用法 二.用途 1. 为对象添加属性 2. 为对象添加方法 3. 克隆对象 4. 合并多个对象 5. 为属性指定默认值 三.浏览器支持 ES6 O ...

  5. c++调用动态库失败解决办法

    c++调用动态库失败解决办法 之前写好的程序今天早上过来发现在服务器上出错了,于是就各种查问题,整整一个早上外加下午两个小时都在查这个问题,最终被我找到了问题: 在程序中我发现LoadLibrary( ...

  6. Android中View类OnClickListener和DialogInterface类OnClickListener冲突解决办法

    Android中View类OnClickListener和DialogInterface类OnClickListener冲突解决办法 如下面所示,同时导入这两个,会提示其中一个与另一个产生冲突. 1i ...

  7. .NET在IE9中页面间URL传递中文变成乱码的解决办法

     在.Net的项目中,鼠标点击查询按钮,转到查询页面,但URL中包含中文时,传到服务器端后,中文变成了乱码(只有IE9出现该问题).       尝试使用Server.UrlEncode()进行编码, ...

  8. Visual studio 2017中 Javascript对于Xrm对象模型没有智能提示的解决办法

    Visual studio 2017中 Javascript对于Xrm对象模型没有智能提示的解决办法 先上个图.语法提示支持到 Microsoft Dynamics xRM API 8.2 也就是cr ...

  9. electron-vue中使用iview 报错this. is readonly的解决办法

    title: electron-vue中使用iview 报错this. is readonly的解决办法 toc: false date: 2019-02-12 19:33:28 categories ...

随机推荐

  1. 导航条上UIBarButtonItem的更改方法(使用initWithCustomView:btn)

    UINavigationController *nav = [[[UINavigationController alloc] initWithRootViewController:self.newMe ...

  2. 数据库VIEW(视图)

    视图是基于 SQL 语句的结果集的可视化的表. 视图包括行和列,就像一个真实的表.视图中的字段就是来自一个或多个数据库中的真实的表中的字段. 我们能够向视图加入 SQL 函数.WHERE 以及 JOI ...

  3. [Git] Automatically running tests before commits with ghooks

    Wouldn't it be nice if everyone ran the tests before committing code? With ghooks, you can automatic ...

  4. Java基础知识强化53:经典排序之选择排序(SelectionSort)

    1.选择排序的原理图: 2. 选择排序代码实现: package cn.itcast_02; /* * 数组排序之选择排序: * 从0索引开始,依次和后面元素比较,小的往前放,第一次完毕,最小值出现在 ...

  5. C#SaveFileDialog的使用

    SaveFileDialog sfd = new SaveFileDialog(); //默认打开的路径 sfd.InitialDirectory = "C:\\Users\\Adminis ...

  6. 导出数据库中所有数据到Excle中

    Workbook wb = new HSSFWorkbook();//创建工作簿 Connection conn = DataSourceUtils.getDataSource().getConnec ...

  7. Sicily 1194. Message Flood

    题目地址:1194. Message Flood 思路: 不区分大小写,先全部转化为小写,用stl提供的函数做会很方便. 具体代码如下: #include <iostream> #incl ...

  8. C++程序设计教程学习(1)-第一部分 编程基础

    第一章 概述 C++到底难不难学?没有学不会的事情 1.1 程序设计语言 语言 编程语言 人和计算机交流的工具,群体扩大,人人间交流过程描述与信息表达的工具 机器语言,汇编语言,高级语言 1.2 C+ ...

  9. iOS中的UIWindow

    UIWindow的作用 UIWindow主要有两个作用: 1 作为UIView视图的最顶层容器,包含所有要显示的UIView 2 传递触摸,非触摸,键盘事件,其中传递非触摸和键盘事件时,UIWindo ...

  10. uva 10994 - Simple Addition

    //组合数学 //计算sum{i从右往左数的第一个非0数字,p<=i<=q}. #include <cstdio> typedef long long ll; ll sum(l ...