gpt4 book ai didi

java - Spring 3.0.2 中如何设置请求内容类型?

转载 作者:行者123 更新时间:2023-11-30 03:24:19 25 4
gpt4 key购买 nike

我的代码是这样的:

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

在 postman 中按照以下步骤点击发布请求。

  1. 打开 postman 。
  2. 在地址栏中输入网址http://localhost:8080/walley/login .
  3. 点击 Headers 按钮并输入 Content-Type 作为 header,并在 value 中输入 application/json。
  4. 从 URL 文本框旁边的下拉列表中选择 POST。
  5. 从 URL 文本框下方的按钮中选择原始数据。
  6. 从以下下拉列表中选择 JSON。在下面的文本区域中,发布您的请求对象:{“用户名”:“测试”,“密码”:“某人”}

作为回应,我收到错误:

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

我检查了一下,发现在 Spring 3.1.X 或 3.2.X 中,我们可以在 @RequestMapping 中为请求设置内容类型“消费者和生产者”,并且它可以工作,但在 3.0.2 中,它们不支持“消费者和生产者”。那么在Spring 3.0.2版本中我们如何使用@RequestBody注解设置请求内容类型呢?

最佳答案

Spring 3.0.2 版本中没有“消费者和生产者”,因此我们需要在 root 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>

dispatch-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 应该会被喜欢

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

关于java - Spring 3.0.2 中如何设置请求内容类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30627090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com