一.除了搭建springmvc框架需要的jar包外,还需要这两个jar包
jackson-core-asl-1.9.2.jar和jackson-mapper-asl-1.9.2.jar
二.web,.xml配置
classpath:spring-servlet.xml指定springmvc配置文件的位置
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
spring
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-servlet.xml
1
spring
*.do
三.spring-servlet.xml配置
通过此配置,将实体类自动返回为json格式的数据
application/json;charset=UTF-8
四,后台java代码
packageme.mvc;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.text.SimpleDateFormat;importjava.util.ArrayList;importjava.util.Date;importjava.util.HashMap;importjava.util.List;importjava.util.Map;importjavax.annotation.Resource;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importme.mvc.service.testmvcDao;importnet.sf.json.JSONArray;importorg.apache.struts2.ServletActionContext;importorg.springframework.http.HttpRequest;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.ModelAttribute;importorg.springframework.web.bind.annotation.PathVariable;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestMethod;importorg.springframework.web.bind.annotation.ResponseBody;importorg.springframework.web.multipart.MultipartFile;importorg.springframework.web.multipart.MultipartHttpServletRequest;importorg.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/mvc/*")public classtestmvc {
@RequestMapping(method=RequestMethod.GET,value="/hello22index.do")//第一步访问hello2页面
publicString index2() {
return "hello2";
}
@ResponseBody
@RequestMapping(method=RequestMethod.POST,value="/hello22.do")//第二步前台发送ajax请求调用此方法并返回json数据
public User index2post(String testname1 ,HttpServletResponse response) throwsIOException {
System.out.println("*************:"+testname1);
User u=newUser();
u.setUsername("name");
u.setUserpassword("pass");returnu;
}
}
五.前端页面
该方法sendajax()将向后台发送请求,调用index2post()方法,返回json数据格式
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'hello2.jsp' starting pagefunction sendajax()
{
var testname1=$("#testname1").val();
alert(testname1);
$.ajax({
type: "post",
url: "/mvc/hello22.do",
data: {testname1:testname1},
dataType: "json",
success: function (data) {
alert(data.username);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("系统繁忙,请稍后重试!");
}
});
}