SpringMVC-相关 Ajax及拦截器

Posted jiaxing-java

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringMVC-相关 Ajax及拦截器相关的知识,希望对你有一定的参考价值。

Ajax

异步的JavaScript和XML

Ajax初体验

1、配置页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>

    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></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>

  <p>用户名:</p>
  <%--失去焦点的时候,发起一个请求到后台--%>
  <input type="text" id="username" onblur="a()"/>

  </body>
</html>

2、配置Controller类

@RequestMapping("t1")
public String test()
    return "hello";


@RequestMapping("a1")
public void a1(String name, HttpServletResponse resp) throws IOException 
    System.out.println("a1:param=>" + name);
    if("kuangshen".equals(name))
        resp.getWriter().print("true");
    else
        resp.getWriter().print("false");
    

Ajax异步加载数据

1、配置页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>

    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>

    <script>
        $(function ()
            $("#btn").click(function ()
                /*
                $.post(url,param[可以省略],success
                */
                $.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>

2、配置Controller类

@RequestMapping("a2")
public List<User> a2()
    List<User> userList = new ArrayList<>();
    // 添加数据
    userList.add(new User("狂神说Java",1,"男"));
    userList.add(new User("狂神说前端",1,"女"));
    userList.add(new User("狂神说运维",1,"男"));

    return userList;

Ajax验证用户名

1、配置页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Title</title>

  <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></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:"pwd":$("#pwd").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>

2、配置Controller类

package com.kuang.controller;

import com.kuang.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class AjaxController 

    @RequestMapping("t1")
    public String test()
        return "hello";
    

    @RequestMapping("a1")
    public void a1(String name, HttpServletResponse resp) throws IOException 
        System.out.println("a1:param=>" + name);
        if("kuangshen".equals(name))
            resp.getWriter().print("true");
        else
            resp.getWriter().print("false");
        
    

    @RequestMapping("a2")
    public List<User> a2()
        List<User> userList = new ArrayList<>();
        // 添加数据
        userList.add(new User("狂神说Java",1,"男"));
        userList.add(new User("狂神说前端",1,"女"));
        userList.add(new User("狂神说运维",1,"男"));

        return userList;
    

    @RequestMapping("a3")
    public String a3(String name,String pwd)
        // admin 这些数据应该在数据库中查
        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;
    


拦截器

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>

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

2、配置applicationContext.mxl文件

<?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
        https://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">

    <mvc:default-servlet-handler/>
    <context:component-scan base-package="com.kuang.controller"/>
    <!--配置注解驱动(含乱码处理)-->
    <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>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
    <mvc:interceptors>
        <mvc:interceptor>
            <!--包括这个请求下面的所有的请求-->
            <mvc:mapping path="/**"/>
            <bean class="com.kuang.cofig.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

</beans>

3、配置Controller类

@RestController
public class TestController 

    @GetMapping("t1")
    public String test()
        System.out.println("TestController == > test()执行了");
        return "OK";
    


4、配置拦截器

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 false;
    

    @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("---------清理---------");
    

以上是关于SpringMVC-相关 Ajax及拦截器的主要内容,如果未能解决你的问题,请参考以下文章

SpringMVC之数据传递三Ajax与Controller交互

SpringMVC案例3----spring3.0项目拦截器ajax文件上传应用

springMVC工作流程

[SSM]详解 SpringMVC 中的拦截器异常处理器与执行流程及两种配置方式

SpringBoot相关配置

SpringMVC:理解SpringMVC相关概念