简体   繁体   中英

Implementing Ajax in spring MVC

Ajax is not sending the data to the specified URL. Here is my controller:

@Controller
public class HomeController {
    private List<User> userList = new ArrayList<User>();

    @RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
    public String showForm() {
        return "AddUsers";
    }

    @RequestMapping(value = "User.htm", method = RequestMethod.POST)
    public @ResponseBody
    String addUser(@ModelAttribute(value = "user") User user,
            BindingResult result) {
        String returnText;

        if (!result.hasErrors()) {
            userList.add(user);
            returnText = "User has been added to the list. Total number of users are"
                    + userList.size();
        } else {
            returnText = "Sorry, an error has occur. User has not been added to list.";
        }
        return returnText;
    }

    @RequestMapping(value = "ShowUsers.htm")
    public String showUsers(ModelMap model) {
        model.addAttribute("Users", userList);
        return "ShowUsers";
    }
}

AddUser.jsp page

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>
<script type="text/javascript">
function AjaxCall() {
  alert('ready');
  //get the form variables....

  var name = $('#name').val();
  var education = $('#education').val();

  $.ajax({

    type: "POST",
    url: "AddUsers.htm",
    data: " name=" + name + "&education=" + education,
    success: function (response) {

      $('#info').html(response);
      $('#name').val('');
      $('#education').val('');
    },
    error: function (e) {
      alert('ERROR : ' + e);
    }
  });
}
</script>
<body>
<h1>Welcome to the AddUsers page. </h1>
<table>
<tr><td>Enter your name : </td><td> <input type = "text" id="name"></td></tr>
<tr><td>Educational qualification : </td><td> <input type = "text" id="education"></td></tr>
<tr><td colspan = "2"><input type="button" value="Add Users" onclick="AjaxCall()"></td></tr>
<tr><td colspan = "2"><div id ="info"></div></td></tr>
</table>
<a href="ShowUsers.htm">Show users </a>

</body>
</html>

I have inserted an alert within the ajax which never comes up. So I believe there is something wrong with the ajax method.

web.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-          app_2_5.xsd">
    <!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/root-context.xml</param-value>
    </context-param>
    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!-- Processes application requests -->
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

I have also created a domain class which would store the student information:

public class User {
    private String name = null;
    private String education = null;

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

    public String GetName() {
        return name;
    }

    public void SetEdu(String education) {
        this.education = education;
    }

    public String GetEdu() {
        return education;
    }
}

There is also a warning:

WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with 
URI [/sum/] in DispatcherServlet with name 'appServlet'>`

Dispatch servlet:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/mvc           http://www.springframework.org/schema/mvc/spring-mvc.xsd     http://www.springframework.org/schema/beans             http://www.springframework.org/schema/beans/spring-beans.xsd   http://www.springframework.org/schema/context          http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />
    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources 
        in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />
    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-
        INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>
    <context:component-scan base-package="com.faisal.sum" />
</beans:beans>

I corrected the upper case problem ( $.ajax instead of $.Ajax ). Thanks for pointing out.

Now I have a different error:

POST http://localhost:8080/sum/AddUsers.htm 405 (Method Not Allowed)

the url you are calling is this

type: "POST",
url: "AddUsers.htm",

Which is POST, the controller method is GET. Hecne the 405 error, method not supported.

将网址:“ AddUsers.htm”更改为网址:“ $ {pageContext。request.contextPath} /AddUsers.htm”,然后尝试。

You try to send POST request but mapped your method call with GET method

@RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)

try to change RequestMethod.GET to POST

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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