【SpringMVC】(八)使用Ajax前后端传数据&不使用Ajax
Ajax
-
AJAX=Asynchronous JavaSript and XML(异步的JavaScript和XML)。
-
实现异步局部更新页面
-
利用Ajax可以
- 登录用户时,自动检测用户是否存在、密码错误
- 删除数据时,数据库删除成功后,在页面中更新数据。
-
本文利用JQuery Ajax方法
1.搭建环境
-
pom.xml
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.9.RELEASE</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--lombok --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> <scope>provided</scope> </dependency> </dependencies> <build> <resources> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
-
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!--1. 注册DispatcherServlet--> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc-servlet.xml</param-value> </init-param> <!--启动级别-1--> <load-on-startup>1</load-on-startup> </servlet> <!-- / 和/* 的区别--> <!-- / 匹配所有的请求:(不包括.jsp)--> <!-- /* 匹配所有的请求:(包括.jsp)--> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--SpringMVC提供的乱码过滤器--> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
-
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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--自动扫描包,让指定包下的注解生效,由IOC容器统一管理--> <context:component-scan base-package="com.musecho.controller"/> <!--视图解析器ViewResolver:解析DispatcherServlet传递来的ModelAndView--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver"> <!--前缀--> <property name="prefix" value="/WEB-INF/jsp/" /> <!--后缀--> <property name="suffix" value=".jsp" /> </bean> <!--JSON乱码问题配置--> <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <constructor-arg value="UTF-8"/> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="objectMapper"> <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"> <property name="failOnEmptyBeans" value="false"/> </bean> </property> </bean> </mvc:message-converters> </mvc:annotation-driven> </beans>
-
User
@Data @AllArgsConstructor @NoArgsConstructor public class User { private String name; private int age; private String sex; }
-
Controller
@Controller public class UserController { }
2. 输入用户名,打印用户名是否正确
-
Controller:给前端返回字符串常量
@RequestMapping("/a1") public void ajax1(String name, HttpServletResponse resp) throws IOException { System.out.println("name=" + name); if ("admin".equals(name)) { resp.getWriter().print("true"); } else { resp.getWriter().print("false"); } }
-
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登录</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script> function login() { $.ajax({ url: "${pageContext.request.contextPath}/a1", data: {'name': $("#id").val()}, success: function (data, status) { console.log("data=" + data); console.log("status=" + status); } }) } </script> </head> <body> 用户:<input type="text" id="id" onblur="login()"> </body> </html>
-
控制台打印,可以直接打印出字符串常量。
3. 页面显示所有用户
-
Controller
@ResponseBody @PostMapping("/a2") public List<User> showAllUsers(HttpServletResponse resp) { List<User> list = new ArrayList<User>(); list.add(new User("小鸭子1号", 1, "男")); list.add(new User("小鸭子2号", 2, "女")); list.add(new User("小鸭子3号", 3, "男")); return list;//返回json格式的list字符串 }
-
allUsers.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script> $(function () { $.post("${pageContext.request.contextPath}/a2", function (list) { console.log(list); var jsonObj = eval(list); showData(jsonObj); }) }); function showData(jsonObj) { var text = ""; for (let i = 0; i < jsonObj.length; i++) { text += "<tr>"; text += "<td>" + jsonObj[i].name + "</td>"; text += "<td>" + jsonObj[i].age + "</td>"; text += "<td>" + jsonObj[i].sex + "</td>"; text += "</tr>"; } console.log(text); $("#content").html(text); } </script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="page-header"> <h1> <small>显示所有用户</small> </h1> </div> </div> </div> <div class="row"> <div class="col-md-12"></div> <table class="table table-striped table-hover"> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> </tr> </thead> <tbody id="content"> </tbody> </table> </div> </div> </body> </html>
-
控制台打印,返回的list的json格式字符串
-
这里如果用
resp.getWriter().print(list);//返回对象.toString()的字符串
返回数据看一下返回的是对象.toString()的字符串,这样返回给前端的ajax方法,取值是取不出来的。
如果想用这个方式返回给前段数据,可以使用GSON或Jackson等工具将对象转为json格式字符串,再返回。
4. 登录用户时,自动检测用户是否存在、密码错误
-
Controller:传给前端字符串变量
@ResponseBody @PostMapping("/a3") public String ajax3(String id, String pwd) { String msg = ""; if (!"".equals(id)) { if ("admin".equals(id)) { if (!"".equals(pwd)) { if ("123".equals(pwd)) { msg = "OK"; } else msg = "密码错误"; } } else msg = "用户名不存在"; } return msg; }
-
login2.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登录2</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script> function a3() { $.post("${pageContext.request.contextPath}/a3", { 'id': $("#id").val(), 'pwd': $("#pwd").val() }, function (data) { console.log(data); if (data == "OK") { $("#error").css("color","green"); } else $("#error").css("color","red"); $("#error").html(data); }) } </script> </head> <body> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="page-header"> <h1> <small>登录验证提示</small> </h1> </div> </div> </div> <div class="row"> <div class="col-md-6"> <form> <div class="form-group"> <p id="error" ></p> <label for="id">用户名</label> <input type="text" id="id" onblur="a3()"> </div> <div class="form-group"> <label for="pwd">密码</label> <input type="password" id="pwd" onblur="a3()"> </div> </form> </div> </div> </div> </body> </html>
-
控制台打印,字符串变量的值
5.总结
5.1 Controller中,后端返回给前端数据 有两种方式:
-
resp.getWriter().print(字符串对象或常量);
返回的是对象.toString()的字符串,不会自动转为json格式。
返回类型void
-
return 对象名(典型如List);
返回对象的json格式字符串。
返回类型与对象类型一样。
需要在方法上加注解
@ResponseBody
,或在类上加注解@RestController
。
若前端用ajax接受数据,需要的json格式。
注意,诸如list的对象用``return 对象名;`。字符串变量或常量两种方式皆可。
5.2 前端页面,使用ajax(模版):
-
ajax全写
function login() { $.ajax({ url: "${pageContext.request.contextPath}/a1", data: {'name': $("#id").val()}, success: function (data, status) { console.log("data=" + data); console.log("status=" + status); } }) }
-
post简写-无参
$(function () { $.post("${pageContext.request.contextPath}/a2", function (list) { var jsonObj = eval(list);//json字符串转为jsonObj对象 showData(jsonObj); }) });
-
post简写-无参
function a3() { $.post("${pageContext.request.contextPath}/a3", { 'id': $("#id").val(), 'pwd': $("#pwd").val() }, function (data) { console.log(data); if (data == "OK") { $("#error").css("color","green"); } else $("#error").css("color","red"); $("#error").html(data); }) }