您好,欢迎访问代理记账网站
移动应用 微信公众号 联系我们

咨询热线 -

电话 15988168939

联系客服
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

SpringMVC的学习

SpringMVC

1、初识SpringMVC

SpringMVC是一个基于Java实现MVC模式的一种轻量级架构。

1.1 主要特点

  • 轻量级,高效
  • 依靠请求响应
  • 与Spring兼容性好
  • 实现功能强大,可以整合其他风格设计(Restful)

1.2 基本原理

在这里插入图片描述

DispatcherServlet :前置控制器,在整个SpringMVC中,作为中央控制角色。

HandlerMapping:处理器映射,根据传递过来的请求(url)映射相应handler。

HandLerExecution:具体的handler,根据映射关系,查找具体的handler。

HandlerAdapter:处理器适配器,根据规则执行handler。

ViewResolver:视图解析器,用来解析相应的视图。

执行流程:

  1. 当用户发起请求时,会传递一个请求(URL)到DispatcherServlet进行解析请求
  2. DispatcherServlet携带所请求的控制器名称(/hello)到HandlerMapping,HandlerMapping根据名称去找到相对应的处理器
  3. HandlerExecution去接收查找到的handler,
  4. 并且将所接收到的hello请求名称传递给DispatcherServlet
  5. HandlerAdapter表示处理器适配器,就是指根据handler的请求,去适配相应的handler执行
  6. handler使得对应的Controller执行
  7. Controller将执行得到的信息返回给HandlerAdapter,也就是ModelAndView(模型和视图)
  8. HandlerAdapter将得到信息传递给DispatcherServlet
  9. DispatcherServlet 调用ViewResolver(视图解析器)来解析传递过来的视图名
  10. ViewResolver将结果传递给DispatcherServlet
  11. DispatcherServlet 根据传递过来的信息,调用具体的视图
  12. 显示到界面

1.3 一个简单的demo

在这里插入图片描述

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

    <!--配置DispatcherServlet  -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--绑定Spring的核心配置文件-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>

        <!--        启动级别,服务器刚启动,就执行-->
        <load-on-startup>1</load-on-startup>
    </servlet>


    <!--
            /   指匹配所有的请求
           /*   匹配所有请求,包括jsp页面   会造成  index.jsp.jsp~~~~~  -->
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

springmvc-servlet.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--处理器映射器-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean>
    <!--处理器适配器-->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean>
    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>


    <bean id="/test" class="com.myl.TestController"></bean>


</beans>

test.jsp

<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/3/27
  Time: 15:18
  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>
${msg}
</body>
</html>

TestController.java

package com.myl;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import sun.awt.ModalityEvent;
import sun.security.provider.MD2;

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

/**
 * @ClassName: TestController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/27  15:31
 */
public class TestController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        ModelAndView mv = new ModelAndView();

        //编写业务代码,逻辑处理
        String result = "Hello SpringMvc";
        mv.addObject("msg", result);

        // 视图跳转
        mv.setViewName("test");


        return mv;
    }
}

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.myl</groupId>
    <artifactId>SpringMVC</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>SpringMVC-HelloWorld</module>
    </modules>

    <dependencies>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.5</version>
        </dependency>


        <!--        添加Servlet依赖包-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

    </dependencies>



</project>

1.4 使用注解开发

在这里插入图片描述

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


    <!--    配置DispatcherServlet :注册Servlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.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>
</web-app>

springmvc-servlet.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
        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">

    <!--配置扫描包,包下的注解生效-->
    <context:component-scan base-package="com.myl.controller"/>
    <!--使MVC 不去处理静态资源(例如CSS、js)-->
    <mvc:default-servlet-handler/>
    <!--支持MVC注解驱动,使得handler和adapter完成配置-->
    <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>

TestController.java

package com.myl.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


/**
 * @ClassName: TestController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/27  16:25
 */
@Controller
// @RequestMapping("/HelloController")   表示  localhost:8080/ /HelloController/test
public class TestController {


    //设置请求的servlet
    @RequestMapping("/test")
    public String hello(Model model){

        //模型中添加数据,发给视图
        model.addAttribute("msg","Hello mvc");

        //设置想要访问的视图   WEB-INF/jsp/test.jsp
        return "test";
    }
}

2、Restful风格

package com.myl.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

/**
 * @ClassName: Restful
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/27  20:16
 */

@Controller
public class RestfulController {


    //之前使用  localhost:8080/add/a=?&b=?
    //现在      localhost:8080/add/1/2
    //常用注解   @RequestMapping @GetMapping  @PostMapping

    
    @GetMapping("/add/{a}/{b}")
    public String test1(@PathVariable int a,@PathVariable int b, Model model){
        int result = a+b;
        model.addAttribute("msg",result);

        return "test";
    }
}

3、重定向和请求转发

3.1 没有视图解析器情况下Servlet

package com.myl.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

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

/**
 * @ClassName: ServletController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/29  20:45
 */
@Controller
public class ServletController {

    @RequestMapping("/test/t1")
    public String test1(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        System.out.println(session.getId());

       // return "test";
        return "/index.jsp";

    }


    //是在没有视图解析器情况下测试

    @RequestMapping("/test/t2")
    public String test2(Model model){
        model.addAttribute("msg","aa");

        //默认的是  请求转发
//        return "/index.jsp";
        //重定向  :地址栏会显示参数  , 不能访问WEB-INF下的东西。
        //       return "redirect:/index.jsp";
        return "redirect:/test/t1";

    }
}

4、前端传递参数

package com.myl.controller;

import com.myl.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


/**
 * @ClassName: UserController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/29  21:30
 */

@Controller
@RequestMapping("/user")
public class UserController {


    //路径:localhost:8080/user/t1?name=myl
    @GetMapping("/t1")
    public String test1(@RequestParam("username") String name, Model model){
        //从前端接收到的参数
        System.out.println("前端接收到的参数:"+name);
        //返回结果传递给前端
        model.addAttribute("msg",name);
        //跳转视图
        return "test";
    }


    /*
        接收到的是一个对象,参数直接使用对象即可(对象有get和set方法和构造方法)
        User的属性和参数名需要一致,否则是null
     */

    @GetMapping("/t2")
    public String test2(User user){
        System.out.println("前端接收一个对象:"+user);

        return "test";
    }
}

5、乱码问题处理

<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/3/30
  Time: 10:41
  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="/encoding/t3">
    <input type="text" name="name">
    <input type="submit">
</form>
</body>
</html>

web.xml

 <!--配置Springmvc自带的乱码处理-->
    <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>

test.java

@Controller
@RequestMapping("/encoding")
public class EncodingController {
    @RequestMapping("/t3")
    public String test3(String name, Model model){
        model.addAttribute("msg",name);

        return "test";
    }
}

解决失败:自定义过滤器,进行配置。

package com.kuang.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

/**
* 解决get和post请求 全部乱码的过滤器
*/
public class GenericEncodingFilter implements Filter {

   @Override
   public void destroy() {
  }

   @Override
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
       //处理response的字符编码
       HttpServletResponse myResponse=(HttpServletResponse) response;
       myResponse.setContentType("text/html;charset=UTF-8");

       // 转型为与协议相关对象
       HttpServletRequest httpServletRequest = (HttpServletRequest) request;
       // 对request包装增强
       HttpServletRequest myrequest = new MyRequest(httpServletRequest);
       chain.doFilter(myrequest, response);
  }

   @Override
   public void init(FilterConfig filterConfig) throws ServletException {
  }

}

//自定义request对象,HttpServletRequest的包装类
class MyRequest extends HttpServletRequestWrapper {

   private HttpServletRequest request;
   //是否编码的标记
   private boolean hasEncode;
   //定义一个可以传入HttpServletRequest对象的构造函数,以便对其进行装饰
   public MyRequest(HttpServletRequest request) {
       super(request);// super必须写
       this.request = request;
  }

   // 对需要增强方法 进行覆盖
   @Override
   public Map getParameterMap() {
       // 先获得请求方式
       String method = request.getMethod();
       if (method.equalsIgnoreCase("post")) {
           // post请求
           try {
               // 处理post乱码
               request.setCharacterEncoding("utf-8");
               return request.getParameterMap();
          } catch (UnsupportedEncodingException e) {
               e.printStackTrace();
          }
      } else if (method.equalsIgnoreCase("get")) {
           // get请求
           Map<String, String[]> parameterMap = request.getParameterMap();
           if (!hasEncode) { // 确保get手动编码逻辑只运行一次
               for (String parameterName : parameterMap.keySet()) {
                   String[] values = parameterMap.get(parameterName);
                   if (values != null) {
                       for (int i = 0; i < values.length; i++) {
                           try {
                               // 处理get乱码
                               values[i] = new String(values[i]
                                      .getBytes("ISO-8859-1"), "utf-8");
                          } catch (UnsupportedEncodingException e) {
                               e.printStackTrace();
                          }
                      }
                  }
              }
               hasEncode = true;
          }
           return parameterMap;
      }
       return super.getParameterMap();
  }

   //取一个值
   @Override
   public String getParameter(String name) {
       Map<String, String[]> parameterMap = getParameterMap();
       String[] values = parameterMap.get(name);
       if (values == null) {
           return null;
      }
       return values[0]; // 取回参数的第一个值
  }

   //取所有值
   @Override
   public String[] getParameterValues(String name) {
       Map<String, String[]> parameterMap = getParameterMap();
       String[] values = parameterMap.get(name);
       return values;
  }
}

6、JSON

6.1 使用第三方工具 Jackson

pom.xml

  <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.2</version>
        </dependency>

springmvc-servlet.xml

<!--    解决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>

UserController.java

package com.myl.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.myl.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * @ClassName: UserController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/30  11:18
 */
//@RestController   类中所有的方法都将返回字符串,不走视图解析器
@Controller
public class UserController {

    @RequestMapping("/j1")
    //ResponseBody 不走视图解析器,直接返回一个字符串,配合@Controller使用
    @ResponseBody
    public String json1() throws JsonProcessingException {
        //jackson的对象
        ObjectMapper mapper = new ObjectMapper();
        User user = new User(1,"孟哈哈",18);
        //调用方法将value转化为String
        String users = mapper.writeValueAsString(user);

        return users;
    }
}


    @RequestMapping("/j2")
    @ResponseBody
    public String test1() throws JsonProcessingException {

        Date date = new Date();
        return JSONutils.getJson(date,"yyy-MM-dd HH:mm:ss");
    }

工具类:

package com.myl.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.text.SimpleDateFormat;

/**
 * @ClassName: JSONutils
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/30  16:47
 */
public class JSONutils {

    public static String getJSON(Object o ) throws JsonProcessingException {
        return getJson(o,"yyy-MM-dd HH:mm:ss");
    }



    public static String getJson(Object o,String dataFormat) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        //关闭默认时间戳显示方式,从1970年到现在所经历的毫秒数
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dataFormat);
        //将自定义日期格式set进去
        mapper.setDateFormat(simpleDateFormat);

        try {
            return mapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

6.2 使用第三方工具FastJson

   <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>

 @RequestMapping("/j3")
    @ResponseBody
    public String test2() throws JsonProcessingException {


        //
        List<User> userList = new ArrayList<>();

        User user1 = new User(1,"lala",3);
        User user2 = new User(2,"lala",4);
        User user3 = new User(3,"lala",5);
        User user4 = new User(4,"lala",6);

        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        //使用alibaba的FastJson包
        return JSON.toJSONString(userList);
    }

7、Ajax简单使用

7.1、使用jquery的Ajax

jQuery Ajax本质就是 XMLHttpRequest,进行了封装,方便调用!

jQuery.ajax(...)
     部分参数:
           url:请求地址
           type:请求方式,GETPOST1.9.0之后用method)
       headers:请求头
           data:要发送的数据
   contentType:即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
         async:是否异步
       timeout:设置请求超时时间(毫秒)
     beforeSend:发送请求前执行的函数(全局)
       complete:完成之后执行的回调函数(全局)
       success:成功之后执行的回调函数(全局)
         error:失败之后执行的回调函数(全局)
       accepts:通过请求头发送给服务器,告诉服务器当前客户端可接受的数据类型
       dataType:将服务器端返回的数据转换成指定类型
         "xml": 将服务器端返回的内容转换成xml格式
         "text": 将服务器端返回的内容转换成普通文本格式
         "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
       "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
         "json": 将服务器端返回的内容转换成相应的JavaScript对象
       "jsonp": JSONP 格式使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数

简单小demo:测试失去焦点发起请求

jquery.ajax

jquery-3.6.0.js
<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/3/31
  Time: 19:56
  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}/static/js/jquery-3.6.0.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);
            },
            error:function (data) {
              console.log("data"+data);
              console.log("status"+status);
            }
          })
      }
    </script>
  </head>
  <body>


  用户名<input type="text" id="username" οnblur="a()">

  </body>
</html>

package com.myl.controller;

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

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName: AjaxController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/31  20:00
 */
@RestController
public class AjaxController {

    @RequestMapping("/t1")
    public String test(){

        return "hello";
    }

    @RequestMapping("/a1")
    public void a1(String name, HttpServletResponse response) throws IOException {
        //从前端接收data中 name属性的值
        System.out.println("name"+name);
        
        //向前端发送响应消息
        if("meyolo".equals(name)){
            response.getWriter().print("true");
        }else{
            response.getWriter().print("false");
        }
    }
}

7.2、Ajax异步加载数据

package com.myl.pojo;

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

/**
 * @ClassName: User
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/4/2  15:32
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
    private String sex;
}

 @RequestMapping("/a2")
    public List<User> a2(){
        List<User> userList = new ArrayList<>();
        userList.add(new User("孟哈哈",18,"男"));
        userList.add(new User("孟小二",19,"男"));
        userList.add(new User("孟十一",20,"男"));

        return userList;
<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/4/2
  Time: 15:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>信息</title>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>
    <script>

       $(function () {
           /*添加点击事件*/
           $("#btn").click(function () {
               /*使用Ajax获取数据
               * $>post(url  param[可以省略]  success)
               * */
              $.post("${pageContext.request.contextPath}/a2",function (data) {
                    console.log(data);
                    //进行html节点拼接
                    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>"
                    }
                    /*嵌入到html中*/
                    $("#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>

7.3、Ajax实现异步登录

package com.myl.controller;

import com.myl.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;

/**
 * @ClassName: AjaxController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/3/31  20:00
 */
@RestController
public class AjaxController {

    @RequestMapping("/t1")
    public String test(){

        return "hello";
    }

    @RequestMapping("/a1")
    public void a1(String name, HttpServletResponse response) throws IOException {
        //从前端接收data中 name属性的值
        System.out.println("name"+name);

        //向前端发送响应消息
        if("meyolo".equals(name)){
            response.getWriter().print("true");
        }else{
            response.getWriter().print("false");
        }
    }

    @RequestMapping("/a2")
    public List<User> a2(){
        List<User> userList = new ArrayList<>();
        userList.add(new User("孟哈哈",18,"男"));
        userList.add(new User("孟小二",19,"男"));
        userList.add(new User("孟十一",20,"男"));

        return userList;

    }

    @RequestMapping("/a3")
    public String a3(String username,String pwd){
        String msg ="";
        if(username!=null){
            if("meyolo".equals(username)){
                msg="用户名正确";
            }else{
                msg="用户名错误";
            }
        }
        if(pwd!=null){
            if("12345".equals(pwd)){
                msg="密码正确";
            }else{
                msg="密码错误";
            }
        }
        return msg;

    }
}

<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/4/2
  Time: 16:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
    <script src="${pageContext.request.contextPath}/static/js/jquery-3.6.0.js"></script>

    <script>
        function a1() {
            //使用Ajax异步提交数据
            $.post({
                url: "${pageContext.request.contextPath}/a3",
                data: {"username": $("#username").val()},    //向后端传递data中username的值
                success: function (data) {        //从后端接收data
                    if (data.toString() === "用户名正确") {
                        $("#sp").css("color","green");
                    }else{
                        $("#sp").css("color","red");
                    }
                    //嵌入到span中
                    $("#sp").html(data);
                }
            })
        }

        function a2() {
            $.post({
                url: "${pageContext.request.contextPath}/a3",
                data: {"pwd": $("#pwd").val()},
                success: function (data) {
                    if (data.toString() === "密码正确") {
                        $("#spw").css("color","green");
                    }else{
                        $("#spw").css("color","red");
                    }
                    $("#spw").html(data);
                }
            })
        }
    </script>
</head>
<body>


用户名<input type="text" id="username" οnblur="a1()">
<span id="sp"></span>
密码<input type="text" id="pwd" οnblur="a2()">
<span id="spw"></span>
</body>
</html>

注意处理乱码问题

    <!--    解决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>

8、拦截器

拦截器是基于AOP思想的具体实现

自定义拦截器

applicationContext.xml

 <!--注册拦截器-->
    <mvc:interceptors>
        <mvc:interceptor>
            <!--表示拦截user下的所有请求-->
            <mvc:mapping path="/user/**"/>
            <bean class="com.myl.InterCeptor.LoginInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

拦截器实现类

package com.myl.InterCeptor;

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

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

/**
 * @ClassName: LoginInterceptor
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/4/2  17:44
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();

        //   判断是否包含goLogin  请求
        if(request.getRequestURI().contains("goLogin")){
            return true;
        }

        //  判断是否包含 login 请求,第一次登录
        if(request.getRequestURI().contains("login")){
            return true;
        }

        //如果session不为空,直接跳转
        if(session.getAttribute("user")!=null){
            return true;
        }
        //否则去登录
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
        return false;
    }
}

Controller类

package com.myl.controller;

import com.myl.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @ClassName: LoginController
 * @Description: TODO
 * @author: meyolo
 * @date: 2021/4/2  17:40
 */
@Controller
@RequestMapping("/user")
public class LoginController {

    //WEB-INF下的页面是不能直接访问的,只能通过Controller或者Servlet访问
    @RequestMapping("/main")
    public String main() {
        return "main";
    }

    //去登录页面
    @RequestMapping("/goLogin")
    public String goLogin() {
        return "login";
    }


    //登录
    @RequestMapping("/login")
    public String login(HttpServletRequest request, User user, Model model) {
        System.out.println("接收到的参数"+user);
        request.getSession().setAttribute("user", user);
        model.addAttribute("msg", user.getUsername());
        return "main";
    }

    //注销
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "main";
    }


}

index.jsp

<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/4/2
  Time: 17:35
  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>
  <a href="${pageContext.request.contextPath}/user/goLogin">登录页面</a>
  <a href="${pageContext.request.contextPath}/user/main">首页</a>
  </body>
</html>

main.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/4/2
  Time: 17:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
</head>
<body>

<h1>首页</h1>
    ${msg} <a href="/user/logout">注销</a>

</body>
</html>

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/4/2
  Time: 17:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<form action="/user/login" method="post">
    用户名<input type="text" name="username">
    密码<input type="text" name="password">
    <input type="submit" value="提交">
</form>

</body>
</html>

A.
User: 10254
Date: 2021/4/2
Time: 17:35
To change this template use File | Settings | File Templates.
–%>
<%@ page contentType=“text/html;charset=UTF-8” language=“java” %>

$Title$ 登录页面 首页

main.jsp

```jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/4/2
  Time: 17:35
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>首页</title>
</head>
<body>

<h1>首页</h1>
    ${msg} <a href="/user/logout">注销</a>

</body>
</html>

login.jsp

<%--
  Created by IntelliJ IDEA.
  User: 10254
  Date: 2021/4/2
  Time: 17:36
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录</title>
</head>
<body>
<form action="/user/login" method="post">
    用户名<input type="text" name="username">
    密码<input type="text" name="password">
    <input type="submit" value="提交">
</form>

</body>
</html>


分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进