`

javax.servlet.http.HttpServletResponse 得到 status_code

阅读更多
javax.servlet.http.HttpServletResponse 得到 status_code

一) 在log4j的日志中需要输出应答的status_code,不用还真不知道,HttpServletResponse接口并没有getStatus()方法。

二) 自己动手,用一个Reponse的装饰器,解决这个问题。这算是一个过滤器和装饰器设计模式的典型应用吧
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ying.car.shiro.ShiroUtils;

/**
 * 记录http信息的Filter
 * 
 *
 */
public class HttpInfoLoggingFilter implements Filter{

	private static final Logger LOGGER = LoggerFactory.getLogger(HttpInfoLoggingFilter.class);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// 无配置
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		StatusExposingServletResponse response = new StatusExposingServletResponse((HttpServletResponse) res);
		
		Integer currentUserId 	 = getCurrentUserId();
		String ip     			 = request.getRemoteAddr();
		String method 			 = request.getMethod();
		String url    			 = request.getRequestURI();
		String characterEncoding = request.getCharacterEncoding();
		String referer			 = request.getHeader("Referer");
		chain.doFilter(request, response);
		int status  =  response.getStatus();
		LOGGER.info("{}, {}, {}, {}, {}, {}, {}", currentUserId, ip, method, characterEncoding, referer, url, status);
	}

	@Override
	public void destroy() {
		// 无动作
	}

	private Integer getCurrentUserId() {
		Integer currentUserId = 0;
		try { currentUserId = ShiroUtils.getPrincipalDomainId(); } catch (Exception e) {} // apache-shiro框架
		return currentUserId;
	}

	//~ ============================================================================================================================
	public static class StatusExposingServletResponse extends HttpServletResponseWrapper implements HttpServletResponse {

		private int status = 200;

		public StatusExposingServletResponse(HttpServletResponse response) {
			super(response);
		}

		@Override
		public void setStatus(int sc) {
			this.status = sc;
			super.setStatus(sc);
		}

		public int getStatus() {
			return status;
		}
	}
}


web.xml
<!-- apache-shiro 核心拦截器 -->
<filter>
	<filter-name>shiroFilter</filter-name>
	<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
	<filter-name>shiroFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- http信息日志过滤器 -->
<filter>
	<filter-name>httpInfoLoggingFilter</filter-name>
	<filter-class>ying.car.filter.HttpInfoLoggingFilter</filter-class>
</filter>
<filter-mapping>
	<filter-name>httpInfoLoggingFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>
分享到:
评论
1 楼 yubao2008 2018-08-02  
[size=x-small]为什么我也这样试了, 就是没有生效呢,返回前端是500,但过滤器中打印的始终是200[/size]

相关推荐

    servlet2.4doc

    addCookie(Cookie) - Method in interface javax.servlet.http.HttpServletResponse Adds the specified cookie to the response. addDateHeader(String, long) - Method in class javax.servlet....

    Servlet和Android网络交互1

    import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class FirstServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, ...

    J2ME手机登陆程序

    import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException...

    使用jQuery ajaxFileUpload+servlet实现文件上传

    import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.Enumeration; @WebServlet("/fileUploadServlet") public class FileUploadServlet extends ...

    HttpServletResponse对象、HttpServletResponse应用、请求重定向

    `HttpServletResponse`是Servlet API中的一个接口,位于`javax.servlet.http`包下。它提供了向客户端发送HTTP响应的方法,是服务器端与浏览器进行通信的桥梁。主要功能包括设置响应状态码、添加响应头、以及写入响应...

    ssm_异常处理

    response.setStatus(ex.getErrorCode()); request.setAttribute("errorMsg", ex.getMessage()); // 显示自定义错误页面 return new ModelAndView("error/business"); } } ``` 注册这个自定义异常处理器到...

    JSP里web.xml实现错误处理页面的制作404,和500

    &lt;%=request.getAttribute("javax.servlet.forward.servlet_path")%&gt; 以下为堆栈跟踪信息: &lt;% exception.printStackTrace(); %&gt; ``` `error.jsp` 页面提供了更丰富的错误信息,包括异常类名、异常消息以及堆栈跟踪...

    AJAX实例

    import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class AjaxServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse ...

    java使用uploadify批量上传文件

    import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; public class FileUploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request,...

    Spring boot自定义http反馈状态码详解

    HttpServletResponse 是 javax.servlet下的一个接口,通过使用 HttpServletResponse,我们可以自定义 HTTP 状态码。例如: ```java @RequestMapping(value = "/user", method = RequestMethod.GET) public void ...

    JSP的内置对象详细讲解

    - `setStatus(int code)`:设置HTTP状态码。 - `getOutputStream()`:获取用于写入响应内容的输出流。 6.5 `session` 对象 `session`对象用于管理用户会话,基于`HttpSession`: - `getAttribute(String name)`:...

    tomcat:java简单实现tomcat

    例如,`setStatus(int code)`用于设置HTTP状态码,`getOutputStream()`或`getWriter()`用于输出响应内容。 综上所述,这个项目涵盖了Java网络编程、多线程处理、Servlet技术以及HTTP协议的基础知识。通过实现这样一...

Global site tag (gtag.js) - Google Analytics