SpringMVC和Ajax交互
程序员小王java 人气:0SpringMVC与Ajax的交互
一、ajax的实现
ajax异步请求 javaScript and xml 异步请求
1、同步请求和异步请求
1、异步请求 特点:请求响应回来页面不动 只刷新页面局部
2、同步请求 特点:响应回来全部刷新(地址栏,超链接,表单 js的location.href="")
3、通过Ajax发送的请求都是异步请求 多请求之间并行处理 请求之间不会相互影响
2、Ajax实现异步请求
Ajax发送请求 通过js的异步请求对象发送请求 xhr XMLHttpRequest
js实现ajax:
1、创建异步请求对象 xhr 2、准备并且发送请求xhr.open() xhr.send(); 3、处理响应 xhr.onreadyStateChang=dunction(){ if(xhr.readyState==4&&xhr.status==200{ xhr.responseText } } 4、ajax只认字符串
jquery实现Ajax的封装
$.ajax({}) 基础发送Ajax请求的方式 $.get(url,method,function(){})//get方式发送请求 $.post(url,method,function{},"json")
二、SpringMVC和AJAX交互(手工处理)
控制器使用的json解析工具:阿里巴巴的fastjson
<!--引入阿里巴巴json解析器fastjson--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.73</version> </dependency>
1、案例:使用Ajax形式查询所有用户
(1)交互示意图
(2)ajax页面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <%--引入js相关的jquery页面--%> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js"></script> <script type="text/javascript"> $(function () { //获取单击按钮对象,绑定单击事件 $("#btn").click(function () { //发送get形式的Ajax异步请求 $.get("${pageContext.request.contextPath}/user/show", function (result) { console.log(result) }, "json"); }) }); </script> </head> <body> <input type="button" value="点击查询所有" id="btn"> </body> </html>
(3)实体类
public class User { private Integer id; private String Username; private String password; private Double salary; private Date birthday;
(4)Controller以手工转化json
@Controller @RequestMapping("user") public class QueryUser { @RequestMapping("show") public String showUser(HttpServletResponse response) throws IOException { User user1 = new User(1,"王恒杰1","123",2000d,new Date()); User user2 = new User(2,"王恒杰2","123",20000d,new Date()); User user3 = new User(3,"王恒杰3","123",200000d,new Date()); User user4 = new User(4,"王恒杰4","123",2000000d,new Date()); User user5 = new User(5,"王恒杰5","123",20000000d,new Date()); List<User> users = Arrays.asList(user1, user2, user3, user4, user5); //1、将users用户集合转化为json形式字符串 String jsonUsers = JSONObject.toJSONStringWithDateFormat(users, "yyyy-mm-dd"); //2、通过响应输出流,响应到客户端 //设置响应格式 response.setCharacterEncoding("utf-8"); response.getWriter().print(jsonUsers); return null; } }
(5)响应到前端中文乱码 Ajax前端页面响应中文乱码
响应之前先设置响应格式:
//设置响应格式 response.setCharacterEncoding("utf-8");
解决乱码问题后
三、SpringMVC和AJAX交互(@responseBody注解实现)
1、SpringMVC提供注解:@responseBody
@responseBody:简化返回的数据转化成json串并且通过response响应的回客户端过程
2、使用@ResponseBody替代手工处理(使用Ajax形式查询所有用户)
@Controller @RequestMapping("user") public class QueryUser { @RequestMapping("show") @ResponseBody public List<User> showUser(HttpServletResponse response) throws IOException { User user1 = new User(1,"王恒杰1","123",2000d,new Date()); User user2 = new User(2,"王恒杰2","123",20000d,new Date()); User user3 = new User(3,"王恒杰3","123",200000d,new Date()); User user4 = new User(4,"王恒杰4","123",2000000d,new Date()); User user5 = new User(5,"王恒杰5","123",20000000d,new Date()); List<User> users = Arrays.asList(user1, user2, user3, user4, user5); return users; } }
@ResponseBody
替代示意图
3、@responsBody注意事项
(1)@responsBody注解 使用的json转化工具 不是fastjson,用的是jackjson
<!--jackson相关依赖 Springmvc@responsBody注解使用jackSon--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.3</version> </dependency>
(2)@responsBody可以放在返回值前面
(3)设置当前方式的日期转化格式需要使用注解
//jackson SpringMVC内置的 @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") //fastjson 阿里的 @JSONFiled(format="yyyy-mm-dd")
解决办法:在实体类的属性Date加入:@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
设置后结果:
4、@ResponseBody案例:通过动态获取id查询用户并在页面显示结果
(1)前端页面动态获取id,通过Ajax实现异步传输id值到Controller层
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js"></script> <script> $(function () { $("#del").click(function () { $.get("${pageContext.request.contextPath}/user/showById?id=" + $("input[name='id']").val(), function (result) { console.log(result); // 创建ul标签 var ul = $("<ul></ul>"); // 创建li当前获取到的值 var idLi = $("<li>" + result.id + "</li>"); var usernameLi = $("<li>" + result.username + "</li>"); var passwordLi = $("<li>" + result.password + "</li>"); var salaryLi = $("<li>" + result.salary + "</li>"); var birthdayLi = $("<li>" + result.birthday + "</li>"); // 将li子标签添加到ul上 ul.append(idLi); ul.append(usernameLi); ul.append(passwordLi); ul.append(salaryLi); ul.append(birthdayLi); $("#body").append(ul) }, "json"); }) }) </script> </head> <body id="body"> ID:<input type="text" name="id" placeholder="请输入用户的ID"> <input type="button" name="id" value="提交" id="del"> </body> </html>
(2)控制层java代码
@RequestMapping("showById") public @ResponseBody User showUserById(HttpServletResponse response,Integer id) throws IOException { User user1 = new User(1,"王恒杰1","123",2000d,new Date()); User user2 = new User(2,"王恒杰2","123",20000d,new Date()); User user3 = new User(3,"王恒杰3","123",200000d,new Date()); User user4 = new User(4,"王恒杰4","123",2000000d,new Date()); User user5 = new User(5,"王恒杰5","123",20000000d,new Date()); List<User> users = Arrays.asList(user1, user2, user3, user4, user5); for (User user : users) { if(id.equals(user.getId())){ return user; } } return null; }
(3)效果展示图
总结
加载全部内容