Spring MVC - ajax集成pageContext.request.contextPath不能正常工作

时间:2015-07-13 20:33:59

标签: jquery ajax spring spring-mvc

我正在尝试使用Ajax将数据传递给控制器​​。但我认为URL属性存在问题。当我点击buttonHello时,ajax正在工作,但在错误功能中,er参数返回" NOT FOUND"。

我认为url属性有问题,因为没有调用控制器类。 我尝试了其他选项,如' / memorize / result / helloajax'等。 $ {pageContext.request.contextPath}的值是/ springcrud

我的Ajax

$(document).ready(function() {
    $('#buttonHello').click(function(){
        $.ajax({
            type : 'POST',
            url : '${pageContext.request.contextPath}/memorize/result/helloajax',
            success : function(data) {
                $('.result').html(data);
            },
            error:function(data,status,er) { 
                alert("error: "+data+" status: "+status+" er:"+er);
            }
        })
    });
});

的login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

<script src="<c:url value="/resources/js/jquery-1.11.3.min.js" />"></script>
<script src="<c:url value="/resources/js/main.js" />"></script>

<title>Login Page</title>
</head>

<input type="button" value="Hello" id="buttonHello">
<div id="result"></div>
</html>

ResultController:

@Controller
@RequestMapping(value = "/result")
public class ResultController {

    @RequestMapping(value ="/helloajax", method = RequestMethod.GET)
    @ResponseBody
    public String hello(){
        return "index";
    }

    @RequestMapping(value ="/helloajax", method = RequestMethod.POST)
    @ResponseBody
    public String helloajax(){
        return "Hello Ajax";
    }
}

我的Web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app id="WebApp_ID" version="2.4">

    <servlet>
        <servlet-name>springcrud</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
                
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springcrud</servlet-name>
        <url-pattern>/memorize/*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/springcrud-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
</web-app>

0 个答案:

没有答案