2016-07-04 3 views
0

Spring을 사용하여 RESTFull 서비스를 빌드 할 때 모든 요청에 ​​대해 특수 처리를 수행해야합니다. 그래서 요격기를 소개합니다. 문제는 내 매개 변수가 자신이 정의한 Java 객체입니다. HttpServletRequest를 내 객체로 변환하려면 어떻게해야합니까? 요청 유형은 아마도 JSON 일 수도 있고 XML 일 수도 있습니다. HttpServletRequest를 HandlerInterceptorAdapter의 Java Object로 변환하는 방법

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(); 
+0

두 번 요청을 구문 분석 할 때 당신은 문제로 실행됩니다 작동하지 않는, 방법을 아래에 시도했다. 구체적으로 무엇을해야합니다. 왜 당신 자신의 물건을 소개 했습니까?이 물건의 목적은 무엇입니까? –

+0

Michael, 요청을 두 번 구문 분석하지 않습니다. 내가하고 싶은 일은 내 자신의 개체로 변환하고 속성 중 하나에 대해 강제로 값을 설정하는 것입니다. cslRequest.setName ("Derek"), 모든 reqeust에 대해 말하십시오. – DerekLiu

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

HandlerInterceptor를 구현 중이며 다음과 같이 preHandle을 쓸 수 없습니다. public boolean preHandle (@RequestBody String handler) throws IOException {} – DerekLiu

관련 문제