AJAX
Ajax即Asynchronous Javascript And XML(异步JavaScript和XML);Ajax技术网页应用能够快速地将增量更新呈现在用户界面上,不需要重载(刷新)整个页面,使程序能够更快地回应用户的操作
伪造AJAX
- 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> <load-on-startup>1</load-on-startup> </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 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.wei.controller"/> <!--静态资源过滤--> <mvc:default-servlet-handler/> <!--配置annotation-driven使:处理器映射器 和 处理器适配器 自动完成实例的注入--> <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>
- AjaxController类
package com.wei.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @RestController public class AjaxController { @RequestMapping("/t1") public String test(){ return "hello"; } @RequestMapping("/a1") public void a1(String name, HttpServletResponse response) throws IOException { System.out.println("a1:param=>"+name); if ("weishuo".equals(name)){ response.getWriter().print("True"); }else { response.getWriter().print("False"); } } }
- test.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>iframe测试体验页面无刷新</title> </head> <body> <div> <p>请输入地址:</p> <p> <input type="text" id="url" value="https://www.csdn.net/"> <input type="button" value="提交" onclick="go()"> </p> </div> <div> <iframe id="iframe" style="width: 100%;height: 500px"></iframe> </div> <script> function go(){ var url = document.getElementById("url").value; document.getElementById("iframe").src=url; } </script> </body> </html>
- index.jsp
<%-- Created by IntelliJ IDEA. User: ws199 Date: 2022/12/15 Time: 17:02 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> <script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.2.js"></script> <script> function a() { $.post({ url: "${pageContext.request.contextPath}/a1", data: {"name": $("#username").val()}, success: function (data,status) { console.log("data=" + data); console.log("status=" + status); } }) } </script> </head> <body> <%--失去焦点的时候,发起一个请求到后台--%> 用户名:<input type="text" id="username" οnblur="a()"> </body> </html>
启动tomcat测试!打开浏览器的控制台,当我们鼠标离开输入框的时候,可以看到发出了一个ajax的请求
AJAX异步加载数据
- user类
package com.wei.pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class User { private String name; private int age; private String sex; }
- AjaxController类
@RequestMapping("/a2") public List<User> a2(){ List<User> userList = new ArrayList<>(); //添加数据 userList.add(new User("wei_shuo",18,"男")); userList.add(new User("wei",17,"女")); userList.add(new User("shuo",8,"男")); return userList; }
- 前端jsp页面
<%-- Created by IntelliJ IDEA. User: ws199 Date: 2022/12/17 Time: 15:28 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.2.js"></script> <script> $(function () { $("#btn").click(function () { $.post("${pageContext.request.contextPath}/a2", function (data) { console.log(data) var html = ""; for (let i = 0; i < data.length; i++) { html += "<tr>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].age + "</td>" + "<td>" + data[i].sex + "</td>" + "</tr>" } $("#content").html(html); }) }) }); </script> </head> <body> <input type="button" value="加载数据" id="btn"> <table> <tr> <td>姓名</td> <td>年龄</td> <td>性别</td> </tr> <tbody id="content"> <%--数据:后台--%> </tbody> </table> </body> </html>
AJAX验证用户名
- AjaxController类
@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; }
- login.jsp页面
<%-- Created by IntelliJ IDEA. User: ws199 Date: 2022/12/20 Time: 9:01 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.2.js"></script> </head> <body> <p> 用户名:<input type="text" id="name" οnblur="a1()"> <span id="userInfo"></span> </p> <p> 密码:<input type="text" id="pwd" οnblur="a2()"> <span id="pwdInfo"></span> </p> <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: {"pwd": $("#pwd").val()}, success: function (data) { if (data.toString() === 'OK') { $("#pwdInfo").css("color", "green"); } else { $("#pwdInfo").css("color", "red"); } $("#pwdInfo").html(data); } }) } </script> </body> </html>
- AjaxController类
@RequestMapping("/a4") public String a4(String name, String pwd) { String msg = ""; if (name != null && pwd != null) { if ("Admin".equals(name) && "123456".equals(pwd)) { msg = "OK"; } else { msg = "用户名或者密码输入错误"; } } return msg; }
- login.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.2.js"></script> </head> <body> <p> 用户名:<input type="text" id="name" οnblur="Login()"> <span id="UserPwdInfo"></span> </p> <p> 密码:<input type="text" id="pwd" οnblur="Login()"> </p> <script> function Login() { $.post({ url: "${pageContext.request.contextPath}/a4", data: {"name": $("#name").val(),"pwd":$("#pwd").val()}, success: function (data) { if (data.toString() === 'OK') { $("#UserPwdInfo").css("color", "green"); } else { $("#UserPwdInfo").css("color", "red"); } $("#UserPwdInfo").html(data); } }) } </script> </body> </html>
拦截器
概述
SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。开发者可以自己定义一些拦截器来实现特定的功能
过滤器
- servlet规范中的一部分,任何java web工程都可以使用
- 在url-pattern中配置了/*之后,可以对所有要访问的资源进行拦截
拦截器
- 拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
- 拦截器只会拦截访问的控制器方法, 如果访问的是jsp/html/css/image/js是不会进行拦截的
- 拦截器MyInterceptor类
package com.wei.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 不执行下一个拦截器 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("======处理前======"); return true; } //在请求处理方法执行之后执行 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("======处理后======"); } //dispatcherServlet处理后执行,做清理工作 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("======清理======"); } }
- applicationContext.xml拦截器配置
<!--拦截器配置--> <mvc:interceptors> <mvc:interceptor> <!--/** 包括路径及其子路径--> <mvc:mapping path="/**"/> <!--bean配置的就是拦截器--> <bean class="com.wei.config.MyInterceptor"/> </mvc:interceptor> </mvc:interceptors>
- TestController测试
@RestController public class TestController { @GetMapping("t1") public String test(){ System.out.println("TestController==Test"); return "OK"; }
- 结果
======处理前====== TestController==Test ======处理后====== ======清理======
登录判断验证
- index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <h1><a href="${pageContext.request.contextPath}/user/goLogin">登录页面</a></h1> <h1><a href="${pageContext.request.contextPath}/user/main">首页</a></h1> </body> </html>
- main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>首页</h1> <span>${username}</span> <p> <a href="${pageContext.request.contextPath}/user/goOut">注销</a> </p> </body> </html>
- login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <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.wei.controller; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; 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, Model model){ session.setAttribute("userLoginInfo",username); model.addAttribute("username",username); return "main"; } @RequestMapping("/goOut") public String goOut(HttpSession session){ //销毁session数据 //session.invalidate(); //移除session数据 session.removeAttribute("userLoginInfo"); return "main"; } }
- 拦截器LoginInterceptor.java
package com.wei.config; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); //判断什么情况,放行 //登录页面,放行 if (request.getRequestURI().contains("goLogin")){ return true; } //第一次登录,没有session,放行 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; } }
- 拦截器配置applicationContext.xml
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/user/**"/> <bean class="com.wei.config.LoginInterceptor"/> </mvc:interceptor> </mvc:interceptors>
文件上传和下载
文件上传
- pom.xml导入包
<dependencies> <!--文件上传--> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency> <!--servlet-api导入高版本的--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> </dependencies>
- applicationContext.xml
<!--文件上传配置--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 --> <property name="defaultEncoding" value="utf-8"/> <!-- 上传文件大小上限,单位为字节(10485760=10M) --> <property name="maxUploadSize" value="10485760"/> <property name="maxInMemorySize" value="40960"/> </bean>
- index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post"> <input type="file" name="file"/> <input type="submit" value="upload"> </form> </body> </html>
- FileController.java
package com.wei.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.commons.CommonsMultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.*; @RestController public class FileController { //@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象 //批量上传CommonsMultipartFile则为数组即可 @RequestMapping("/upload") public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException { //获取文件名 : file.getOriginalFilename(); String uploadFileName = file.getOriginalFilename(); //如果文件名为空,直接回到首页! if ("".equals(uploadFileName)){ return "redirect:/index.jsp"; } System.out.println("上传文件名 : "+uploadFileName); //上传路径保存设置 String path = request.getServletContext().getRealPath("/upload"); //如果路径不存在,创建一个 File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } System.out.println("上传文件保存地址:"+realPath); InputStream is = file.getInputStream(); //文件输入流 OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流 //读取写出 int len=0; byte[] buffer = new byte[1024]; while ((len=is.read(buffer))!=-1){ os.write(buffer,0,len); os.flush(); } os.close(); is.close(); return "redirect:/index.jsp"; } /* * 采用file.Transto 来保存上传的文件 */ @RequestMapping("/upload2") public String fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException { //上传路径保存设置 String path = request.getServletContext().getRealPath("/upload"); File realPath = new File(path); if (!realPath.exists()){ realPath.mkdir(); } //上传文件地址 System.out.println("上传文件保存地址:"+realPath); //通过CommonsMultipartFile的方法直接写文件(注意这个时候) file.transferTo(new File(realPath +"/"+ file.getOriginalFilename())); return "redirect:/index.jsp"; } }
文件下载
- FileController.java
@RequestMapping(value="/download") public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{ //要下载的图片地址 String path = request.getServletContext().getRealPath("/upload"); String fileName = "基础语法.jpg"; //1、设置response 响应头 response.reset(); //设置页面不缓存,清空buffer response.setCharacterEncoding("UTF-8"); //字符编码 response.setContentType("multipart/form-data"); //二进制传输数据 //设置响应头 response.setHeader("Content-Disposition", "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8")); File file = new File(path,fileName); //2、 读取文件--输入流 InputStream input=new FileInputStream(file); //3、 写出文件--输出流 OutputStream out = response.getOutputStream(); byte[] buff =new byte[1024]; int index=0; //4、执行 写出操作 while((index= input.read(buff))!= -1){ out.write(buff, 0, index); out.flush(); } out.close(); input.close(); return null; }
- index.jsp
<a href="/download">点击下载</a>
🌼 结语:创作不易,如果觉得博主的文章赏心悦目,还请——
点赞
👍收藏
⭐️评论
📝