2011-03-03 31 views
9

我正在使用Spring的@ExceptionHandler注释来捕获我的控制器中的异常。从spring异常处理程序中读取httprequest内容

一些请求将POST数据作为纯XML字符串写入请求正文,我想读取该数据以便记录异常。 问题是,当我在异常处理程序中请求inputstream并尝试从它读取时,流返回-1(空)。

异常处理程序的签名是:

@ExceptionHandler(Throwable.class) 
public ModelAndView exception(HttpServletRequest request, HttpServletResponse response, HttpSession session, Throwable arff) 

有什么想法?有没有办法访问请求体?

我的控制器:

@Controller 
@RequestMapping("/user/**") 
public class UserController { 

    static final Logger LOG = LoggerFactory.getLogger(UserController.class); 

    @Autowired 
    IUserService userService; 


    @RequestMapping("/user") 
    public ModelAndView getCurrent() { 
     return new ModelAndView("user","response", userService.getCurrent()); 
    } 

    @RequestMapping("/user/firstLogin") 
    public ModelAndView firstLogin(HttpSession session) { 
     userService.logUser(session.getId()); 
     userService.setOriginalAuthority(); 
     return new ModelAndView("user","response", userService.getCurrent()); 
    } 


    @RequestMapping("/user/login/failure") 
    public ModelAndView loginFailed() { 
     LOG.debug("loginFailed()"); 
     Status status = new Status(-1,"Bad login"); 
     return new ModelAndView("/user/login/failure", "response",status); 
    } 

    @RequestMapping("/user/login/unauthorized") 
    public ModelAndView unauthorized() { 
     LOG.debug("unauthorized()"); 
     Status status = new Status(-1,"Unauthorized.Please login first."); 
     return new ModelAndView("/user/login/unauthorized","response",status); 
    } 

    @RequestMapping("/user/logout/success") 
    public ModelAndView logoutSuccess() { 
     LOG.debug("logout()"); 
     Status status = new Status(0,"Successful logout"); 
     return new ModelAndView("/user/logout/success", "response",status); 

    } 

    @RequestMapping(value = "/user/{id}", method = RequestMethod.POST) 
    public ModelAndView create(@RequestBody UserDTO userDTO, @PathVariable("id") Long id) { 
     return new ModelAndView("user", "response", userService.create(userDTO, id)); 
    } 

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET) 
    public ModelAndView getUserById(@PathVariable("id") Long id) { 
     return new ModelAndView("user", "response", userService.getUserById(id)); 
    } 

    @RequestMapping(value = "/user/update/{id}", method = RequestMethod.POST) 
    public ModelAndView update(@RequestBody UserDTO userDTO, @PathVariable("id") Long id) { 
     return new ModelAndView("user", "response", userService.update(userDTO, id)); 
    } 

    @RequestMapping(value = "/user/all", method = RequestMethod.GET) 
    public ModelAndView list() { 
     return new ModelAndView("user", "response", userService.list()); 
    } 

    @RequestMapping(value = "/user/allowedAccounts", method = RequestMethod.GET) 
    public ModelAndView getAllowedAccounts() { 
     return new ModelAndView("user", "response", userService.getAllowedAccounts()); 
    } 

    @RequestMapping(value = "/user/changeAccount/{accountId}", method = RequestMethod.GET) 
    public ModelAndView changeAccount(@PathVariable("accountId") Long accountId) { 
     Status st = userService.changeAccount(accountId); 
     if (st.code != -1) { 
      return getCurrent(); 
     } 
     else { 
      return new ModelAndView("user", "response", st); 
     } 
    } 
    /* 
    @RequestMapping(value = "/user/logout", method = RequestMethod.GET) 
    public void perLogout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
     userService.setOriginalAuthority(); 
     response.sendRedirect("/marketplace/user/logout/spring"); 
    } 
    */ 

    @ExceptionHandler(Throwable.class) 
public ModelAndView exception(HttpServletRequest request, HttpServletResponse response, HttpSession session, Throwable arff) { 
    Status st = new Status(); 
    try { 
     Writer writer = new StringWriter(); 
     byte[] buffer = new byte[1024]; 

     //Reader reader2 = new BufferedReader(new InputStreamReader(request.getInputStream())); 
     InputStream reader = request.getInputStream(); 
     int n; 
     while ((n = reader.read(buffer)) != -1) { 
      writer.toString(); 

     } 
     String retval = writer.toString(); 
     retval = ""; 
     } catch (IOException e) { 

      e.printStackTrace(); 
     } 

     return new ModelAndView("profile", "response", st); 
    } 
} 

谢谢

回答

9

我试过你的代码,我发现在异常处理一些错误,当您从InputStream阅读:

Writer writer = new StringWriter(); 
byte[] buffer = new byte[1024]; 

//Reader reader2 = new BufferedReader(new InputStreamReader(request.getInputStream())); 
InputStream reader = request.getInputStream(); 
int n; 
while ((n = reader.read(buffer)) != -1) { 
    writer.toString(); 

} 
String retval = writer.toString(); 
retval = ""; 

我已将此代码替换为此代码:

BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); 
String line = ""; 
StringBuilder stringBuilder = new StringBuilder(); 
while ((line=reader.readLine()) != null) { 
    stringBuilder.append(line).append("\n"); 
} 

String retval = stringBuilder.toString(); 

然后我可以从异常处理程序中的InputStream中读取它的工作原理! 如果您仍然无法从InputStream中读取,我建议您检查POST xml数据到请求主体的方式。 您应该考虑到每个请求只能使用一次Inputstream,所以我建议您检查是否没有任何其他电话拨打getInputStream()。如果您必须多次调用它,则应该编写自定义HttpServletRequestWrapper以制作请求主体的副本,以便您多读几次。

UPDATE
您的意见帮助我重现了这个问题。您使用注释@RequestBody,所以确实不要调用getInputStream(),但Spring会调用它来检索请求的正文。看看org.springframework.web.bind.annotation.support.HandlerMethodInvoker这个班级:如果您使用@RequestBody这个班级调用resolveRequestBody方法,依此类推......最后,您不能再从ServletRequest中读取InputStream了。如果您仍然想在自己的方法中同时使用@RequestBodygetInputStream(),则必须将请求包装为自定义HttpServletRequestWrapper以制作请求主体的副本,以便您可以手动读取更多次。 这是我的包装:

public class CustomHttpServletRequestWrapper extends HttpServletRequestWrapper { 

    private static final Logger logger = Logger.getLogger(CustomHttpServletRequestWrapper.class); 
    private final String body; 

    public CustomHttpServletRequestWrapper(HttpServletRequest request) { 
     super(request); 

     StringBuilder stringBuilder = new StringBuilder(); 
     BufferedReader bufferedReader = null; 

     try { 
      InputStream inputStream = request.getInputStream(); 
      if (inputStream != null) { 
       bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); 
       String line = ""; 
       while ((line = bufferedReader.readLine()) != null) { 
        stringBuilder.append(line).append("\n"); 
       } 
      } else { 
       stringBuilder.append(""); 
      } 
     } catch (IOException ex) { 
      logger.error("Error reading the request body..."); 
     } finally { 
      if (bufferedReader != null) { 
       try { 
        bufferedReader.close(); 
       } catch (IOException ex) { 
        logger.error("Error closing bufferedReader..."); 
       } 
      } 
     } 

     body = stringBuilder.toString(); 
    } 

    @Override 
    public ServletInputStream getInputStream() throws IOException { 
     final StringReader reader = new StringReader(body); 
     ServletInputStream inputStream = new ServletInputStream() { 
      public int read() throws IOException { 
       return reader.read(); 
      } 
     }; 
     return inputStream; 
    } 
} 

那么你应该写一个简单的Filter包装要求:

public class MyFilter implements Filter { 

    public void init(FilterConfig fc) throws ServletException { 

    } 

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
     chain.doFilter(new CustomHttpServletRequestWrapper((HttpServletRequest)request), response); 

    } 

    public void destroy() { 

    } 

} 

最后,你必须配置你的过滤器在你的web.xml:

<filter>  
    <filter-name>MyFilter</filter-name> 
    <filter-class>test.MyFilter</filter-class> 
</filter> 
<filter-mapping> 
    <filter-name>MyFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 

您只能为真正需要它的控制器启动过滤器,因此您应该根据需要更改url模式。

如果您仅需要一个控制器中的此功能,那么当您通过@RequestBody注释接收到请求时,您也可以在该控制器中创建请求主体的副本。

+0

感谢您的回复,我仍然无法阅读请求正文。没有抛出异常,只是读者返回null意味着它是空的。也许我在春天错过了关于异常处理程序的事情。如何在哪里阅读请求? – 2011-03-07 09:06:57

+0

我刚刚将您的代码(通过更正)复制到新项目中。我通过enctype =“multipart/form-data”和输入类型=“file”的静态html表格来调用控制器来上传文件。我添加了一个RequestMapping注释和相应的方法,只抛出一个RuntimeException。在异常处理程序方法中,我可以记录通过表单上传的整个文件。当你进入控制器或者已经通过对getInputStream()的另一个调用使用时,似乎输入流是空的。什么版本的Spring? – javanna 2011-03-07 09:33:58

+0

@Noam Nevo有什么消息吗? :-) – javanna 2011-03-08 17:20:44

5

我有同样的问题,并用HttpServletRequestWrapper解决它,如上所述,它很好。但后来,我发现了另一个扩展HttpMessageConverter的解决方案,在我的案例中是MappingJackson2HttpMessageConverter

public class CustomJsonHttpMessageConverter extends MappingJackson2HttpMessageConverter{ 

    public static final String REQUEST_BODY_ATTRIBUTE_NAME = "key.to.requestBody"; 


    @Override 
    public Object read(Type type, Class<?> contextClass, final HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { 

     final ByteArrayOutputStream writerStream = new ByteArrayOutputStream(); 

     HttpInputMessage message = new HttpInputMessage() { 
      @Override 
      public HttpHeaders getHeaders() { 
       return inputMessage.getHeaders(); 
      } 
      @Override 
      public InputStream getBody() throws IOException { 
       return new TeeInputStream(inputMessage.getBody(), writerStream); 
      } 
     }; 
        RequestContextHolder.getRequestAttributes().setAttribute(REQUEST_BODY_ATTRIBUTE_NAME, writerStream, RequestAttributes.SCOPE_REQUEST); 

     return super.read(type, contextClass, message); 
    } 

} 

com.sun.xml.internal.messaging.saaj.util.TeeInputStream被使用。

Spring MVC中配置

<mvc:annotation-driven > 
    <mvc:message-converters> 
     <bean class="com.company.remote.rest.util.CustomJsonHttpMessageConverter" /> 
    </mvc:message-converters> 
</mvc:annotation-driven> 

在@ExceptionHandler方法

@ExceptionHandler(Exception.class) 
public ResponseEntity<RestError> handleException(Exception e, HttpServletRequest httpRequest) { 

    RestError error = new RestError(); 
    error.setErrorCode(ErrorCodes.UNKNOWN_ERROR.getErrorCode()); 
    error.setDescription(ErrorCodes.UNKNOWN_ERROR.getDescription()); 
    error.setDescription(e.getMessage()); 


    logRestException(httpRequest, e); 

    ResponseEntity<RestError> responseEntity = new ResponseEntity<RestError>(error,HttpStatus.INTERNAL_SERVER_ERROR); 
    return responseEntity; 
} 

private void logRestException(HttpServletRequest request, Exception ex) { 
    StringWriter sb = new StringWriter(); 
    sb.append("Rest Error \n"); 
    sb.append("\nRequest Path"); 
    sb.append("\n----------------------------------------------------------------\n"); 
    sb.append(request.getRequestURL()); 
    sb.append("\n----------------------------------------------------------------\n"); 
Object requestBody = request.getAttribute(CustomJsonHttpMessageConverter.REQUEST_BODY_ATTRIBUTE_NAME); 

    if(requestBody != null) { 
     sb.append("\nRequest Body\n"); 
     sb.append("----------------------------------------------------------------\n"); 
     sb.append(requestBody.toString()); 

     sb.append("\n----------------------------------------------------------------\n"); 
    } 

    LOG.error(sb.toString()); 
} 

我希望它能帮助:)

+0

它......) – masadwin 2017-01-05 20:38:13

+0

TeeInputStream刚刚为XML工作? – Frank 2017-01-06 07:03:14

2

最近我遇到这个问题,并解决它略有不同。使用弹簧启动1.3.5.RELEASE

该过滤器是使用Spring类ContentCachingRequestWrapper实现的。这个包装器有一个方法getContentAsByteArray()可以多次调用。

import org.springframework.web.util.ContentCachingRequestWrapper; 
public class RequestBodyCachingFilter implements Filter { 

    public void init(FilterConfig fc) throws ServletException { 
    } 

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { 
     chain.doFilter(new ContentCachingRequestWrapper((HttpServletRequest)request), response); 
    } 

    public void destroy() { 
    } 
} 

添加过滤器链

@Bean 
public RequestBodyCachingFilter requestBodyCachingFilter() { 
    log.debug("Registering Request Body Caching filter"); 
    return new RequestBodyCachingFilter(); 
} 

在异常处理程序。

@ControllerAdvice(annotations = RestController.class) 
public class GlobalExceptionHandlingControllerAdvice { 
    private ContentCachingRequestWrapper getUnderlyingCachingRequest(ServletRequest request) { 
     if (ContentCachingRequestWrapper.class.isAssignableFrom(request.getClass())) { 
      return (ContentCachingRequestWrapper) request; 
     } 
     if (request instanceof ServletRequestWrapper) { 
      return getUnderlyingCachingRequest(((ServletRequestWrapper)request).getRequest()); 
     } 
     return null; 
    } 

    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) 
    @ExceptionHandler(Throwable.class) 
    public @ResponseBody Map<String, String> conflict(Throwable exception, HttpServletRequest request) { 
     ContentCachingRequestWrapper underlyingCachingRequest = getUnderlyingCachingRequest(request); 
     String body = new String(underlyingCachingRequest.getContentAsByteArray(),Charsets.UTF_8); 
     .... 
    } 
} 
+0

到目前为止干净/最好的答案,谢谢! – 2017-07-02 08:07:00