SpringMVC处理AJAX请求

Spring MVC 处理AJAX请求

1.视图View的jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
	function ajaxFunction() {
		var xmlHttp;
		try {
			xmlHttp = new XMLHttpRequest();
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
					alert("您的浏览器不支持AJAX!");
					return false;
				}
			}
		}
		return xmlHttp;
	}

	function sendAjaxReq() {
		var xmlHttp = ajaxFunction();//创建一个xmlHttpRequest对象
		xmlHttp.open("GET", "ajax?id=2");//向处理器controller发送请求,表示发送给方法名为ajax()方法
		xmlHttp.setRequestHeader("accept", "application/json");//设置请求头
		xmlHttp.onreadystatechange = function() {//编写回调函数
// 			alert(xmlHttp.readyState);
// 			if (xmlHttp.readyState == 4) {
// 				eval("var result=" + xmlHttp.responseText);
// 				alert("["+result[0].id+","+result[0].name+","+result[0].age+","+result[0].salary+"]");
// 			}
			eval("var result=" + xmlHttp.responseText);//可以百度eval的作用
                        //将请求结果显示在页面上
			document.getElementById("div1").innerHTML = "["+result[0].id+","+result[0].name+","+result[0].age+","+result[0].salary+"]";
			document.getElementById("div2").innerHTML = "["+result[1].id+","+result[1].name+","+result[1].age+","+result[1].salary+"]";
		}
		xmlHttp.send(null);
	}
</script>
</head>
<body>

	<a href="javascript:void(0);" onclick="sendAjaxReq()">Ajax请求</a>
	<div id="div1"></div>
	<div id="div2"></div>

</body>
</html>

 
2.SpringMVC-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:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	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    
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">


<!-- 	<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> -->

<!-- 	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> -->

<!-- 	<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" /> -->

	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="cacheSeconds" value="0" />
		<property name="messageConverters">
			<list>
				<bean
					class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
			</list>
		</property>
	</bean>

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

	<context:component-scan base-package="com.mvc.*"></context:component-scan>
	<mvc:annotation-driven />
</beans>

 
3.处理器Contrller代码

@RequestMapping(value = "/ajax", method = RequestMethod.GET)//刚刚jsp页面中的open请求就发送到这个来了
@ResponseBody//核心就是这个annotation
public List<User> ajax(HttpServletRequest request, HttpServletResponse response) {
	System.out.println("AJAX");
	List<User> list = new ArrayList<>();
	User user = userService.getUser();//这个地方返回User对象,包括user.id,user.name,user.age,user.salary.....
	User user_ = userService.getUser_();
	list.add(user);
	list.add(user_);
	return list;
}

 
4.web.xml配置(就是普通的SpringMVC的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"
	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>webSpringMVC</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
	</welcome-file-list>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:config/applicationContext.xml</param-value>
	</context-param>

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

	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:config/springmvc-servlet.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

相关推荐