记录HttpRequest参数和请求正文

编程入门 行业动态 更新时间:2024-10-27 10:18:39
本文介绍了记录HttpRequest参数和请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试为我的Web应用程序创建请求日志.我正在使用Spring 3. 0.

I am trying to create a request log for my web app. I am using Spring 3. 0.

我实现了扩展HandlerInterceptorAdapter的类,并使用preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)拦截了请求.

I implemented a class extending HandlerInterceptorAdapter and used the preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) to intercept the request.

在该方法中,我希望能够记录请求正文(我的参数是直接写入请求正文的XML对象),为此,我使用request.getReader();

In the method i want to be able to log the request body (my parameters are objects in XML that are written directly to the request body), and for that i use request.getReader();

问题是-稍后,当spring控制器尝试读取请求时,我会得到一个IllegalStateException.

The problem is - later on I will get an IllegalStateException when the spring controller tries to read the request.

有没有办法做我打算做的事?

Is there a way to do what I intend?

推荐答案

您可以使用过滤器执行此操作.请求参数易于处理. 但是,处理请求主体将更加困难 并且需要包装servlet请求,请参见: HttpServletRequest .

You can do this with a filter. The request parameters are easy to handle. However dealing with the request body will be much more difficult and will require wrapping the servlet request see: HttpServletRequest.

您将需要查看传入的请求的大小,并确定是将请求正文存储为tmp文件还是字符串.

You will need to look how big the incoming request is and decide whether you want to store the request body as a tmp file or string.

您将需要使用用于记录日志的文件或保存的字符串覆盖ServetRequest.getInputStream().

You will need to override ServetRequest.getInputStream() with your file or saved string that used for logging.

如果请求主体很大,我建议将输入流放入缓冲的输入流中,然后读取主体的开头.

If the request body is huge I recommend putting the input stream into a buffered input stream and then reading the start of the body.

public class LogRequest extends HttpServletRequestWrapper { public LogRequest(HttpServletRequest request) { super(request); } @Override public ServletInputStream getInputStream() throws IOException { //read from tmp file or string. } @Override public BufferedReader getReader() throws IOException { //read from tmp file or string } }

更多推荐

记录HttpRequest参数和请求正文

本文发布于:2023-10-29 09:33:11,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539348.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   正文   HttpRequest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!