关于Ajax的简单用法

我们首先要导入jq的包,这里可以从官网下载,引入js文件会有代码提示。也可以使用在线的cdn,这样会更加方便。

经过实验在jq2.0时不支持$.post等方法,必须使用$.ajax在type中定义post还是get。在3.0中可以写$.post但是不支持写type。

1. 普通写法测试

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>Ajax</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div>
  <input type="text" id="username" onblur="a()">
</div>
<script>
  function a() {
    $.ajax({
      type:"post",
      url:"${pageContext.request.contextPath}/a1",
      data:{"user":$("#username").val()},
      success:function (data) {
        alert(data);
      }
    });
  }
</script>
</body>
</html>

这里我们可以看到,传入后端的是data中的键,我们这里使用@RestController,我们的返回值就是前端接收的data值。

@RestController
public class AjaxController {
    @RequestMapping("/a1")
    public String test(String user){
        System.out.println(user);
        if ("a".equals(user)){
            return "hello";
        }else{
            return "false";
        }
    }
}

2.表单的刷新。

这里主要我们需要的是了解js中的字段拼接。还有.html方法

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Ajax</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>
<body>

<input type="button" id="btn" value="显示数据">
    <table>
        <thead>
            <tr>
                <th>id</th>
                <th>age</th>
                <th>name</th>
            </tr>
        </thead>
        <tbody id="content">

        </tbody>
    </table>
    <script>

            $("#btn").click(function () {
                $.ajax({
                    url:"/a2",
                    success:function (data) {
                        var html = "";

                        for (let i=0;i<data.length;i++){
                            html += "<tr>"+
                                    "<td>"+data[i].id+"</td>"+
                                    "<td>"+data[i].age+"</td>"+
                                    "<td>"+data[i].name+"</td>"+
                                    "</tr>"
                        }
                        $("#content").html(html);
                    }
                })
            })

    </script>
</body>
</html>

直接返回一个list。

package com.controller;

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

import java.util.ArrayList;
import java.util.List;

@RestController
public class AjaxController {
    @RequestMapping("/a2")
    public List<User> test2(){
        List<User> users = new ArrayList<User>();
        users.add(new User(1,1,"wp"));
        users.add(new User(2,2,"ty"));
        users.add(new User(3,3,"ja"));
        return users;
    }
}

3. 数据匹配

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Form</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

</head>
<body>

<input name="username" id="username" type="text" onblur="a1()"/>
<span id="user"></span><br>
<input name="password" id="password" type="password" onblur="a2()"/>
<span id="pwd"></span>

<script>
    function a1() {
        $.post({
            url:"${pageContext.request.contextPath}/a3",
            data:{"username":$("#username").val()},
            success: function (data) {
                if (data.toString()==='ok'){
                    $("#user").css("color","green");
                }
                $("#user").html(data);
            }
        })
    }
    function a2() {
        $.post({
            url:"${pageContext.request.contextPath}/a3",
            data:{"password":$("#password").val()},
            success: function (data) {
                if (data.toString()==='ok'){
                    $("#pwd").css("color","green");
                }
                $("#pwd").html(data);
            }
        })
    }
</script>
</body>
</html>

java


@RestController
public class AjaxController {
    @RequestMapping("/a3")
    public String a3(String username,String password){
        String msg = "";
        if(username!=null){
            if ("admin".equals(username)){
                msg = "用户名已存在";
            }else {
                msg = "ok";
            }
        }
        if(password!=null){
            if ("122356".equals(password)){
                msg = "ok";
            }else {
                msg = "false";
            }
        }
        return msg;
    }
}

Interceptor

mvc拦截器,功能比过滤器更加强大方便。

原来:

------>|

加了拦截器

----}--->|

设置访问规则,拦截未有权限的访问。

讲到mvc拦截器,我们要做的事情就是,使用它自带的拦截器接口。这是一个测试,return true的意思就是放行。

public class MyInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("============拦截前==========");
        return true;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        System.out.println("============拦截后==========");
    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("============清理==========");
    }
}

然后再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.controller"/>

    <!--    不处理静态资源-->
    <mvc:default-servlet-handler/>

    <mvc:annotation-driven/>
    <!--springmvc 统一解决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>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!--        前缀,后缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
    
<!--    拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.config.MyInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

</beans>

来写一个controller

package com.controller;

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

@RestController
public class TestController {

    @RequestMapping("/a")
    public String test01(){
        System.out.println("======Start====");
        return "OK";
    }
}

============拦截前==========
======Start====
============拦截后==========
============清理==========

我们可以看出来拦截器配置成功。

接下来我们来写一个登录实验。将登陆的用户放在session中,通过是否有session判断是否放行,当然登陆页面和登陆跳转页面不能拦截,把尚未登陆没有权限的用户直接跳转到登陆页面。

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        HttpSession session = httpServletRequest.getSession();
        if (session.getAttribute("user")!=null){
            return true;
        }
        if (httpServletRequest.getRequestURI().contains("toLogin")){
            return true;
        }
        if (httpServletRequest.getRequestURI().contains("login")){
            return true;
        }
        httpServletRequest.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(httpServletRequest,httpServletResponse);
        return false;
    }

    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

我们把这个拦截器也添加到我们的配置文件中。

<?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.controller"/>

    <!--    不处理静态资源-->
    <mvc:default-servlet-handler/>

    <mvc:annotation-driven/>
    <!--springmvc 统一解决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>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!--        前缀,后缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
    
<!--    拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.config.MyInterceptor"/>
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/user/**"/>
            <bean class="com.config.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

</beans>

写一个controller,添加注销功能。

@Controller
@RequestMapping("/user")
public class LoginController {
    @RequestMapping("/toIndex")
    public String toIndex(){
        return "main";
    }
    @GetMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
    @PostMapping("/login")
    public String Login(HttpSession session, String name, String password){
        session.setAttribute("user",name);
        return "main";
    }
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "main";
    }
}

我们把首页做成一个链接跳转,这样就会方便许多。

<%--
  Created by IntelliJ IDEA.
  User: quanwu
  Date: 2020/7/30
  Time: 3:07 下午
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  <h1><a href="${pageContext.request.contextPath}/user/toIndex">去首页</a></h1>
  <h1><a href="${pageContext.request.contextPath}/user/toLogin">去登录页</a></h1>
  </body>
</html>

登录页面:

<%--
  Created by IntelliJ IDEA.
  User: quanwu
  Date: 2020/7/30
  Time: 3:34 下午
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/login" method="post">
    用户名:<input type="text" name="name"><br>
        密码:<input type="password" name="password">
    <input type="submit">
</form>
</body>
</html>

登录成功页面:

<%--
  Created by IntelliJ IDEA.
  User: quanwu
  Date: 2020/7/30
  Time: 3:34 下午
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>main</title>
</head>
<body>
<h1>hello world</h1>
<a href="${pageContext.request.contextPath}/user/logout">注销</a>
</body>
</html>

这样mvc就告一段落了,可能还有下载上传啥的,不想看了,等以后项目用到再看。