无法从Ajax向Spring控制器发送JSON请求

时间:2017-08-17 06:13:42

标签: java json ajax spring spring-mvc

我正在使用Spring MVC来创建我的项目模板。

我正在尝试使用Ajax向我的spring控制器发送JSON请求,我尝试添加json的内容类型等。它是一个POST请求。然而试验失败了。

的index.jsp

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {      

        $.ajax({ 
            url:"getNames",
            type:"POST", 
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({"name":"testName"}), 
            async: false,    
            cache: false,      
            dataType : "json",
             processData:false, 
             success: function(resposeJsonObject){
                // Success Action
            }
        });


    });
</script>

控制器

除导入以外的总控制器

@Controller
public class HelloWorldController {

// Produces JSON data
@RequestMapping(value="hello",produces="application/json")
public @ResponseBody String helloWorld() throws JSONException {

    JSONObject obj = new JSONObject();
    obj.put("my key", "my Value");
    return obj.toString();
}

// Accept JSON data
@RequestMapping(value="getNames", method=RequestMethod.POST)
public @ResponseBody Test addNewWorker(@RequestBody Test jsonString) {
    Test test = new Test();
    test.setName(jsonString.getName());
    System.out.println(test.getName());
    return test;
}

Web.xml中

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>Spring3MVC</display-name>
<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

我的测试课

public class Test implements Serializable {
/**
 * 
 */
private static final long serialVersionUID = 1L;
private String name;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

我的弹簧配置文件

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">


<context:component-scan base-package="net.viralpatel.spring3.controller" />

<bean id="test" class="com.qiib.spring3.model.Test"></bean>


<bean id="viewResolver"
    class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass"
        value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>

错误

org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver logException
WARNING: Handler execution resulted in exception: Content type 'application/json;charset=UTF-8' not supported

以下JAR可在我的项目中使用

aopalliance-1.0.jar
commons-logging-1.2.jar
jackson-core-asl-1.9.13.jar
jackson-databind-2.1.4.jar
jackson-mapper-asl-1.9.13.jar
jackson-servlet-api-3.1.0.jar
jstl-1.2.jar
spring-aop-4.2.0.RELEASE.jar
spring-beans- ""
spring-context-""
spring-core-""
spring-expression-""
spring-web-""
spring-webmvc-4.2.0.RELEASE.jar

1 个答案:

答案 0 :(得分:0)

我已将您的代码导入到我的项目中,并且它的工作非常好。你应该检查你的bean和pom.xml。我发布了我的代码和结果:

控制器:

@RequestMapping(value="getNames", method=RequestMethod.POST)
        public @ResponseBody Test addNewWorker(@RequestBody Test jsonString) {
            Test test = new Test();
            test.setName(jsonString.getName());
            System.out.println(test.getName());
            return test;
        }

index.js:

$.ajax({ 
        url:"getNames",
        type:"POST", 
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify({"name":"testName"}), 
        async: false,    
        cache: false,      
        dataType : "json",
         processData:false, 
         success: function(resposeJsonObject){
            // Success Action
        }
    });

输出:

2017-08-17 08:59:22.045  INFO 7092 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring FrameworkServlet 'dispatcherServlet'
2017-08-17 08:59:22.046  INFO 7092 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2017-08-17 08:59:22.049  INFO 7092 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 3 ms
testName
相关问题