AJAX | 拦截器、文件上传和下载

在这里插入图片描述

wei_shuo的个人主页

wei_shuo的学习社区

Hello World !


AJAX

Ajax即Asynchronous Javascript And XML(异步JavaScript和XML);Ajax技术网页应用能够快速地将增量更新呈现在用户界面上,不需要重载(刷新)整个页面,使程序能够更快地回应用户的操作

伪造AJAX

  • web.xml

<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>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:applicationContext.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>

    <filter>
        <filter-name>encodingfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>utf-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>encodingfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
web-app>
  • applicationContext.xml

<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">

    
    <context:component-scan base-package="com.wei.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>
  • ​ 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" %>


    $Title$

    

    



<%--失去焦点的时候,发起一个请求到后台--%>
用户名:



启动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" %>


    Title
    
    






    <%--数据:后台--%>

    
姓名 年龄 性别

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" %>


    Title
    



用户名:

密码:

  • 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" %>


    Title
    



用户名:

密码:

拦截器

概述

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 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-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.3.3version>
        dependency>
        
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>javax.servlet-apiartifactId>
            <version>4.0.1version>
        dependency>
    dependencies>
  • applicationContext.xml

<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    
    <property name="defaultEncoding" value="utf-8"/>
    
    <property name="maxUploadSize" value="10485760"/>
    <property name="maxInMemorySize" value="40960"/>
bean>
  • index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    $Title$


  • 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
点击下载

结语:创作不易,如果觉得博主的文章赏心悦目,还请——点赞收藏⭐️评论


你可能感兴趣的:(ajax,servlet,javascript)