简体   繁体   English

无法使用 Jquery、Ajax 和 Json 向 Spring 控制器发送 POST 请求

[英]Not able to send a POST request to Spring controller using Jquery, Ajax and Json

I am trying to make a very simple flow using Spring, jQuery, Ajax and Json.我正在尝试使用 Spring、jQuery、Ajax 和 Json 制作一个非常简单的流程。 But I am not able to send a POST request to Spring controller.但我无法向 Spring 控制器发送 POST 请求。 Also my eclipse shows compilation error when I am trying to use consumes and produces in @RequestMapping.当我尝试在@RequestMapping 中使用消耗和生产时,我的 Eclipse 也显示编译错误。 I am not using maven.我没有使用 Maven。 It is a simple dynamic web project in eclipse.它是eclipse中一个简单的动态web项目。 I am using spring 3.0.5 jars.我正在使用 spring 3.0.5 罐子。

HTML page. HTML 页面。

<html>
  <head>
  <style>
    div {
            border: 1px solid #000000;
        }
  </style>

    <script src="/JSONProject/js/jquery-1.11.0.min.js"></script>
    <script>
    var user="";
    var pwd1="";
    var json="";
    var strJson="";
        $(document).ready(function(){

            $("#button").click(function(){  
                console.log("inside click");
                user=$("#userName").val();
                pwd1=$("#password").val();
                json={username:user,password:pwd1};
                console.log("json: "+json);
                strJson=JSON.stringify(json);
                console.log("strJson: "+strJson);

                $.ajax({
                    type: "POST",
                    url: "http://localhost:8080/JSONProject/add.html",
                    contentType: 'application/json',
                    data: JSON.stringify(json)
                })
                .done(function(resultUserDTO) {
                    JSON.stringify(resultUserDTO)
                    alert("result: "+resultUserDTO);
                    });



            });
        });
    </script>
  </head>
  <body>
  <FORM>
            Please enter your text:
            <BR>
                <div  >
                    <label id="uName">Username</label>
                    <input id="userName"/>
                    <br>
                    <label id="pwd">Password</label>
                    <input id="password" type="Password" id="pwd"/>

                </div>
            <BR>
            <INPUT id="button" TYPE="SUBMIT" VALUE="Submit">
        </FORM>
  </body>
</html>

Controller:控制器:

package demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import demo.model.Login;

@Controller

public class HelloWorldController {

    Login users;

    @RequestMapping("/hello")
    public ModelAndView helloWorld() {

        String message = "Hello World, Spring 3.0!";
        System.out.println("Inside controller");
        return new ModelAndView("hello", "message", message);
    }

    /**
     * Handles POST request
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST ,consumes = "application/json")
    public String processJson(@RequestBody String requestBody){

        return "Handled application/json request "; 


    }
}

I am getting the following compilation error:我收到以下编译错误:

The attribute consumes is undefined for the annotation type RequestMapping注释类型 RequestMapping 的属性消耗未定义

web.xml网页.xml

<?xml version="1.0" encoding="UTF-8"?>
<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>


    <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>*.html</url-pattern>
    </servlet-mapping>
</web-app>

spring-servlet.xml spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<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"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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
http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <context:component-scan base-package="demo.controller" />
    <mvc:annotation-driven /> 

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

</beans>

index.jsp索引.jsp

<html>
<head>
    <title>Spring with ajax</title>
</head>
<body>
    <a href="hello.html">Say Hello</a>
</body>
</html>

When I click the hello.html link in index.jsp, hello.html opens and i get the syso of the controller method that handles "\\hello" and get.当我单击 index.jsp 中的 hello.html 链接时,hello.html 打开并且我得到处理“\\hello”的控制器方法的 syso 并获取。 But when i make a POST request using jquery, i still see the syso of the method that handle "\\hello" and get method on console..但是当我使用 jquery 发出 POST 请求时,我仍然在控制台上看到处理“\\hello”和 get 方法的方法的 syso..

Really confused.真的很迷茫。 Please help Thank you in advance!!请帮忙先谢谢了!!

New updated code after the suggestions given.给出建议后新的更新代码。 Code has complied.代码已遵守。 Yet not call to POST handler.尚未调用 POST 处理程序。 Syso inside POST handler is not getting printed on eclipse console. POST 处理程序中的 Syso 未打印在 Eclipse 控制台上。

Controller:控制器:

package demo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import demo.model.Login;

@Controller

public class HelloWorldController {

    Login users;

    @RequestMapping("/hello")
    public ModelAndView helloWorld() {

        String message = "Hello World, Spring 3.0!";
        System.out.println("Inside controller");
        return new ModelAndView("hello", "message", message);
    }

    /**
     * Handles request for adding two numbers
     */
    @RequestMapping(value = "/add",method = RequestMethod.POST ,consumes = "application/json",produces = "application/json")
    public @ResponseBody String processJson(@RequestBody String requestBody){
        System.out.println("inside controller 2");

        return "Handled application/json request "; 


    }
}

hello.html:你好.html:

<html>
  <head>
  <style>
    div {
            border: 1px solid #000000;
        }
  </style>

    <script src="/JSONProject/js/jquery-1.11.0.min.js"></script>
    <script>
    var user="";
    var pwd1="";
    var json="";
    var strJson="";
        $(document).ready(function(){

            $("#button").click(function(){  
                console.log("inside click");
                user=$("#userName").val();
                pwd1=$("#password").val();
                json={username:user,password:pwd1};
                console.log("json: "+json);
                strJson=JSON.stringify(json);
                console.log("strJson: "+strJson);

                $.ajax({
                    type: "POST",
                    url: "http://localhost:8080/JSONProject/add.html",
                    contentType: 'application/json',
                    data: JSON.stringify(json)
                })
                .done(function(resultUserDTO) {
                    JSON.stringify(resultUserDTO)
                    alert("result: "+resultUserDTO);
                    });



            });
        });
    </script>
  </head>
  <body>
  <FORM method="post">
            Please enter your text:
            <BR>
                <div  >
                    <label id="uName">Username</label>
                    <input id="userName"/>
                    <br>
                    <label id="pwd">Password</label>
                    <input id="password" type="Password" id="pwd"/>

                </div>
            <BR>
            <INPUT id="button" TYPE="SUBMIT" VALUE="Submit">
        </FORM>
  </body>
</html>

PS: I have used 3.2.0 version PS:我用的是3.2.0版本

The produces and consumes attributes have been introduced with spring 3.1. producesconsumes属性已在 spring 3.1 中引入。 See: http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/new-in-3.1.html请参阅: http : //docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/new-in-3.1.html

You are using spring 3.0.x, so your program won't compile and therefore won't do anything.您使用的是 spring 3.0.x,因此您的程序将无法编译,因此不会执行任何操作。

Also, as configured, your add method's return value will be used as a view name ( A view with name "Handled application/json request ").此外,根据配置,您的add方法的返回值将用作视图名称(名称为“处理的应用程序/json 请求”的视图)。 If you want to handle the content generation by yourself annotate your add method with @ResponseBody .如果您想自己处理内容生成,请使用@ResponseBody注释您的add方法。

Also your js handler is calling the wrong url:此外,您的 js 处理程序正在调用错误的 url:

$.ajax({
    url: "http://localhost:8080/JSONProject/add.html"
});

vs.对比

@RequestMapping(value = "/add",method = RequestMethod.POST ,consumes = "application/json")
public String processJson(@RequestBody String requestBody){

Either change the js/ajax url to http://localhost:8080/JSONProject/add or your request mapping to @RequestMapping(value = "/add.html",method = RequestMethod.POST ,consumes = "application/json")将 js/ajax url 更改为http://localhost:8080/JSONProject/add或您的请求映射到@RequestMapping(value = "/add.html",method = RequestMethod.POST ,consumes = "application/json")

Following is my observation, let me know if it helps:以下是我的观察,如果有帮助,请告诉我:

1. Internal Resource View Resolver 1. 内部资源视图解析器

Your Internal Resource View Resolver looks for files with suffix .htm in jsp folder.您的内部资源视图解析器会在 jsp 文件夹中查找后缀为 .htm 的文件。 Hence all your files, except index.jsp, should end with .htm.因此,除了 index.jsp 之外的所有文件都应该以 .htm 结尾。 Or if they are .html, you can change the View Resolver to look for .html instead.或者,如果它们是 .html,您可以更改视图解析器以查找 .html。

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

2. Input Type Button not Submit 2.输入类型按钮不提交

Change the Input Type to just Button and not Submit.将输入类型更改为仅按钮而不是提交。 On Click of this Input[type="Submit"], tends to submit the form to the action of the form(which isn't specified hence reloads the page which is why you get the same syso).单击此输入 [type="Submit"] 时,倾向于将表单提交给表单的操作(未指定因此重新加载页面,这就是您获得相同系统的原因)。 You want to override this input with your onclick event.您想用您的 onclick 事件覆盖此输入。 Hence change it's type to button.因此将其类型更改为按钮。

   <INPUT id="button" TYPE="Button" VALUE="Submit">

3. Consumes and Produces 3. 消费和生产

Not really required.不是真的需要。 Those are basically restrictions on the handlers.这些基本上是对处理程序的限制。 It was giving me trouble.它给我带来了麻烦。 It works without them.没有它们它也能工作。 Totally your call on this one.完全是你对这个的呼吁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM