Ajax技术
Asynchronous Javascript And XML (异步JavaScript和XML)
异步无刷新请求
Jquery就是一个库
jQuery使用
1.配置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">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
- 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"
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">
<!--注解驱动 视图解析器 静态资源过滤-->
<context:component-scan base-package="com.kang.controller"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
- index.jsp 编写相应的js代码 导入jQuery
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.0.js"></script>
<script>
function a() {
$.post(
{
url: "${pageContext.request.contextPath}/a1",
data: {"name": $("#username").val()},
success: function (data) {
alert(data);
},
}
)
}
</script>
</head>
<body>
<%--失去焦点的时候,发送一个请求到后台--%>
用户名:<input type="text" id="username" onblur="a()">
</body>
</html>
- AjaxController 编写后台接口
package com.kang.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@RestController
public class AjaxController {
@RequestMapping("/ajax1")
public String test() {
return "hello";
}
@RequestMapping("/a1")
public void a1(String name, HttpServletResponse response) throws IOException {
System.out.println("a1:para,==>" + name);
if ("kangnkang".equals(name)) {
response.getWriter().print("true");
} else {
response.getWriter().print("false");
}
}
}
模拟用户异步登录
AjaxController
- 设计controller容器
@RequestMapping("/a3")
public String a3(String name, String pwd) {
String msg = "";
if (name != null) {
if ("admin".equals(name)) {
msg ="ok";
}else {
msg="用户名有误";
}
}
if (pwd != null) {
if ("123456".equals(pwd)) {
msg ="ok";
}else {
msg="密码有误";
}
}
return msg;
}
- 设计jsp站点
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.0.js"></script>
<script>
function a1() {
//发起一个请求
$.post({
url: "${pageContext.request.contextPath}/a3",
data: {"name": $("#name").val()},
success: function (data) {
if (data.toString() === 'ok') {
$("#userInfo").css("color", "green");
} else {
$("#userInfo").css("color", "red");
}
$("#userInfo").html(data);
}
})
}
function a2() {
$.post({
url: "${pageContext.request.contextPath}/a3",
data: {"name": $("#name").val()},
success: function (data) {
if (data.toString() === 'ok') {
$("#pwdInfo").css("color", "green");
} else {
$("#pwdInfo").css("color", "red");
}
$("#pwdInfo").html(data);
}
})
}
</script>
</head>
<body>
<p>
用户名:<input type="text" id="name" onblur="a1()">
<span id="userInfo"></span>
</p>
<p>
密码:<input type="text" id="pwd" onblur="a2()">
<span id="pwdInfo"></span>
</p>
</body>
</html>
拦截器
1.配置web.xml文件以及applicationContext.xml,并且在applicationContext.xml中配置拦截器
<!--拦截器配置-->
<mvc:interceptors>
<mvc:interceptor>
<!--**代表包括这个请求下面的所有请求-->
<mvc:mapping path="/**"/>
<bean class="com.kang.config.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
-
设计拦截器
//return true 执行下一个拦截器 放行
//return false 不执行下一个拦截器
package com.kang.config;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyInterceptor implements HandlerInterceptor {
//return true 执行下一个拦截器 放行
//return false 不执行下一个拦截器
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("=======处理前======");
return false;
}
//日志
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("=======处理后======");
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("=======清理======");
}
}
验证用户是否登录
- 编写登录页面 login.jsp /WEB-INF/jsp/login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--WEB-INF下的所有页面或者资源,只能通过controller,或者servlet进行访问--%>
<h1>登录页面</h1>
<form action="${pageContext.request.contextPath}/user/login" method="post">
用户名:<input type="text" name="username"/>
密码:<input type="text" name="password"/>
<input type="submit" value="提交">
</form>
</body>
</html>
- 编写LoginController 处理请求
package com.kang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
@Controller
@RequestMapping("/user")
public class LoginController {
@RequestMapping("/main")
public String main() {
return "main";
}
@RequestMapping("/goLogin")
public String login() {
return "login";
}
@RequestMapping("/login")
public String login(HttpSession session, String username, String password) {
//把用户的的信息存在Session中:
session.setAttribute("userLoginInfo", username);
return "main";
}
@RequestMapping("/goOut")
public String loginOut(HttpSession session, String username, String password) {
//把用户的的信息存在Session中:
session.removeAttribute("userLoginInfo");
return "login";
}
}
- 编写登录成功的页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>首页</h1>
<p>
<a href="${pageContext.request.contextPath}/user/goOut">注销</a>
</p>
</body>
</html>
- 编写拦截器
public class LoginInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
//放行:判断什么情况下登录
//登录页面放行
if (request.getRequestURI().contains("goLogin")){
return true;
}
if (request.getRequestURI().contains("login")){
return true;
}
if (session.getAttribute("userLoginInfo") != null) {
return true;
}
//判断什么情况下没有登录
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
return false;
}
}
- 在springmvc的配置文件中注册拦截器
<!--拦截器配置-->
<mvc:interceptors>
<mvc:interceptor>
<!--**代表包括这个请求下面的所有请求-->
<mvc:mapping path="/user/**"/>
<bean class="com.kang.config.LoginInterceptor"/>
</mvc:interceptor> <mvc:interceptor>
<!--**代表包括这个请求下面的所有请求-->
<mvc:mapping path="/**"/>
<bean class="com.kang.config.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>