如何在HandlerInterceptorAdapter中将HttpServletRequest转换为Java对象

时间:2016-07-04 07:23:51

标签: java spring rest servlets

当我使用Spring构建RESTFull服务时,我需要为每个请求执行特殊处理。所以我介绍了拦截器。问题是我的参数是我自己定义的Java对象。如何将HttpServletRequest转换为我的对象?请求类型可能是JSON,也许是XML。

public class RequestInterceptors extends HandlerInterceptorAdapter {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    CslRequestmyReq = new CslRequest();
    // Convert request to myReq ????
    return true;
  }
}

我尝试了下面的方法,没有工作......

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,   false);
CslRequest re = mapper.readValue(request.getInputStream(), CslRequest.class);

OR

HttpEntity entity = new InputStreamEntity(request.getInputStream(),
            request.getContentLength());
ObjectInputStream ois = new ObjectInputStream(entity.getContent());
CslRequest o = (CslRequest) ois.readObject();

1 个答案:

答案 0 :(得分:0)

Try this : 
// @RequestBody allow to get the header into a string object or something else

public boolean preHandle(@RequestBody String handler) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        CslRequest re;
        try {
            re = mapper.readValue(handler, CslRequest.class);
        } catch (IOException e) {
            e.printStackTrace();
             Error parsing object
        }return true;
    }