有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

当我使用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);

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

共 (1) 个答案

  1. # 1 楼答案

    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;
        }