2015-06-03 112 views
1

我的代碼是這樣的:我們如何在Spring 3.0.2中設置請求內容類型?

@Controller 
    @RequestMapping(value = "/walley/login", method = RequestMethod.POST) 
    public void login(HttpServletRequest request, 
      HttpServletResponse response, 
      @RequestBody RequestDTO requestDTO) 
      throws IOException, ServiceException { 
       String userName = requestDTO.getUserName(); 
      String password = requestDTO.getPassword(); 
      System.out.println("userName " + userName +" :: password "+  password);} 

RequestDTO.java文件

public class RequestDTO { 
    public String userName; 
    public String password; 

    public String getUserName() { 
     return userName; 
    } 

    public void setUserName(String userName) { 
     this.userName = userName; 
    } 

    public String getPassword() { 
     return password; 
    } 

    public void setPassword(String password) { 
     this.password = password; 
    } 
    } 

打中立柱請求與跟隨郵遞員步驟。

  1. 打開郵差。
  2. 在URL欄中輸入URL http://localhost:8080/walley/login
  3. 點擊Headers按鈕,輸入Content-Type作爲頭和application/json的值。
  4. 從URL文本框旁邊的下拉列表中選擇POST。
  5. 從URL文本框下面的按鈕中選擇原始。
  6. 從下列下拉列表中選擇JSON。 在下面提供的文字區域,發表您的請求對象: { 「username」 的: 「測試」, 「密碼」: 「某人」 }

對此我得到錯誤:

org.springframework.web.HttpMediaTypeNotSupportedException:Content type 'application/json' not supported 

我檢查並發現在Spring 3.1.X或3.2.X中,我們可以在@RequestMapping中爲請求設置內容類型「消費者和生產者」,但它在3.0.2中不支持「消費者和生產者」。那麼我們如何使用@RequestBody註解在Spring 3.0.2版本中設置請求內容類型呢?

+0

你的方法是不會阻止任何使每個請求都前往那方法。確保你的類路徑中有一個JSON庫,例如Jackson。 –

+0

使用@RequestBody作爲第一個參數i.s.o.持續。 –

回答

2

我們沒有Spring版本3.0.2的「消費者和生產者」,所以我們需要在根pom.xml和dispatch-servlet.xml中添加一些額外的條目以使用@RequestBody註釋。

的pom.xml

<!-- jackson --> 
     <dependency> 
      <groupId>org.codehaus.jackson</groupId> 
      <artifactId>jackson-mapper-asl</artifactId> 
     <version>1.9.13</version> 
     </dependency> 
     <dependency> 
      <groupId>org.codehaus.jackson</groupId> 
      <artifactId>jackson-core-asl</artifactId> 
      <version>1.9.13</version> 
     </dependency> 

調度 - servlet.xml中

<bean id="jacksonMessageConverter" 
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> 
    <bean 
     class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
     <property name="messageConverters"> 
      <list> 
       <ref bean="jacksonMessageConverter" /> 
      </list> 
    </property> 
    </bean> 

和控制器應該喜歡

@Controller 
    @RequestMapping(value = "/walley/login", method = RequestMethod.POST) 
    public void login(@RequestBody RequestDTO requestDTO, 
      HttpServletRequest request, HttpServletResponse response) 
      throws IOException, ServiceException { 
       String userName = requestDTO.getUserName(); 
      String password = requestDTO.getPassword(); 
      System.out.println("userName " + userName +" :: password "+ password);} 
相關問題