1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| package cn.idea360.junit.filter;
import cn.idea360.junit.wrapper.ContentCachingRequestWrapper; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils;
import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map;
@Slf4j public class LogFilter implements Filter{
private final ObjectMapper objectMapper = new ObjectMapper();
@Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { ContentCachingRequestWrapper request = new ContentCachingRequestWrapper((HttpServletRequest) servletRequest); HttpServletResponse response = (HttpServletResponse) servletResponse; String header = request.getHeader("blog"); String requestURL = request.getRequestURL().toString(); String contextPath = request.getContextPath(); String servletPath = request.getServletPath(); String requestURI = request.getRequestURI(); String method = request.getMethod(); String queryString = request.getQueryString(); Map<String, String[]> parameterMap = request.getParameterMap(); String body = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8); log.info(body); filterChain.doFilter(request, response); sendUnauthorizedMessage(response, "验签失败"); }
private void sendUnauthorizedMessage(HttpServletResponse response, String message) { response.setContentType("application/json;charset=UTF-8"); response.setCharacterEncoding(StandardCharsets.UTF_8.name()); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
try { PrintWriter out = response.getWriter(); Map<String,Object> map = new HashMap<>(); map.put("code", HttpServletResponse.SC_UNAUTHORIZED); map.put("msg", message); out.write(objectMapper.writeValueAsString(map)); out.flush(); out.close(); } catch (Exception e) { log.error("can't push signature err message", e); } } }
|