springmvc

SpringMVC

简介

  • SpringMVC是一种架构模式,一种软件设计规范,降低视图与业务逻辑耦合性

  • Model Dao Service层,连接数据库,处理数据

    javabean

  • View 前端展示

    jsp

  • Controller servlet处理请求,接受前端数据交给model处理,然后控制跳转对应view

    servlet

    image-20250306154836489

回顾Servlet

实现servlet接口的类都是servlet

HttpServlet的祖先类实现了servlet 接口

  1. 导maven依赖

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>6.2.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    
  2. class HelloServlet继承HttpServlet 重写 get post

    获取前端参数,根据参数存值到session 的 msg 中

    请求转发getRequestDispatcher到/WEB-INF/jsp/test.jsp

    package com.zhm.servlet;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    public class HelloServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            // 1.获取前端参数
            String method = req.getParameter("method");
            if (method.equals("add")){
                // 一个名为 msg 的属性存储在会话(HttpSession)中,并将其值设置为 “执行了add方法”
                req.getSession().setAttribute("msg","执行了add方法");
            }
            if (method.equals("delete")){
                req.getSession().setAttribute("msg","执行了delete方法");
            }
            // 2.调用应用层
            // 3.视图转发或重定向
            req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  3. 注册servlet web.xml

    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.zhm.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>
    
  4. test.jsp 显示session结果

    image-20250306182753813

    web-inf下面为隐藏目录不能直接访问,web下面为公开目录

    ${msg}获取session的msg的值,显示在页面上

    <%--
      Created by IntelliJ IDEA.
      User: zhm
      Date: 2025/3/6
      Time: 16:43
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%--web-inf下面是保密页面,不能直接访问--%>
    <html>
    <head>
    <title>xax</title>
    </head>
    <body>
    ${msg}
    </body>
    </html>
    
  5. form.jsp 提交method给servlet处理

    action="/hello" 代表点提交后跳转

    method="get" 代表用get处理请求

    input type="text" name="method" 代表输出的值对应键为method 将值传入servlet

    <%--
      Created by IntelliJ IDEA.
      User: zhm
      Date: 2025/3/6
      Time: 16:46
      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="/hello" method="get">
        <input type="text" name="method">
        <input type="submit">
    </form>
    </body>
    </html>
    
  • 流程
    1. 浏览器访问 form.jsp
    2. 填对应 method对应值 提交
    3. action="/hello" 跳转到/hello 并 将method 一起提交到/hello
    4. 根据servlet绑定的类 找到/hello对应的类,再根据表单提交方式get调用doget方法(doservice)处理请求
    5. 方法获取前端传入method,进行判断匹配,根据结果传入session中,msg的值
    6. 跳转到test.jsp
    7. test.jsp ${msg} 从session中获取msg的值 返回到前端浏览器页面

为什么要学

  1. 简单高效
  2. 基于请求响应的轻量级mvc框架(底层servlet)
  3. 与spring无缝
  4. 用的多

HelloSpring

  1. 导入mvc依赖

    版本号6以下,不如后面包位置不对

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.3.39</version>
    </dependency>
    
  2. web.xml配置所有servlet的前置调度员

    请求通过调度员来分配对应servlet

    <?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">
        <!--1.注册DispatcherServlet-->
    <!--所有servlet前的一层,过滤层-->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc-servlet.xml</param-value>
            </init-param>
            <!--启动级别-1-->
            <load-on-startup>1</load-on-startup>
        </servlet>
        <!--/ 匹配所有的请求;(不包括.jsp)-->
        <!--/* 匹配所有的请求;(包括.jsp)-->
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    </web-app>
    
  3. resources创建

    springmvc-servlet.xml spring配置文件

    注册匹配器类,视图解析器(前缀后缀)

    <?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
            http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--看有没有可以匹配到的bean-->
        <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
        <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
    
        <!--视图解析器:DispatcherServlet给他的ModelAndView-->
        <!--加前缀后缀-->
        <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="/hello" class="com.zhm.controller.HelloController"/>
    
    </beans>
    
  4. 写处理请求的类实现controller接口

    package com.zhm.controller;
    
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.Controller;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class HelloController implements Controller {
        @Override
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
            ModelAndView mav = new ModelAndView();
            mav.addObject("msg","wcnm");
            mav.setViewName("hello");
            return mav;
        }
    }
    
  5. 注册bean

    <bean id="/hello" class="com.zhm.controller.HelloController"/>
    
  6. 写jsp页面

    <%--
      Created by IntelliJ IDEA.
      User: zhm
      Date: 2025/3/7
      Time: 13: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>
    ${msg}
    </body>
    </html>
    

流程

  1. 浏览器请求 /hello
  2. web.xml servlet调度员 找到关联的springmvc-servlet.xml
  3. 匹配器 找到 匹配的bean 对应的class
  4. 处理请求 转发存值
  5. 把请求路径视图解析加前后缀,找到jsp,servlet调度员获取数据,数据model交给view解析
  6. view 返回渲染好的界面给调度员
  7. 调度员给浏览器返回界面
  • 主要三个大块

    1. 请求到前端控制器,适配请求,找到对应bean,返回信息到前端控制器
    2. 前端控制器找到bean对应的类处理请求,调用controller返回数据到前端控制器
    3. 前端控制器渲染数据到view,view返回渲染后的界面到前端控制器,前端控制器返回浏览器

    MVC最重要核心的是DispatcherServlet前端控制器,请求分发器

    image-20250307151217595

注意

404可能是项目没有springweb的lib jar包

项目结构,工件里面加上jar包

image-20250307144514546

注解实现

  1. 导spring-mvc依赖

  2. web.xml注册前端分发器DispatcherServlet

    <?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>
    <!--        绑定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>
    
  3. 配置springmvc-servlet.xml

    记得beans头配置约束

    <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.zhm.controller"/>
    <!--    mvc映射不处理静态资源 只处理servlet-->
        <mvc:default-servlet-handler/>
    <!--    支持mvc注解驱动,完成之前匹配器和适配器的功能-->
        <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>
    
  4. 编写处理类Controller

    使用注解

    @Controller 注册bean

    @RequestMapping("/hello") 代表访问路径

    model.addAttribute("msg","anno-study-h1");发给view的值

    return "hello" 交给视图解析器应该处理的string

    package com.zhm.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    @RequestMapping("/hello")
    public class HelloController {
    
        // 访问的地址 localhost:8080/项目名/类上注解父地址/方法名上子地址
        // /hello/h1
        @RequestMapping("/h1")
        public String hello(Model model){
            // 向模型添加值,给view渲染
            model.addAttribute("msg","anno-study-h1");
            // 交给视图解析器,解析完跳转的jsp
            return "hello";
        }
    
        @RequestMapping("/h2")
        public String hello2(Model model){
            // 向模型添加值,给view渲染
            model.addAttribute("msg","anno-study-h2");
            // 交给视图解析器,解析完跳转
            return "hello";
        }
    }
    

controller

  1. 实现controller接口,注册bean

    package com.zhm.controller;
    
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.Controller;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class HelloController implements Controller {
        @Override
        public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
            ModelAndView mv = new ModelAndView();
            mv.addObject("msg","class implements controller");
            mv.setViewName("test");
            return mv;
        }
    }
    
  2. 注解

    开启注解扫描

    package com.zhm.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class MyController {
        @RequestMapping("m1")
        public String test1(Model model){
            model.addAttribute("msg","anno controller test1");
            return "test";
        }
    
        @RequestMapping("m2")
        public String test2(Model model){
            model.addAttribute("msg","anno controller test2");
            return "test";
        }
    }
    
  3. springmvc-servlet配置

    <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.zhm.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>
    
        <bean id="/t" class="com.zhm.controller.HelloController"/>
    
    </beans>
    

RequestMapping

package com.zhm.controller;

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

@Controller
@RequestMapping("/admin")// 访问的父路径
public class MyController2 {

    @RequestMapping("/m2")// 访问的子路径
    public String test(Model model){
        model.addAttribute("msg","MyController2");
        return "test";// 跳转的路径
    }
}

RestFul风格

  • 一种网址风格 更简洁更有层次更安全

    /commit/1/2

    传参的参数前面+@PathVariable

    package com.zhm.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;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class RestFulController {
    
        // RestFul风格
        @RequestMapping("/commit/{a}/{b}")
        public String test(@PathVariable int a, @PathVariable int b, Model model){
            model.addAttribute("msg",a+b+"->test结果");
            return "test";
        }
        // get请求走这个
        @GetMapping("/commit/{a}/{b}")
        public String test2(@PathVariable int a, @PathVariable int b, Model model){
            model.addAttribute("msg",a+b+"->test get结果");
            return "test";
        }
    
        // post请求走这个
        @PostMapping("/commit/{a}/{b}")
        public String test3(@PathVariable int a, @PathVariable int b, Model model){
            model.addAttribute("msg",a+b+"->test post结果");
            return "test";
        }
    }
    

转发和重定向

  1. HttpServletResponse,HttpServletRequest 用这两个的对象
  2. 实现controller接口,modelandview实现转发
  3. 注解springmvc实现(重点)
  • 用注解springmvc实现

    视图解析器(如 InternalResourceViewResolver)不会解析带有 redirect: 或 forward: 前缀 或 值

    /WEB-INF/ 目录下的资源受服务器保护,不允许客户端直接访问。

    当你使用 redirect: 时,实际上是让浏览器重新发起一个请求,而浏览器无法直接访问受保护的 WEB-INF 目录。

    package com.zhm.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;
    
    @Controller
    public class ModelTest {
        @RequestMapping("/rad/r1")
        public String test(Model model){
    
            model.addAttribute("msg","redirect");
    
            // 加forward转发和redirect重定向
            // 加了后需要传完整地址 视图解析器不会解析
            // 视图解析器(如 InternalResourceViewResolver)不会解析带有 redirect: 或 forward: 前缀 或 值
    //        return "forward:/WEB-INF/jsp/test.jsp";
    //      /WEB-INF/ 目录下的资源受服务器保护,不允许客户端直接访问。
    //      当你使用 redirect: 时,实际上是让浏览器重新发起一个请求,而浏览器无法直接访问受保护的 WEB-INF 目录。
    //        return "redirect:/WEB-INF/jsp/test.jsp";
            return "test";// 默认是转发
    
        }
    }
    

处理前端请求传入参数

  1. HttpServletRequest.getpara...

  2. springmvc 的三种

    1. 前端传入名 和 方法参数名一样 不用变

    2. 前端传入名 和 方法参数名不一样 加 @RequestParam注解(跟mybatis@Param有点像)

      能加就加 加就代表这个数据要从前端获得要处理

    3. 前端传入对象 和 定义的对象各个属性名一样就可以直接用

    package com.zhm.controller;
    
    import com.zhm.pojo.User;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    @Controller
    @RequestMapping("/user")
    public class ModelTest1 {
    
        // http://localhost:8080/user/t1?username=fuck
        // RequestParam 代表改名传参的k 能加就加 不加就要对应 加了就是username= 不加就是name=
        @RequestMapping("/t1")
        public String test(@RequestParam("username") String name,Model model){
            model.addAttribute("msg",name);
            return "test";
        }
    
        // http://localhost:8080/user/t2?id=1&name=kaxl&age=6 传对象 要对应属性名
        @RequestMapping("/t2")
        public String test(User user, Model model){
            model.addAttribute("msg",user);
            return "test";
        }
    }
    

配置前端过滤器

过滤器实现传入中文数据为乱码的问题

  1. HttpServletRequest/HttpServletResponse.setEncode

  2. 用spring配置好的过滤器类CharacterEncodingFilter,在web.xml配置

    本质也是实现Filter接口

    <!--两个易错点-->   
    <!--初始化-->    
    <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value> 
    </init-param>
        <!--/* 包括jsp和所有请求
            /只处理所有请求 -->
    <url-pattern>/*</url-pattern>
    
    <?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">
    <!--1.配置前端分发器-->
        <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: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>
    
    <!--配置过滤器,网页可以显示中文-->
        <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>
        <!--/* 包括jsp和所有请求
            /只处理所有请求 -->
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    </web-app>
    

JSON

  • 是一种数据交换格式,用文本格式来存储和表示数据

  • 简单来说 JSON就是 js对象的 字符串形式

    image-20250311163954621

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script>
            var user = {
                name : "招笑",
                id : 6,
                sex : "boy"
            };
            // js对象转化为json字符串
            var json = JSON.stringify(user);
            // json字符串转化为js对象
            var object = JSON.parse(json);
    
            console.log(json);
            console.log(object);
    
        </script>
    </head>
    <body>
    
    </body>
    </html>
    

    image-20250311163844874

JackSon

  • java常用的一种json转化工具类

  • 可以把类,集合,Date等等转化为JSON格式字符串,传给前端

    1. 导入依赖

      <dependency>
          <groupId>com.fasterxml.jackson.core</groupId>
          <artifactId>jackson-databind</artifactId>
          <version>2.18.3</version>
      </dependency>
      
    2. 配置springmvc-servlet.xml,解决中文json显示乱码

      <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.zhm.controller"/>
          <!--    mvc映射不处理静态资源 只处理servlet-->
          <mvc:default-servlet-handler/>
          <!--    支持mvc注解驱动,完成之前匹配器和适配器的功能-->
          <!--    解决前端js显示中文乱码-->
          <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>
      
      </beans>
      
    3. 注解使用

      • @RestController=@Controller + @ResponseBody

      • @RestController加在类上,之后类的所有方法的返回不走视图解析器只返回字符串

      • @ResponseBody加在方法上效果一样

      • 使用方法

        1. new ObjectMapper()获取mapper

        2. mapper.writeValueAsString(object)

          object为需要变为json的对象,结果返回的就是json字符串

      package com.zhm.controller;
      
      import com.fasterxml.jackson.core.JsonProcessingException;
      import com.fasterxml.jackson.databind.ObjectMapper;
      import com.fasterxml.jackson.databind.SerializationFeature;
      import com.zhm.pojo.User;
      import com.zhm.utils.JsonUtil;
      import org.springframework.stereotype.Controller;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.ResponseBody;
      import org.springframework.web.bind.annotation.RestController;
      
      import java.text.SimpleDateFormat;
      import java.util.Date;
      import java.util.LinkedList;
      
      // @Controller 通常返回视图(如HTML页面),需要配合 @ResponseBody 注解才能直接返回数据。
      // @RestController 默认所有方法都直接返回数据,适合API开发
      // 加了这个下面不用加 responseBody
      // 它结合了 @Controller 和 @ResponseBody 的功能,简化了开发
      @RestController
      //@Controller
      public class TestJson {
      
          @RequestMapping("/t/j1")
      //    @ResponseBody// 加这个注释不走视图解析器 只返回一个字符串
          public String test1() throws JsonProcessingException {
              User user = new User(1,"朱汉明","boy");
              ObjectMapper mapper = new ObjectMapper();
              String s = mapper.writeValueAsString(user);
              return s;
          }
      
          @RequestMapping("/t/j2")
          public String test2() throws JsonProcessingException {
              User user1 = new User(1,"朱汉明","boy");
              User user2 = new User(2,"朱明","boy");
              User user3 = new User(3,"朱汉","boy");
              User user4 = new User(4,"汉明","boy");
              User user5 = new User(5,"明","boy");
      
              LinkedList<User> users = new LinkedList<>();
              users.add(user1);
              users.add(user2);
              users.add(user3);
              users.add(user4);
              users.add(user5);
      
              return JsonUtil.getJson(users);
          }
      
          @RequestMapping("/t/j3")
          public String test3() throws JsonProcessingException {
              ObjectMapper mapper = new ObjectMapper();
              Date date = new Date();
              SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
              mapper.setDateFormat(sdf);
              return mapper.writeValueAsString(date);
          }
      
          @RequestMapping("/t/j4")
          public String test4() throws JsonProcessingException {
              return JsonUtil.getJson(new Date(),"yyyy-MM-dd HH:mm:ss");
          }
      
      }
      

      image-20250311224007066

      image-20250311224016034

    4. 可以写一个工具类,实现json

      package com.zhm.utils;
      
      
      import com.fasterxml.jackson.core.JsonProcessingException;
      import com.fasterxml.jackson.databind.ObjectMapper;
      
      import java.text.SimpleDateFormat;
      import java.util.Date;
      
      public class JsonUtil {
          public static String getJson(Object object) {
              return getJson(object,"yyyy-MM-dd HH:mm:ss");
          }
      
          public static String getJson(Object object,String form) {
              try {
                  ObjectMapper mapper = new ObjectMapper();
                  SimpleDateFormat sdf = new SimpleDateFormat(form);
                  mapper.setDateFormat(sdf);
                  return mapper.writeValueAsString(object);
              } catch (JsonProcessingException e) {
                  throw new RuntimeException(e);
              }
          }
      }
      

FastJson

  1. 导入依赖,项目结构工件lib记得加上这个

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.83</version>  <!-- 请使用最新版本 -->
    </dependency>
    
  2. 类上加@RestController或者@Controller+方法上@ResponseBody

    JSON.toJSONString(o)和JSON.parseObject(s,o.class)

    @RequestMapping("/t/j5")
    public String test5() throws JsonProcessingException {
        User user1 = new User(1,"朱汉明","boy");
        User user2 = new User(2,"朱明","boy");
        User user3 = new User(3,"朱汉","boy");
        User user4 = new User(4,"汉明","boy");
        User user5 = new User(5,"明","boy");
    
        LinkedList<User> users = new LinkedList<>();
        users.add(user1);
        users.add(user2);
        users.add(user3);
        users.add(user4);
        users.add(user5);
    
        String s = JSON.toJSONString(users);// 将对象变为json字符串
        Object parse = JSON.parse(s);// 把字符串变为对象
        System.out.println(parse);
        return s;
    }
    

Ajax

  • 前后端分离,把前端显示控制权由后端交给前端

  • image-20250318123858113

  • url 获取请求

    data 传前端数据给后端

    success 获取url成功就执行这个方法

    $.post({
      url : "${pageContext.request.contextPath}/h1/a1",
      data : {"name":$("#username").val()},
      success :function (data){
        alert(data);
      }
    })
    
  • <%--
      Created by IntelliJ IDEA.
      User: zhm
      Date: 2025/3/18
      Time: 10:22
      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}/statics/js/jquery-3.7.1.js"></script>
        <script>
          function a() {
            $.post({
              url : "${pageContext.request.contextPath}/h1/a1",
              data : {"name":$("#username").val()},
              success :function (data,status){
                alert(data); // 弹出服务器返回的数据(如 JSON 对象或字符串)
                alert(status);// 弹出 "success",因为请求成功
              }
            })
          }
        </script>
      </head>
      <body>
    <%--    失去焦点指向a方法--%>
        用户名 <input type="text" id="username" onblur="a()">
      </body>
    </html>
    
  • package com.zhm.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @Controller
    @RequestMapping("/h1")
    public class AjaxController {
        @ResponseBody
        @RequestMapping("/a1")
        public void a1(String name,HttpServletResponse response) throws IOException {
            if (name.equals("kuangshen")){
                response.getWriter().print("true");
            }else response.getWriter().print("false");
        }
    
    }
    

注意点

success :function (status,data){
  alert(data); // 弹出状态码,status因为在前面,所以status为返回数据true,data为状态码success
}
  1. 参数顺序

    第一个参数始终是服务器返回的数据,第二个参数是状态字符串(如 "success")。即使你将参数名改为 date,它依然代表服务器返回的数据,因为顺序不变。

异步加载数据

package com.zhm.controller;

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

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

@Controller
@RequestMapping("/h1")
public class AjaxController {
    @ResponseBody
    @RequestMapping("/a2")
    public List<User> a2(HttpServletResponse httpServletResponse) throws IOException {
        List<User> users = new ArrayList<User>();
        users.add(new User("kuangshen1",18,"boy"));
        users.add(new User("kuangshen2",38,"girl"));
        users.add(new User("kuangshen3",28,"boy"));
        return users;
    }
}
<%--
  Created by IntelliJ IDEA.
  User: zhm
  Date: 2025/3/18
  Time: 14:31
  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}/statics/js/jquery-3.7.1.js"></script>
    <script>
        $(function (){
            $("#btn").click(function () {
                $.post("${pageContext.request.contextPath}/h1/a2",function (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>"
                    }

                    $("#context").html(html);
                })
            })
        })

    </script>
</head>
<body>
<input type="button" id="btn" value="加载数据">
<table>
    <tr>
        <td>姓名</td>
        <td>年龄</td>
        <td>性别</td>
    </tr>
    <tbody id="context">
    </tbody>
</table>
</body>
</html>

ajax实现用户名密码验证

<%--
  Created by IntelliJ IDEA.
  User: zhm
  Date: 2025/3/18
  Time: 15:20
  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}/statics/js/jquery-3.7.1.js"></script>
    <script>
        function a1() {
            $.post({
                url: "${pageContext.request.contextPath}/h1/a3",
                data:{"name":$("#name").val()},
                success:function (data){
                    if (data.toString() === "Exist"){
                        $("#nameInfo").css("color","green");
                    }else {
                        $("#nameInfo").css("color","red");
                    }
                    $("#nameInfo").html(data);
                }
            })
        }
        function a2() {
            $.post({
                url: "${pageContext.request.contextPath}/h1/a3",
                data:{"pwd":$("#pwd").val()},
                success:function (data){
                    if (data.toString() === "Right"){
                        $("#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="nameInfo"></span>
</p>
<p>
    密码<input type="text" id="pwd" onblur="a2()">
    <span id="pwdInfo"></span>
</p>
</body>
</html>
package com.zhm.controller;

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

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

@Controller
@RequestMapping("/h1")
public class AjaxController {
    @ResponseBody
    @RequestMapping("/a3")
    public String a3(String name,String pwd){
        String msg = "";
        if (name!=null){
            if (name.equals("admin")) msg = "Exist";
            else msg = "Not Exist";
        }
        if (pwd!=null){
            if (pwd.equals("123456")) msg = "Right";
            else msg = "Wrong";
        }
        return msg;
    }
}

Interceptor拦截器

  • mvc自有,类似过滤器,拦截器就像一道门,根据条件拦截请求

  • 实现HandlerInterceptor接口就是拦截器

  • 用法

    1. 创建类实现HandlerInterceptor接口,重写方法,执行前,执行后,清理

      package com.zhm.interceptor;
      
      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 {
          @Override
          public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
              System.out.println("=======================执行前=======================");
              return true;// false阻止通过 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("=======================清理=======================");
          }
      }
      
    2. spring配置文件application-Context.xml(springmvc-servlet.xml)配置一下

          <mvc:interceptors>
              <mvc:interceptor>
      <!--            拦截这个请求下面的所有请求-->
                  <mvc:mapping path="/**"/>
                  <bean class="com.zhm.interceptor.MyInterceptor"/>
              </mvc:interceptor>
          </mvc:interceptors>
      
    3. 测试

      package com.zhm.controller;
      
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.RestController;
      
      @RestController
      public class MyTest {
      
          @GetMapping("/test")
          public String test(){
              System.out.println("=======================OK执行=======================");
              return "OK";
          }
      }
      

实现不登录就拦截

  1. 写前端页面,首页,登录页,跳转页(用于进入jsp页面,WEB-INF只能通过请求转发或者重定向进入)

    <%--
      Created by IntelliJ IDEA.
      User: zhm
      Date: 2025/3/18
      Time: 16: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/goLogin">登录页面</a></h1>
      <h1><a href="${pageContext.request.contextPath}/user/goMain">首页,登录才能进入,否则被重定向到登陆页面</a></h1>
      </body>
    </html>
    
    <%--
      Created by IntelliJ IDEA.
      User: zhm
      Date: 2025/3/18
      Time: 17:27
      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>登录页面</h1>
    <form action="${pageContext.request.contextPath}/user/login" method="post">
        <p>
            用户:<input type="text" name="username">
        </p>
        <p>
            密码:<input type="text" name="password">
        </p>
        <input type="submit" value="提交">
    </form>
    </body>
    </html>
    
    <%--
      Created by IntelliJ IDEA.
      User: zhm
      Date: 2025/3/18
      Time: 17:27
      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>首页</h1>
    </body>
    </html>
    
  2. 写请求controller

    package com.zhm.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    @Controller
    @RequestMapping("/user")
    public class LoginController {
        @RequestMapping("/goLogin")
        public String goLogin(){
            return "login";
        }
    
        @RequestMapping("/goMain")
        public String goMain(){
            return "main";
        }
    
        @RequestMapping("/login")
        public String Login(String username, String password, HttpSession session){
            session.setAttribute("userLoginInfo",username);// 把用户数据存入session便于后续确认用户是否登录
            return "redirect:/index.jsp";
        }
    }
    
  3. 编写拦截类,重写拦截前方法

    package com.zhm.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("login")){
                return true;
            }
            if (request.getRequestURI().contains("Login")){
                return true;
            }
            if (session.getAttribute("userLoginInfo")==null){
                request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
                return false;
            }
            if (session.getAttribute("userLoginInfo").equals("zhm")){
                return true;
            }
    
            System.out.println("未登录");
            request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
            return false;
        }
    }
    
  4. springmvc-servlet配置拦截器

    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/user/**"/>
            <bean class="com.zhm.config.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
    

文件上传与下载

  • 上传

    由客户端传到服务器,浏览器----》服务器

    1. 把客户端上传文件封装成is输入流

    2. 获取服务器存文件地址和文件名

    3. 通过存文件地址和文件名创建fileos输出流

    4. is读入buffer,os从buffer取出写入

      @RequestMapping("/upload")
      public String upload(@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);
          //上传路径保存设置,getServletContext获取服务器物理路径
          String path = request.getServletContext().getRealPath("/up");
          System.out.println("上传文件保存地址:"+path);
          //如果路径不存在,创建一个
          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";
      }
      
  • 下载

    客户端打开浏览器从服务器中下载文件,服务器----》浏览器

    1. 直接链接指向图片地址,用户自己下载

    2. request.getServletContext()获取图片地址,定义名字

      通过路径和名字创建fileis文件输入流,响应request创建os输出流

      fileis输入流读入buffer,从buffer获取写入os

      因为不用存数据,所以把数据交给浏览器就行了

      @RequestMapping("/download")
      public String downloads(HttpServletResponse response , HttpServletRequest request) throws Exception{
          //要下载的图片地址
          String path = request.getServletContext().getRealPath("/upload");
          String fileName = "屏幕截图(19).png";
          //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;
      }
      
  • 前端

    <%--
      Created by IntelliJ IDEA.
      User: zhm
      Date: 2025/3/19
      Time: 9:55
      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}/upload" enctype="multipart/form-data" method="post">
        <input type="file" name="file"/>
        <input type="submit">
      </form>
    
      <form action="${pageContext.request.contextPath}/upload2" enctype="multipart/form-data" method="post">
        <input type="file" name="file"/>
        <input type="submit">
      </form>
    
      <a href="${pageContext.request.contextPath}/download">点击下载</a>
      <a href="${pageContext.request.contextPath}/statics/1.png">点击下载2</a>
      </body>
    </html>
    
posted @ 2025-04-22 22:09  学习java的白菜  阅读(26)  评论(0)    收藏  举报