【问题标题】:Not able to send JSON request to spring controller from Ajax无法从 Ajax 向 Spring 控制器发送 JSON 请求
【发布时间】:2018-01-25 10:28:31
【问题描述】:

我正在使用 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;
}

}

我的spring配置文件

<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

【问题讨论】:

  • 当您尝试添加内容类型时,您是否尝试过这样的操作:@RequestMapping(value="getNames", method=RequestMethod.POST, consumes="application/json")
  • 嗨,赛义德,您检查过网络标签吗?
  • @Thomas,是的,我试过了,而且,consumes=MediaType.APPLICATION_JSON_VALUE
  • @Pradeep 是的,这是我在网络中看到的消息“服务器拒绝了这个请求,因为请求实体的格式不受所请求方法的请求资源支持。”
  • 尝试删除内容类型或 ContentType: false 并在控制器中添加产生 = MediaType.APPLICATION_JSON_VALUE

标签: java json ajax spring spring-mvc


【解决方案1】:

我已将您的代码导入到我的项目中,并且运行良好。您应该检查您的 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

【讨论】:

  • 另外,你可以在控制器上发布你的 pom.xml(如果你使用的是 maven)和注释
  • 即使我已经发布了 bean。我应该在 spring-servlet.xml 中配置 bean 吗?
  • 我没有使用 maven,它是一个动态网络项目
  • 您是否尝试将注解从 Controller 更改为 @RestController ?
  • 你能告诉我所有的罐子里都有什么吗
猜你喜欢
  • 1970-01-01
  • 2021-08-09
  • 2016-05-17
  • 2014-05-07
  • 2016-03-16
  • 1970-01-01
  • 1970-01-01
  • 2021-04-08
  • 1970-01-01
相关资源
最近更新 更多