从 HTTPServletResponse 获取正文和响应代码
我正在尝试为我们的客户端访问 API 时构建一个简单的日志系统。我们使用 Spring 连接控制器和处理程序。我正在研究 Spring 的拦截器功能来编写 postHandle() 方法。不幸的是,与我在这里看到的所有代码示例不同,HttpServletResponse 没有 getStatus() 等方法。我猜想我们使用了错误版本的 Java 之类的。
我们需要来自 HttpServletResponse 对象的正文和响应代码:如何获取它们?
编辑:我们使用了一个过滤器:
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
RichHttpServletResponse richResponse=new RichHttpServletResponse((HttpServletResponse)response);
chain.doFilter(request, richResponse);
}
RichHttpServletResponse 将 servlet 响应作为其构造函数中的参数,并覆盖一些方法,例如 sendError() 并将值传递到实际的 servlet 响应。 webmvc-config XML 看起来像这样:
<bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy">
<sec:filter-chain-map path-type="ant">
<sec:filter-chain pattern="/**"
filters="requestObjectFilter" />
</sec:filter-chain-map>
</bean>
下面有一个 bean def。
I'm attempting build a simple logging system for when our client accesses out API. We're using Spring to wire up controllers and handlers. I'm looking at Spring's Interceptor functionality to write a postHandle() method. Unfortunately, unlike all the code samples I've seen here, HttpServletResponse does not have, for example, a getStatus() method. I'm supposing that we're using the wrong version of Java or something.
We need the body and response code from the HttpServletResponse object: how can I get those?
EDIT: We went with a filter:
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
RichHttpServletResponse richResponse=new RichHttpServletResponse((HttpServletResponse)response);
chain.doFilter(request, richResponse);
}
RichHttpServletResponse takes a servlet response as an argument in its constructor and overrides some of the methods, such as sendError() and passes the values through to the actual servlet response. The webmvc-config XML looks something like this:
<bean id="filterChainProxy" class="org.springframework.security.web.FilterChainProxy">
<sec:filter-chain-map path-type="ant">
<sec:filter-chain pattern="/**"
filters="requestObjectFilter" />
</sec:filter-chain-map>
</bean>
With a bean def below.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您也许可以调用 getOutputStream() 并阅读该内容,但我担心它会破坏流。有一些重置方法,但我自己不熟悉它们的作用。
You might be able to call getOutputStream() and read that, but I'd be concerned about it screwing up the stream. There are some reset methods, but I'm not familiar with what they do myself.