Ajax与SpringMvc交互

ajax是一种比较常用的页面技术,以其良好的交互效果已经被广泛应用,为了方便的使用ajax,市面上也出现的不少的ajax框架如dwr。为此springmvc借鉴了dwr的思想,可以使用ajax和springmvc交互,同时提供了java对象转换成json的机制。还是先一睹为快吧

1 如果需要springmvc进行java对象和json的转换需要增加如下配置

<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>

如果json数据不需要springmvc进行转换messageConverters的配置可以忽略


2 在控制器中的方法加上注解@ResponseBody,此时该方法就可以通过ajax直接访问了

package com.sxt.action;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

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 com.sxt.po.User;

@Controller
@RequestMapping("myajax.do")
public class MyAjaxController {
	
	@RequestMapping(params="method=test1",method=RequestMethod.GET)
	public @ResponseBody List<User> test1(String uname) throws Exception{ 
		String uname2 = new String(uname.getBytes("iso8859-1"),"UTF-8");
		System.out.println(uname2); 
		System.out.println("MyAjaxController.test1()");
		List<User> list = new ArrayList<User>();
		list.add(new User("潘玮柏","123"));
		list.add(new User("蔡依林","456"));
		
		return list;
	}
	
}

3 使用ajax请求springmvc并取得返回值
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<script>
		function createAjaxObj(){
			var req;
			if(window.XMLHttpRequest){
				req = new XMLHttpRequest();
			}else{
				req = new ActiveXObject("Msxml2.XMLHTTP");  //ie
			}
			return req;
		}
		
		function sendAjaxReq(){
			var req = createAjaxObj();
			req.open("get","myajax.do?method=test1&a="+Math.random());
			req.setRequestHeader("accept","application/json"); 
			req.onreadystatechange  = function(){
				alert(req.responseText);
				//eval("var result="+req.responseText);
				//document.getElementById("div1").innerHTML=result[0].uname;
			}
			req.send(null);
		}
	</script>
  </head>
  
  <body>
    <a href="javascript:void(0);" onclick="sendAjaxReq();">测试</a>
    <div id="div1"></div>
  </body>
</html>

最后来看看运行效果:

是不是也特别简单呢,其中最要注意的是使用这种方式需要jackson的支持,因此下面的这两个jar包不能少

这次先到这里,下次分享的是springmvc的拦截器。

相关文章

开发过程中是不可避免地会出现各种异常情况的,例如网络连接...
说明:使用注解方式实现AOP切面。 什么是AOP? 面向切面编程...
Spring MVC中的拦截器是一种可以在请求处理过程中对请求进行...
在 JavaWeb 中,共享域指的是在 Servlet 中存储数据,以便在...
文件上传 说明: 使用maven构建web工程。 使用Thymeleaf技术...
创建初始化类,替换web.xml 在Servlet3.0环境中,Web容器(To...