2015-02-03 7 views
1

스프링 포틀릿 MVC에서 @ResourceMapping의 JSON 매개 변수를 어떻게 interprete 할 수 있는지 검색하고 있습니다. @RequestBody를 추가하면 다음 메시지가 나타납니다. @RequestBody는 지원되지 않습니다.Ajax 요청에서 JSON을 받아들이는 @ResourceMapping

보기 측 :

<portlet:resourceURL var="getTest" id="ajaxTest" ></portlet:resourceURL> 

    <p> 
     <button onClick="executeAjaxTest();">Klik mij!</button> 
     <button onClick="$('#ajaxResponse').html('');">Klik mij!</button> 
    </p> 
    <p> 
     <h3>Hieronder het antwoord:</h3> 
     <h4 id="ajaxResponse"></h4> 
    </p> 

    <script> 
     function executeAjaxTest() { 

      var jsonObj = { 
        user: "Korneel", 
        password: "testpassword", 
        type: { 
         testParam: "test", 
        } 
       } 

      console.debug(JSON.stringify(jsonObj)); 
      $.ajax({ 
       dataType: "json", 
       contentType:"application/json", 
       mimeType: 'application/json', 
       url:"<%=getTest%>", 
       data:JSON.stringify(jsonObj), 
       success : function(data) { 
        $("#ajaxResponse").html(data['testString']); 
       } 
      }); 

     } 
    </script> 

컨트롤러 측 :

내가 이것을 가지고

가 어떻게 내 자신의 모델에 자동으로 맵이 JSON 데이터를 봄 마법을 사용할 수 있습니다

@ResourceMapping(value="ajaxTest") 
    @ResponseBody 
    public void ajaxTestMethod(ResourceRequest request, ResourceResponse response) throws IOException, ParseException { 

     LOGGER.debug("ajax method"); 

     JSONObject json = JSONFactoryUtil.createJSONObject(); 
     json.put("testString", "Ik ben succesvol verstuurd geweest!"); 
     response.getWriter().write(json.toString()); 
} 
? 참고 : Spring MVC가 아닌 Spring 포틀릿 MVC입니다.

답변

3

는이처럼 JSON 개체를 구축 할 필요가

public class JsonObjCommand { 

private String user; 
private String password; 
private TypeJson type; 

public String getUser() { 
    return user; 
} 
public void setUser(String user) { 
    this.user = user; 
} 
public String getPassword() { 
    return password; 
} 
public void setPassword(String password) { 
    this.password = password; 
} 
public TypeJson getType() { 
    return type; 
} 
public void setType(TypeJson type) { 
    this.type = type; 
} 

} 

public class TypeJson { 

private String testParam; 

public String getTestParam() { 
    return testParam; 
} 

public void setTestParam(String testParam) { 
    this.testParam = testParam; 
} 

} 
0

설명서에 따르면 @RequestBody는 포틀릿 환경 (@ResponseBody와 동일)에서만 지원됩니다. 그래서 당신은 그 기능을 사용할 수없는 것 같습니다.

4

@ResponseBody annotation은 Spring MVC 포틀릿 프레임 워크에서 지원되지 않지만 @ResponseBody 처리는 구현할 수 있습니다.

사용자 지정보기 유형 및 모델 및보기 확인 프로그램을 구현하여이 작업을 수행합니다.

  1. 사용자 정의 모델 및 뷰 해석기 (ModelAndViewResolver)를 구현하려면 JsonModelAndViewResolver를 가정 해 봅시다.
  2. resolveModelAndView 메소드에서 컨트롤러 메소드에 @ResponseBody 주석이 있는지 (또는 JSON 출력을 식별하기위한 특정 조건 - 예 : 주석 + 필수 지원되는 MIME 유형)이 있는지 확인합니다.
  3. 그렇다면 사용자 정의 View 구현을 반환하십시오. SingleObjectJson 뷰 (AbstractView 확장)를 가정 해 봅시다.
  4. 직렬화 될 오브젝트를 뷰 인스턴스에 전달하십시오.
  5. 뷰는 객체를 JSON 형식으로 serialize하고 response에 기록합니다 (renderMergedOutputModel 메소드의 Jackson, Gson 또는 다른 프레임 워크를 사용하여).
  6. 새 해결 프로그램을 AnnotationMethodHandlerAdapter.customModelAndViewResolvers로 등록하십시오.

    @ModelAttribute(value = "jsonObj") 
    public JsonObjCommand obtenerJsonObjCommand() { 
        JsonObjCommand jsonObjCommand = new JsonObjCommand(); 
        return jsonObjCommand; 
    } 
    
    @ResourceMapping(value = "ajaxTest") 
    public void ajaxTestMethod(
         ResourceRequest request, 
         ResourceResponse response, 
         @ModelAttribute(value = "jsonObj") JsonObjCommand jsonObjCommand) 
         throws IOException, ParseException { 
        LOGGER.debug("USER: " + jsonObjCommand.getUser()); 
        LOGGER.debug("Password: " + jsonObjCommand.getPassword()); 
        LOGGER.debug("TestParam: " + jsonObjCommand.getType().getTestParam()); 
        LOGGER.debug("ajax method"); 
    
        JSONObject json = JSONFactoryUtil.createJSONObject(); 
        json.put("testString", "Ik ben succesvol verstuurd geweest!"); 
        response.getWriter().write(json.toString()); 
    } 
    

    당신의 콩을 잊지 마세요 : 당신이 @ModelAttribute 어노테이션을 사용한다

    var jsonObj = { 
           user: "Korneel", 
           password: "testpassword", 
           "type.testParam" : "test" 
          }; 
    
    $.ajax({ 
          dataType: "json", 
          contentType:"application/json", 
          mimeType: 'application/json', 
          url:"<%=getTest%>", 
          data:jsonObj, 
          success : function(data) { 
           $("#ajaxResponse").html(data['testString']); 
          } 
         }); 
    

    당신의 컨트롤러에서 :