Ajax简介
Ajax即Asynchronous JavaScript And XML(异步的JavaScript和XML) 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。Ajax的核心对象就是xmlHttpRequest,XMLHttpRequest用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新,而重定向和请求转发都是需要加载整个网页,因此使用Ajax技术能获得更好的用户体验。
原生Ajax方式实现:
视图层:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax技术基础</title>
<script type = "text/javascript">
window.onload = function(){
// 获取目标的对象
var divobj = document.getElementById("mydiv");
// 定义对象函数
divobj.onclick = function(){
//1 . 创建异步对象
var xhr = new XMLHttpRequest();
//2. 绑定事件
xhr.onreadystatechange = function(){
// console.log("请求状态为:"+xhr.readyState);
// console.log("服务器端响应状态为"+xhr.status);
if(xhr.readyState == 4 && xhr.status == 200){
//处理返回数据 可以更新DOM对象
var data = xhr.responseText; // 获取对象
// alert("Ajax收到的信息为:"+data);
var divobj = document.getElementById("mydiv"); // 局部变量
divobj.innerHTML = data; // 嵌入数据
}
}
//4. 初始请求参数
xhr.open("get","AjaxTest",true);
//5. 发起请求
xhr.send();
}
}
</script>
</head>
<body>
<div id = "mydiv" align = "center" style = "color:red"><h1>点击这</h1></div>
</body>
</html>
采用jQuery方式使用Ajax技术:
环境:spring+springMVC+Mybatis
结构:
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wu.ajax</groupId>
<artifactId>AjaxDemo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<!-- 版本锁定 -->
<properties>
<springVersion>5.2.0.RELEASE</springVersion>
</properties>
<!-- 坐标导入 -->
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.0</version>
</dependency>
<dependency>
<!-- 数据库连接池 -->
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.0</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
</project>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>AjaxDemo1</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- DispatcherServlet绑定Spring的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!-- 启动级别为1 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 乱码问题解决 -->
<filter>
<filter-name>encodingFilter</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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 会话时长设置 -->
<session-config>
<session-timeout>20</session-timeout>
</session-config>
</web-app>
applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-mvc.xml"></import>
<import resource = "classpath:spring-dao.xml"></import>
<import resource = "classpath:spring-service.xml" ></import>
</beans>
mybatis-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="LOG4J" />
</settings>
<!-- 对name名称下的包取别名 -->
<typeAliases>
<package name="com.wu.pojo"></package>
</typeAliases>
<mappers>
<mapper resource="com/wu/mapper/StudentMapper.xml"/>
</mappers>
</configuration>
spring-mvc.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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- JSON乱码问题配置 -->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class = "org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value = "utf-8"></constructor-arg>
</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>
<!-- 扫描使用注解的controller包 -->
<context:component-scan base-package="com.wu.controller" />
<!-- 资源过滤 -->
<mvc:default-servlet-handler/>
<!-- 视图解析器配置 -->
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver" id = "internalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/"></property>
<property name = "suffix" value = ".jsp"></property>
</bean>
</beans>
spring-dao.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 关联数据库配置文件 -->
<context:property-placeholder location="classpath:/database.properties"/>
<bean id = "dataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource">
<property name = "driverClass" value="${jdbc.driver}"/>
<property name = "jdbcUrl" value = "${jdbc.url}"/>
<property name = "user" value = "${jdbc.username}" />
<property name = "password" value = "${jdbc.password}" />
<property name ="maxPoolSize" value="${maxPoolSize}" /> <!--最大连接数-->
<property name ="initialPoolSize" value="${initialPoolSize}"/> <!--初始化连接数-->
<property name ="minPoolSize" value="${minPoolSize}" /> <!--最小连接数-->
<property name = "autoCommitOnClose" value = "false" /> <!-- 关闭连接后不自动提交 -->
</bean>
<bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean">
<property name = "dataSource" ref = "dataSource" />
<!-- 绑定Mybatis的配置文件 -->
<property name = "configLocation" value = "classpath:/mybatis-config.xml" />
</bean>
<!-- 将实现Mapper接口类注入Spring容器中 -->
<bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer" >
<property name = "sqlSessionFactoryBeanName" value = "sqlSessionFactory" />
<property name = "basePackage" value = "com.wu.mapper"/>
</bean>
</beans>
spring-service.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package = "com.wu.service" />
<!-- 声明事务配置 -->
<bean id = "transactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name = "dataSource" ref = "dataSource" />
</bean>
<!-- 配置事务通知 -->
<tx:advice id = "txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切入 -->
<aop:config>
<aop:pointcut expression="execution(* com.wu.service.*.*(..))" id="txPointCut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
database.properties:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
jdbc.username=root
jdbc.password=root
initialPoolSize=10
maxPoolSize=30
minPoolSize=10
log4j.properties:
# 级别为debug 控制台输出
log4j.rootLogger=DEBUG, cosole
log4j.appender.cosole=org.apache.log4j.ConsoleAppender
log4j.appender.cosole.layout=org.apache.log4j.PatternLayout
log4j.appender.cosole.layout.ConversionPattern=%5p [%t] - %m%n
pojo类:
package com.wu.pojo;
public class Student {
private String name;
private Long id;
private Integer grade;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getGrade() {
return grade;
}
public void setGrade(Integer grade) {
this.grade = grade;
}
}
mapper类及配置文件:
package com.wu.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.wu.pojo.Student;
public interface StudentMapper {
List<Student> findStudentByName(@Param("studentName") String name);
}
StudentMapper.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace = "com.wu.mapper.StudentMapper">
<resultMap type="Student" id="studentMapper">
<id property="id" column="student_id"/>
<result property="name" column="student_name"/>
<result property="grade" column="student_grade"/>
</resultMap>
<select id="findStudentByName" resultMap = "studentMapper" parameterType = "string" >
select * from student where student_name like CONCAT('%',#{studentName},'%')
</select>
</mapper>
service类:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package = "com.wu.service" />
<!-- 声明事务配置 -->
<bean id = "transactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name = "dataSource" ref = "dataSource" />
</bean>
<!-- 配置事务通知 -->
<tx:advice id = "txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务切入 -->
<aop:config>
<aop:pointcut expression="execution(* com.wu.service.*.*(..))" id="txPointCut"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>
</beans>
controller类:
package com.wu.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wu.pojo.Student;
import com.wu.service.IStudentService;
@Controller
@RequestMapping("/ajax")
public class MyController {
@Autowired
@Qualifier("studentService")
private IStudentService studentService;
@RequestMapping(path = "/ajaxTest",method = RequestMethod.POST)
@ResponseBody
public String ajaxTest(String name) {
List<Student> studentList = studentService.findStudentByName(name);
System.out.println(studentList);
ObjectMapper mapper = new ObjectMapper();
String result = null;
try {
result = mapper.writeValueAsString(studentList);
return result;
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
@RequestMapping(path = "/result",method = RequestMethod.GET)
public String resultPage(String studentName,Model model) {
List<Student> studentList = studentService.findStudentByName(studentName);
model.addAttribute("studentList",studentList);
return "result";
}
}
index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ajax</title>
<script type="text/javascript" src = "jquery/jquery-3.2.1.js"></script>
<style type='text/css'>
.box{
width: 650px;
height: 400px;
margin:100px auto;
}
.content{
width: 486px;
height: 30px;
float: left;
padding-left:10px;
}
button{
width: 80px;
height: 35px;
float: left;
margin-left:20px;
font-size:18px;
}
#pop{
margin-top:0;
width: 498px;
height: auto;
border: 1px solid gray;
border-top:0;
float: left;
}
ul{
list-style: none;
margin:0;
padding:0;
}
ul li{
margin-left:10px;
margin-top:10px;
cursor: pointer;
height: 30px;
line-height:30px;
}
ul li:hover{
background-color: gray;
}
</style>
<script type = "text/javascript">
function onchangeFun(){
$.ajax({
url:"ajax/ajaxTest",
type:"POST",
data:{"name":$("#txt").val()},
success: function(data) {
$("#history").empty(); // 清空记录
var datas = $.parseJSON(data); // 将json字符串转化为js对象数组
var content = "";
for(var i = 0 ; i<datas.length ; i++){
content += "<li onclick = clickFun("+"\'"+datas[i].name+"\'"+")>"+datas[i].name+"</li>";
}
$("#history").append(content); // 添加元素
}
});
}
// 将鼠标点击的val值传入搜索框中
function clickFun(value){
$("#txt").val(value);
}
</script>
</head>
<body >
<div class="box" id="box">
<h2>试试输入你的姓名</h2>
<form action = "ajax/result/" method = "get">
<input type="text" name="studentName" class="content" id="txt" oninput = "onchangeFun()"/>
<button type="submit">搜索</button>
</form>
<div class="pop" id="pop">
<ul id = "history"></ul>
</div>
</div>
</body>
</html>
resule.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>结果页面</title>
</head>
<body>
<br><br><hr>
<div align = "center">
<h2>结果</h2>
<table border = "1" cellspacing = "0">
<tr>
<th>姓名</th>
<th>学号</th>
<th>班级</th>
</tr>
<c:forEach items = "${requestScope.studentList}" var = "s">
<tr>
<td>${s.name}</td>
<td>${s.id}</td>
<td>${s.grade}</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
采用Ajax技术效果:
点击姓名,可以将内容填入搜索框内,搜索结果跳转页面: