其他分享
首页 > 其他分享> > Spring控制器不接受application / json

Spring控制器不接受application / json

作者:互联网

当我从Chrome Rest Client传递application / json参数时,我收到400错误请求错误.
当我为@RequestParam添加required = false时,Controller接受请求,但值为Null.

@RequestMapping(value = "/add",
                method = RequestMethod.POST,
                consumes="application/json",
                produces="application/json")
public @ResponseBody String add(
  @RequestParam(value="surveyName") String surveyName,
  @RequestParam(value="surveyDesc")  String surveyDesc,
  ModelMap model) throws Exception
{
    System.out.println("request parameters in /add/syrvey surveyName= "+surveyName);
}

我的JSON请求如下,Content-Type是“aplication / json”

{"surveyName"="sd", "surveyDesc":"sd"}

我尝试使用headers =“Accept = application / json”,但它没有多大帮助.

我的调度程序 – servlet是

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=">
    <context:annotation-config />
    <context:component-scan base-package="com.survey.controller" />
    <context:component-scan base-package="com.survey.service" />
    <context:component-scan base-package="com.survey.dao" />
    <context:component-scan base-package="com.survey.entity" />
    <context:component-scan base-package="com.survey.constants" />
    <mvc:annotation-driven />
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters">
            <list>
                <ref bean="jacksonMessageConverter" />
            </list>
        </property>
    </bean>
</beans>

我的pom.xml是

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.9.12</version>
</dependency>

任何帮助非常感谢

解决方法:

在您的情况下,您可以使用地图:

public @ResponseBody String add(@RequestBody Map<String, String> input) throws Exception

然后迭代它以找到您的参数,或者您可以使用Pojo

public class Pojo {
    private String surveyName;
    private String surveyDesc;

    ...
}

public @ResponseBody String add(@RequestBody Pojo pojo) throws Exception

希望这可能有用!

标签:spring-mvc,spring,http-status-code-404,rest-client
来源: https://codeday.me/bug/20190624/1279106.html