目录结构:
引入jquery文件,版本尽量在2.0以上。可以在官网下载,有需求的可以在下面留言。
<%--Created by IntelliJ IDEA.User: LFYDate: /2/6Time: 21:56To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>Title</title><script src="js/jquery-3.2.1.min.js"></script><script>//页面加载 绑定单机事件$(function () {$("#btn").click(function () {// alert("Hello btn");//发送ajax请求$.ajax({//编写json格式,设置属性和值url:"user/testAjax",contentType:"application/json;charset:UTF-8",data:'{"username":"fy","password":"123","age":"20"}',dataType:"json",type:"POST",success:function (data) {//data服务器端响应的json的数据,进行解析alert(data.username);alert(data.password);alert(data.age);}});});});</script></head><body><!--响应式返回值是String--><a href="user/testString">testString</a><br/><!--响应式返回值是void--><a href="user/voidString">voidString</a><br/><!--响应式返回值是ModelAndView--><a href="user/testModelAndView">testModelAndView</a><br/><button id="btn">发送ajax的请求</button><br/></body></html>
我们通过ajax请求,服务器端响应的json的数据,进行解析。
@RequestMapping("/testAjax")public @ResponseBody User testAjax(@RequestBody User user){System.out.println("testAjax方法执行了....");//客户端发送ajax的请求,传的是json字符串,后端把json字符串封装到user对象中System.out.println(user);//作响应,模拟查询数据库user.setUsername("飞扬");user.setAge(10);return user;}
这里通过@RequestBody传入,@ResponseBody传出
<!--前端控制器,那些静态资源不拦截--><mvc:resources mapping="/js/**" location="/js/"/><mvc:resources mapping="/css/**" location="/css/"/><mvc:resources mapping="/images/**" location="/images/"/>
由于在web.xml中我们用dispatcherServlet来拦截所有请求,所以我们需要在配置文件中加入配置,不让拦截那些静态资源,这里我把css和images都写了。
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.9.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.9.0</version></dependency>
如果要对json数据进行转换,需要加入jackson的jar包。
最后我们得出的效果是: