前言:

本文内容:Ajax异步加载数据、Ajax验证用户名体验、拦截器是什么

推荐免费SpringMVC基础教程视频:【狂神说Java】SpringMVC最新教程IDEA版通俗易懂_哔哩哔哩_bilibili

Ajax异步加载数据

  1. 创建实体类User.java(提前在pom中导入lombok)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    package com.jokerdig.pojo;

    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;

    /**
    * @author Joker大雄
    * @data 2022/6/17 - 17:25
    **/
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User {
    private String name;
    private int age;
    private String sex;
    }
  2. 编写AjaxController

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    // 模拟json数据提交到前端
    @RequestMapping("/ajax2")
    public List<User> ajax2(){
    ArrayList<User> userList = new ArrayList<>();
    // 添加
    userList.add(new User("小王",21,"男"));
    userList.add(new User("小张",18,"男"));
    userList.add(new User("小刘",19,"女"));
    return userList;
    }
  3. 新建ajax2.html

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>ajax实现异步数据加载</title>
    <!-- jquery-->
    <script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script>
    $(function (){
    $("#btn").click(function (){
    // 如果这里报错可以这样写 ${pageContext.request.contextPath}/ajax2
    $.post("/ajax2",function (data) {
    // console.log(data)
    let 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="ajax加载数据" id="btn" >
    <table>
    <thead>
    <tr>
    <th>姓名</th>
    <th>年龄</th>
    <th>性别</th>
    </tr>
    </thead>
    <tbody id="content">
    <!-- 数据加载-->
    </tbody>
    </table>
    </body>
    </html>
  4. 运行测试

    image-20220617181853685

Ajax验证用户名体验

  1. 新建login.html页面

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
    <title>使用ajax登录验证</title>
    <!-- jquery-->
    <script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script>
    function n1(){
    $.ajax({
    url:"${pageContext.request.contextPath}/ajax3",
    data:{"name":$("#name").val()},
    success:function (data){
    // console.log(data)
    if(data.toString() === 'ok'){
    $("#uinfo").css("color","green")
    }else{
    $("#uinfo").css("color","red")
    }
    $("#uinfo").html(data)
    }
    })
    }
    function n2(){
    $.ajax({
    url:"${pageContext.request.contextPath}/ajax3",
    data:{"pwd":$("#pwd").val()},
    success:function (data){
    // console.log(data)
    if(data.toString() === 'ok'){
    $("#pinfo").css("color","green")
    }else{
    $("#pinfo").css("color","red")
    }
    $("#pinfo").html(data)
    }
    })
    }
    </script>
    </head>
    <body>
    <form action="" method="">
    账号:<input type="text" id="name" onblur="n1()"><span id="uinfo"></span><br>
    密码:<input type="password" id="pwd" onblur="n2()"><span id="pinfo"></span><br>
    <input type="submit" value="登录">
    </form>
    </body>
    </html>
  2. 编写AjaxController

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    // 登录验证
    @RequestMapping("/ajax3")
    public String ajax3(String name,String pwd){
    String msg= "";
    if(name!=null){
    if("admin".equals(name)){
    msg = "ok";
    }else{
    msg = "账号有误";
    }
    }
    if(pwd!=null){
    if("123".equals(pwd)){
    msg = "ok";
    }else{
    msg = "密码有误";
    }
    }
    return msg;
    }
  3. applicationContext.xml中配置解决json乱码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    <!--    1.注解驱动 解决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>
  4. 运行测试

    image-20220617185231064

拦截器是什么

概述

SpringMVC的拦截器类似与Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。开发者也可以自定义拦截器来实现特定的功能。

过滤器与拦截器的区别:拦截器是AOP思想和具体应用。

过滤器

  • servlet规范中的一部分,任何JavaWeb工程都可以使用
  • url-pattern中配置了/*,可以对所有要访问的资源进行拦截

拦截器

  • 拦截器属于SpringMVC
  • 拦截器只会拦截访问的控制器方法,如果访问的是jsp/html/css/image/js不会进行拦截

自定义拦截器

想要自定义拦截器,必须实现HandlerInterceptor接口

  1. 新建module,springmvc-08-Interceptor,添加web支持

  2. 配置web.xml和applicationContext.xml(和之前的相同,这里就不在赘述了)

  3. 新建TestController.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    package com.jokerdig.controller;

    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;

    /**
    * @author Joker大雄
    * @data 2022/6/17 - 19:21
    **/
    @RestController
    public class TestController {
    @GetMapping("/t1")
    public String test(){
    System.out.println("=======TestController===");
    return "ok";
    }
    }
  4. 编写一个拦截器

    新建MyInterceptor.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    package com.jokerdig.config;

    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;

    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    /**
    * @author Joker大雄
    * @data 2022/6/17 - 19:15
    **/
    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("处理后===============");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    System.out.println("清理===============");
    }
    }
  5. applicationContext.xml配置拦截器

    1
    2
    3
    4
    5
    6
    7
    <!--    拦截器配置-->
    <mvc:interceptors>
    <mvc:interceptor>
    <mvc:mapping path="/**"/>
    <bean class="com.jokerdig.config.MyInterceptor"/>
    </mvc:interceptor>
    </mvc:interceptors>
  6. 运行测试

    运行:localhost:8080/t1

    1
    2
    3
    4
    5
    // 控制台打印
    处理前===============
    =======TestController===
    处理后===============
    清理===============