Spring MVC学习笔记

1、Spring MVC

ssm:MyBatis + Spring + Spring MVC MVC三层架构

Spring MVC + Vue + SpringBoot + SpringCloud + Linux

SSM = JavaWeb做项目

Spring:IOC和AOP

Spring MVC:Spring MVC的执行流程

Spring MVC:SSM框架整合

2、回顾MVC架构

MVC:模型(dao, service) 视图(jsp) 控制器(Servlet)

dao

service

servlet:转发、重定向

jsp/html

前端 数据传输 实体类

实体类:用户名,密码,生日,爱好,……20个

前端:用户名 密码

pojo:

vo(视图层):userVo

dto(数据传输)

JSP:本质就是一个Servlet

假设:你的项目的架构,是设计好的,还是演进的?

  • Alibaba PHP
  • 随着用户大,Java
  • 王坚 去IOE MySQL
  • MySQL:->AliSQL、AliRedis
  • All in one ->微服务

3、回顾Servlet

  1. 新建一个Maven工程当作父工程,pom依赖

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
         <version>1.2</version>
        </dependency>
    </dependencies>
    
  2. 建立一个Module:springmvc-01-servlet,添加Web app的支持(项目右键"Add Frameworks Support")

  3. 导入servlet和jsp的jar依赖

    <dependencies>
        <dependency>
         <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
    </dependencies>
    

HelloServlet

   public class HelloServlet extends HttpServlet {
       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           doGet(request, response);
       }
   
       protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           // 1.获取前端参数
           String method = request.getParameter("method");
           if (method.equals("add")) {
               request.getSession().setAttribute("msg", "执行了add方法");
           }
           if (method.equals("delete")) {
               request.getSession().setAttribute("msg", "执行了delete方法");
           }
           // 2.调用业务层
   
           // 3.视图转发或者重定向
           request.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(request, response);
       }
   }

test.jsp

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

form.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="/hello" method="post">
        <input type="text" name="method"/>
        <input type="submit"/>
    </form>
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>com.tangyixing.servlet.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>hello</servlet-name>
        <url-pattern>/hello</url-pattern>
    </servlet-mapping>

<!--    <session-config>-->
<!--        <session-timeout>15</session-timeout>-->
<!--    </session-config>-->
    
<!--    <welcome-file-list>-->
<!--        <welcome-file>index.jsp</welcome-file>-->
<!--    </welcome-file-list>-->
</web-app>

MVC框架要做哪些事情:

  1. 将url映射到java类或java类的方法
  2. 封装用户提交的数据
  3. 处理请求->调用相关的业务处理->封装响应数据
  4. 将响应的数据进行渲染, jsp/html等表示层数据

MVC

MVVM: M V VM(ViewModel:双向绑定)

4、初识Spring MVC

Spring MVC的特点:

  1. 轻量级, 简单易学
  2. 高效, 基于请求响应的MVC框架
  3. 与Spring兼容性好, 无缝结合
  4. 约定优于配置
  5. 功能强大: RESTful、数据验证、格式化、本地化、主题等
  6. 简洁灵活

步骤:

  1. 新建一个Module,添加web的支持

  2. 确定导入了Spring MVC的依赖

  3. 配置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">
    
        <!-- 1. 注册DispatcherServlet-->
        <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>
    
  4. 编写Spring MVC的配置文件, 名称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">
    
        <!-- 1. 添加 处理映射器 -->
        <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
        <!-- 2. 添加 处理器适配器 -->
        <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
        <!-- 3. 添加 视图解析器 -->
        <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.tangyixing.controller.HelloController"/>
    </beans>
    
  5. 编写我们要操作业务Controller(HelloController.java), 要么实现Controller接口, 要么添加注解

    public class HelloController implements Controller {
        public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
            ModelAndView mv = new ModelAndView();
            mv.addObject("msg", "HelloSpringMVC!");
            mv.setViewName("hello"); 
            // /WEB-INF/jsp/hello.jsp
            return mv;
        }
    }
    
  6. 写要跳转的jsp页面, 显示ModelAndView存放的数据, 以及我们的正常页面

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

可能遇到的问题: 访问出现404, 排查步骤

  1. 查看控制台输出, 看一下是不是缺少了什jar包
  2. 如果jar包存在, 显示无法输出, 就在IDEA的项目发布中, 添加lib依赖
    1. 打开Project Structure
    2. 点击Artifacts
    3. 在WEB-INF下添加文件夹lib
    4. 点击+号把所有包导进去

5、Spring MVC执行原理

Spring的web框架围绕DispatcherServlet设计, DispatcherServlet的作用是将请求分发到不同的处理器

6、深入Spring MVC学习

7、使用注解开发Spring MVC

  1. 配置web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <!-- 关联一个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>
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    </web-app>
    
  2. 添加springmvc-servlet.xml配置文件

    • 让IOC的注解生效
    • 静态资源过滤: HTML, JS, CSS, 图片, 视频
    • MVC的注解驱动
    • 配置视图解析器
    <?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
            https://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/mvc
            https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理-->
        <context:component-scan base-package="com.tangyixing.controller"/>
        <!-- 让Spring MVC不处理静态资源 -->
        <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>
    
  3. 创建Controller

    @Controller
    public class HelloController {
        @RequestMapping("/hello")
        public String hello(Model model) {
            // 封装数据
            model.addAttribute("msg", "Hello,SpringMVC Annotation!");
            return "hello"; // 会被视图解析器处理
        }
    }
    

    在类上添加@RequestMapping(), 则url: /hello/h1

    @Controller
    @RequestMapping("/hello")
    public class HelloController {
        @RequestMapping("/h1")
        public String hello(Model model) {
            // 封装数据
            model.addAttribute("msg", "Hello,SpringMVC Annotation!");
            return "hello"; // 会被视图解析器处理
        }
    }
    

步骤:

  1. 新建一个web项目
  2. 导入相关jar包
  3. 编写web.xml, 注册DispatcherServlet
  4. 编写Spring MVC配置文件
  5. 创建对应的控制类, Controller
  6. 完善前端视图和controller之间的对应
  7. 测试运行调试

使用Spring MVC必须配置的三大件:

处理器映射器, 处理器适配器, 视图解析器

通常我们只需要手动配置 视图解析器, 而 处理器映射器处理器适配器 只需要开启 注解驱动 即可, 从而省去了大段的xml配置.

8、Controller配置总结

方式一: 实现Controller接口

  1. 编写一个Controller类, ControllerTest1

    public class ControllerTest1 implements Controller {
        public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
            ModelAndView mv = new ModelAndView();
            mv.addObject("msg", "ControllerTest1");
            mv.setViewName("test");
            return mv;
        }
    }
    
  2. 编写完毕后,去Spring配置文件中注册请求的bean, name对应请求路径,class对应处理请求的类

    <bean name="/t1" class="com.tangyixing.controller.ControllerTest1"/>
    
  3. springmvc-servlet.xml

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/>
            <property name="suffix" value=".jsp"/>
    </bean>
    <bean name="/t1" class="com.tangyixing.controller.ControllerTest1"/>
    

说明:

  • 实现接口Controller定义控制器是较老的办法
  • 缺点是: 一个控制器中只有一个方法, 如果要多个方法则需要定义多个Controller, 定义的方法比较麻烦

方式二[推荐]: 使用注解@Controller

@Component		组件
@Service		service
@Controller		controller
@Repository		dao

springmvc-servlet.xml

<?xml version="1.0" encoding="GBK"?>
<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">

    <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理-->
    <context:component-scan base-package="com.tangyixing.controller"/>
    <!-- 让Spring MVC不处理静态资源 -->
    <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>

ControllerTest2.java

@Controller // 代表这个类会被Spring托管, 这个注解的类中的所有方法, 如果返回值是String, 并且有具体页面可以跳转, 那么就会被视图解析器解析.
public class ControllerTest2 {
    @RequestMapping("/t2")
    public String test1(Model model) {
        model.addAttribute("msg", "ControllerTest2");
        return "test";
    }
    
    @RequestMapping("/t3")
    public String test3(Model model) {
        model.addAttribute("msg", "test3");
        return "test";
    }
}

可以发现, 我们的两个请求都可以指向一个视图, 但是页面结果是不一样的, 所以视图是可以被复用的, 而控制器与视图之间是弱耦合关系.

9、RequestMapping说明

@RequestMapping 注解用于映射url到控制器类或一个特定的处理程序方法,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

@Controller
@RequestMapping("/c3")
public class ControllerTest3 {
    @RequestMapping("/t1")
    public String test1(Model model) {
        model.addAttribute("msg", "ControllerTest3");
        return "test";
    }
}

10、RestFul风格

功能

  • 资源:互联网所有事物都可以被抽象为资源
  • 资源操作:使用POST,DELETE,PUT,GET,使用不同方法对资源进行操作。
  • 分别对应 添加、删除、修改、查询

传统方式操作资源:通过不同的参数来实现不同的效果,方法单一,post和get

  • http://127.0.0.1/item/queryItem.action?id=1 查询, GET
  • http://127.0.0.1/item/saveItem.action 新增, POST
  • http://127.0.0.1/item/updateItem.action 更新, POST
  • http://127.0.0.1/item/deleteItem.action?id=1 删除, GET或POST

使用RestFul操作资源: 可以通过不同的请求方式来实现不同的效果! 如下: 请求地址一样, 但是功能可以不同

  • http://127.0.0.1/item/1 查询,GET
  • http://127.0.0.1/item 新增, POST
  • http://127.0.0.1/item 更新, PUT
  • http://127.0.0.1/item/1 删除, DELETE

传统方式 (url: /add?a=1&b=2)

@Controller
public class RestFulController {
    @RequestMapping("/add")
    public String test1(int a, int b, Model model) {
        int res = a + b;
        model.addAttribute("msg", "结果为" + res);
        return "test";
    }
}

RestFul方式 (url: add/1/2):

使用 @PathVariable 注解, 让方法参数的值对应绑定到一个URI模板变量上

@Controller
public class RestFulController {
    @RequestMapping("/add/{a}/{b}")
    public String test1(@PathVariable int a, @PathVariable int b, Model model) {
        int res = a + b;
        model.addAttribute("msg", "结果为" + res);
        return "test";
    }
}

设置请求的方式:

@Controller
public class RestFulController {
//    @RequestMapping(value = "/add/{a}/{b}", method = RequestMethod.GET)
    @GetMapping("/add/{a}/{b}")
    public String test1(@PathVariable int a, @PathVariable String b, Model model) {
        String res = a + b;
        model.addAttribute("msg", "结果为" + res);
        return "test";
    }
}
@GetMapping()
@PostMapping()
@PutMapping()
@DeleteMapping()
@RequestMapping(value = "", method = RequestMethod.GET)

使用路径变量的好处:

  • 使路径变得更加简洁
  • 获得参数更加方便, 框架会自动进行类型转换
  • 通过路径变量的类型可以约束访问参数, 如果类型不一样, 则访问不到对应的请求方法

11、重定向和转发

ModelAndView

设置ModelAndView对象, 根据view的名称, 和视图解析器跳转到指定的页面

页面: [视图解析器前缀] + viewName + [视图解析器后缀]

ServletAPI

通过设置ServletAPI, 不需要视图解析器

  1. 通过HttpServletResponse进行输出
  2. 通过HttpServletResponse实现重定向
  3. 通过HttpServletRequest实现转发
// 重定向
response.sendRedirect("/index.jsp");
// 转发
request.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(request, response);

Spring MVC

通过Spring MVC来实现转发和重定向 - 无需视图解析器

测试前, 需要将视图解析器注释

@Controller
public class ModelTest1 {
    @RequestMapping("/m1/t1")
    public String test1(Model model) {
        // 转发
        model.addAttribute("msg", "ModelTest1");
        return "/WEB-INF/jsp/test.jsp";
    }

    @RequestMapping("/m1/t2")
    public String test2(Model model) {
        // 转发
        model.addAttribute("msg", "ModelTest1");
        return "forward:/WEB-INF/jsp/test.jsp";
    }

    @RequestMapping("/m1/t3")
    public String test3(Model model) {
        // 重定向
        model.addAttribute("msg", "ModelTest1");
        return "redirect:/index.jsp";
    }
}

通过Spring MVC来实现转发和重定向 - 有视图解析器

直接在前面添加redirect:

转发才会触发视图解析器拼接, 重定向不会触发

重定向不能访问WEB-INF的内容

@Controller
public class ModelTest1 {
    @RequestMapping("/m1/t1")
    public String test1(Model model) {
        // 转发
        model.addAttribute("msg", "ModelTest1");
        return "test";
    }

    @RequestMapping("/m1/t2")
    public String test2(Model model) {
        // 转发
        model.addAttribute("msg", "ModelTest1");
        return "forward:/WEB-INF/jsp/test.jsp";
    }

    @RequestMapping("/m1/t3")
    public String test3(Model model) {
        // 重定向
        model.addAttribute("msg", "ModelTest1");
        return "redirect:/index.jsp";
    }
}

12、接收请求参数及数据回显

处理提交数据

1. 提交的域名称和处理方法的参数名一致

提交数据: http://localhost:8080/t1?name=tyx

@GetMapping("/t1")
public String test1(String name, Model model) {
    // 1.接收前端参数
    System.out.println("接收到前端的参数为" + name);
    // 2.将返回的结果传递给前端
    model.addAttribute("msg", name);
    // 3.视图跳转
    return "test";
}

2. 后台的域名称和处理方法的参数名不一致

提交数据: http://localhost:8080/t1?username=tyx

@GetMapping("/t2")
public String test2(@RequestParam("username") String name, Model model) {
    // 1.接收前端参数
    System.out.println("接收到前端的参数为" + name);
    // 2.将返回的结果传递给前端
    model.addAttribute("msg", name);
    // 3.视图跳转
    return "test";
}

[建议] 无论前后端参数名是否一致, 都建议在变量前面添加**@RequestParam("") **注解, 代表这是一个前端参数.

3. 提交的是一个对象

要求提交的表单域和属性名一致, 参数使用对象即可

  1. 实体类

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class User {
        private int id;
        private String name;
        private int age;
    }
    
  2. 提交数据: http://localhost:8080/t1?id=1&name=tyx&age=23

  3. 处理方法

    @GetMapping("/t3")
    public String test3(User user) {
        System.out.println(user);
        return "test";
    }
    

后台输出: User(id=1, name=tyx, age=23)

说明: 如果使用对象的话, 前端传递的参数名和对象名必须一致, 否则就是null.

数据显示到前端

1. 通过ModelAndView

public class HelloController implements Controller {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", "HelloSpringMVC!");
        mv.setViewName("test");
        return mv;
    }
}

2. 通过Model

@GetMapping("/t2")
public String test2(@RequestParam("username") String name, Model model) {
    System.out.println("接收到前端的参数为" + name);
    model.addAttribute("msg", name);
    return "test";
}

3. 通过ModelMap

@GetMapping("/t3")
public String test3(@RequestParam("username") String name, ModelMap model) {
    model.addAttribute("name", name);
    System.out.println(name);
    return "test";
}

对比:

Model: 只有寥寥几个方法只适用于储存数据, 简化了新手对于Model对象的操作和理解

ModelMap: 继承了LinkedMap, 除了实现了自身的一些方法, 同样的继承LinkedMap的方法和特性

ModelAndView: 可以在储存数据的同时, 可以进行设置返回的逻辑视图, 进行控制展示层的跳转

13、乱码问题解决

EncodingController

@Controller
public class EncodingController {
    @PostMapping("/e/t1")
    public String test1(@RequestParam("name") String name, Model model) {
        System.out.println(name);
        model.addAttribute("msg", name);
        return "test";
    }
}

form.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="e/t1" method="post">
        <input type="text" name="name"/>
        <input type="submit"/>
    </form>
</body>
</html>

解决方案一:

EncodingFilter

public class EncodingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        filterChain.doFilter(servletRequest, servletResponse);
    }
    public void destroy() {

    }
}

web.xml

<filter>
    <filter-name>encoding</filter-name>
    <filter-class>com.tangyixing.filter.EncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

解决方案二:

将post方式改为get方式

解决方案三: 配置Spring MVC的乱码过滤

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

14、JSON

前后端分离:

后端部署后端,提供接口,提供数据

josn

前端独立部署,负责渲染后端的数据

<script type="text/javascript">
    // 编写一个JavaScript对象
    var user = {
        name : "唐毅兴",
        age: 23,
        sex: "男"
    };
    console.log(user)
    // 将JavaScript对象转换为JSON字符串
    var json = JSON.stringify(user);
    console.log(json);
    // 将JSON字符串转换为JavaScript对象
    var obj = JSON.parse(json);
    console.log(obj);
</script>

14.1 Jackson

pom.xml

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.2</version>
</dependency>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 关联一个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>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

springmvc-servlet.xml

<?xml version="1.0" encoding="GBK"?>
<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">
    <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理-->
    <context:component-scan base-package="com.tangyixing.controller"/>
    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

User.java

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private String name;
    private int age;
    private String sex;
}

UserController.java

@Controller
public class UserController {

    @RequestMapping("j1")
    // 不走视图解析器, 会直接返回一个字符串
    @ResponseBody
    public String json1() throws JsonProcessingException {
        // jackson, ObjectMapper
        ObjectMapper mapper = new ObjectMapper();
        // 创建一个对象
        User user = new User("tyx1", 23, "男");
        String str = mapper.writeValueAsString(user);
        return str;
    }
}

返回输出:

{"name":"唐毅兴","age":23,"sex":"男"}

乱码问题:

方式一:

@RequestMapping(value = "/j1", produces = "application/json;charset=utf-8")

方式二:

上一种方法比较麻烦,如果项目中有许多请求每一个都要添加,可以通过Spring配置统一指定,这样就不用每次都去处理了

可以在Spring MVC的配置文件"springmvc-servlet"上添加一段消息StringHttpMessageConverter转换配置

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

@RestController

相当于@Controller + @ResponseBody

表示这个控制类下的所有方法只会返回字符串

前后端分离,只返回JSON字符串

返回多个对象

@RestController
public class UserController {
    
    @RequestMapping("j2")
    public String json2() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        List<User> userList = new ArrayList<User>();
        User user1 = new User("唐毅兴1", 23, "男");
        User user2 = new User("唐毅兴2", 23, "男");
        User user3 = new User("唐毅兴3", 23, "男");
        User user4 = new User("唐毅兴4", 23, "男");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);
        String str = mapper.writeValueAsString(userList);
        return str;
    }
}

输出:

[{"name":"唐毅兴1","age":23,"sex":"男"},{"name":"唐毅兴2","age":23,"sex":"男"},{"name":"唐毅兴3","age":23,"sex":"男"},{"name":"唐毅兴4","age":23,"sex":"男"}]

返回日期时间

@RestController
public class UserController {
    @RequestMapping("j3")
    public String json3() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Date date = new Date();
        // ObjectMapper, 时间解析后的默认格式为: Timestamp, 时间戳
        return mapper.writeValueAsString(date);
    }
}

输出:

1604123175995
日期格式化

方式一: 纯Java

@RequestMapping("j3")
public String json3() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    Date date = new Date();
    // 自定义日期的格式
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    // ObjectMapper, 时间解析后的默认格式为: Timestamp, 时间戳
    return mapper.writeValueAsString(sdf.format(date));
}

方式二: 关闭时间戳, 设置自己定义的格式

@RequestMapping("j3")
public String json3() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    // 不使用时间戳的方式
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    Date date = new Date();
    // 自定义日期的格式
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    mapper.setDateFormat(sdf);
    // ObjectMapper, 时间解析后的默认格式为: Timestamp, 时间戳
    return mapper.writeValueAsString(date);
}

输出:

"2020-10-31 13:54:57"

提取封装JSON工具类

public class JsonUtils {
    public static String getJson(Object object) {
        return getJson(object, "yyyy-MM-dd HH:ss:mm");
    }

    public static String getJson(Object object, String dateFormat) {
        ObjectMapper mapper = new ObjectMapper();
        // 不使用时间戳的方式
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        Date date = new Date();
        // 自定义日期的格式
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        mapper.setDateFormat(sdf);
        try {
            return mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }
}

14.2 FastJson

pom.xml

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.74</version>
</dependency>

UserController.java

@RequestMapping("j4")
public String json4() {
    List<User> userList = new ArrayList<User>();
    User user1 = new User("唐毅兴1", 23, "男");
    User user2 = new User("唐毅兴2", 23, "男");
    User user3 = new User("唐毅兴3", 23, "男");
    User user4 = new User("唐毅兴4", 23, "男");
    userList.add(user1);
    userList.add(user2);
    userList.add(user3);
    userList.add(user4);
    String str = JSON.toJSONString(userList);
    return str;
}
    @RequestMapping("j4")
    public String json4() {
        List<User> userList = new ArrayList<User>();
        User user1 = new User("唐毅兴1", 23, "男");
        User user2 = new User("唐毅兴2", 23, "男");
        User user3 = new User("唐毅兴3", 23, "男");
        User user4 = new User("唐毅兴4", 23, "男");
        userList.add(user1);
        userList.add(user2);
        userList.add(user3);
        userList.add(user4);

        System.out.println("******* Java对象 转 JSON字符串 *******");
        String str1 = JSON.toJSONString(userList);
        System.out.println("JSON.toJSONString(list)==>" + str1);
        String str2 = JSON.toJSONString(user1);
        System.out.println("JSON.toJSONString(user1)==>" + str2);

        System.out.println("******* JSON字符串 转 Java对象 *******");
        User jp_user1 = JSON.parseObject(str2, User.class);
        System.out.println("JSON.parseObject(str2, User.class)==>" + jp_user1);

        System.out.println("******* Java对象 转 JSON对象 *******");
        JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
        System.out.println("(JSONObject) JSON.toJSON(user2)==>" + jsonObject1.getString("name"));

        System.out.println("******* JSON对象 转 Java对象 *******");
        User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
        System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>" + to_java_user);
        return "hello";
    }

输出:

******* Java对象 转 JSON字符串 *******
JSON.toJSONString(list)==>[{"age":23,"name":"唐毅兴1","sex":"男"},{"age":23,"name":"唐毅兴2","sex":"男"},{"age":23,"name":"唐毅兴3","sex":"男"},{"age":23,"name":"唐毅兴4","sex":"男"}]
JSON.toJSONString(user1)==>{"age":23,"name":"唐毅兴1","sex":"男"}
******* JSON字符串 转 Java对象 *******
JSON.parseObject(str2, User.class)==>User(name=唐毅兴1, age=23, sex=男)
******* Java对象 转 JSON对象 *******
(JSONObject) JSON.toJSON(user2)==>唐毅兴2
******* JSON对象 转 Java对象 *******
JSON.toJavaObject(jsonObject1, User.class)==>User(name=唐毅兴2, age=23, sex=男)

15、整合SSM

数据库环境

CREATE DATABASE `ssmbuild`

USE `ssmbuild`

DROP TABLE IF EXISTS `books`;

CREATE TABLE `books`(
	`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '图书id',
	`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
	`bookCounts` INT(11) NOT NULL COMMENT '数量',
	`detail` VARCHAR(200) NOT NULL COMMENT '描述',
	PRIMARY KEY (`bookID`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO `books`(`bookID`, `bookName`, `bookCounts`, `detail`) VALUES
(1, 'Java', 1, '从入门到放弃'),
(2, 'MySQL', 10, '从删库到跑路'),
(3, 'Linux', 5, '从进门到进牢')

搭建基本环境

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.tangyixing</groupId>
    <artifactId>ssmbuild</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
</project>

建立基本结构和配置文件

pojo, dao, service, controller

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

</configuration>

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

</beans>

16、Ajax

AJAX:异步的JavaScript和XML

16.1 Demo

index.html

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
    <script>
      function a() {
        $.post({
          url:"${pageContext.request.contextPath}/a1",
          data:{"name": $("#username").val()},
          success: function (data) {
            alert(data);
          }
        })
      }
    </script>
  </head>
  <body>
    用户名: <input type="text" id="username" onblur="a()"/>
  </body>
</html>

AjaxController.java

@RestController
public class AjaxController {

    @RequestMapping("/a1")
    public void a1(String name, HttpServletResponse response) throws IOException {
        System.out.println(name);
        if ("tyx".equals(name)) {
            response.getWriter().print("true");
        } else {
            response.getWriter().print("false");
        }
    }
}

16.2 展示后端传的List到表格

test2.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
    <script>
        $(function () {
            $("#btn").click(function () {
                $.post("${pageContext.request.contextPath}/a2", function (data) {
                    console.log(data);
                    var html="<>";
                    for (let i = 0; i < data.length; i++) {
                        html += "<tr>" +
                            "<td>" + data[i].name + "</td>" +
                            "<td>" + data[i].age + "</td>" +
                            "<td>" + data[i].sex + "</td>" +
                            "</tr>"
                    }
                    $("#content").html(html)
                })
            });
        })
    </script>
</head>
<body>
    <input type="button" value="加载数据" id="btn"/>
    <table>
        <tr>
            <th>姓名</th>
            <th>年龄</th>
            <th>性别</th>
        </tr>
        <tbody id="content">

        </tbody>
    </table>
</body>
</html>

AjaxController.java

@RestController
public class AjaxController {
    @RequestMapping("/a2")
    public List<User> a2() {
        List<User> userList = new ArrayList<User>();
        // 添加数据
        userList.add(new User("tyx1", 23, "男"));
        userList.add(new User("tyx2", 24, "男"));
        userList.add(new User("tyx3", 25, "男"));
        return userList;
    }
}

16.3 验证用户名密码是否正确

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
    <script>
        function a1() {
            $.post({
                url: "${pageContext.request.contextPath}/a3",
                data: {"name": $("#name").val()},
                success: function (data) {
                    if (data.toString()==='ok') {
                        $("#userInfo").css("color", "green");
                    } else {
                        $("#userInfo").css("color", "red");
                    }
                    $("#userInfo").html(data);
                }
            })
        }
        function a2() {
            $.post({
                url: "${pageContext.request.contextPath}/a3",
                data: {"pwd": $("#pwd").val()},
                success: function (data) {
                    if (data.toString()==='ok') {
                        $("#pwdInfo").css("color", "green");
                    } else {
                        $("#pwdInfo").css("color", "red");
                    }
                    $("#pwdInfo").html(data);
                }
            })
        }
    </script>
</head>
<body>
    <p>
        用户名: <input type="text" id="name" οnblur="a1()"/>
        <span id="userInfo"></span>
    </p>
    <p>
        密码: <input type="text" id="pwd" οnblur="a2()"/>
        <span id="pwdInfo"></span>
    </p>
</body>
</html>

AjaxController.java

@RestController
public class AjaxController {
    @RequestMapping("/a3")
    public String a3(String name, String pwd) {
        String msg = "";
        if (name != null) {
            if ("admin".equals(name)) {
                msg = "ok";
            } else {
                msg = "用户名有误";
            }
        }
        if (pwd != null) {
            if ("123456".equals(pwd)) {
                msg = "ok";
            } else {
                msg = "密码有误";
            }
        }
        return msg;
    }
}

17、拦截器

17.1 Demo

类似于Servlet开发中的过滤器Filter,

config/MyInterceptor.java

public class MyInterceptor implements HandlerInterceptor {

    // return true: 执行下一个拦截器, 放行
    // return false: 不执行下一个拦截器
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("==========处理前==========");
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("==========处理后==========");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("==========清理==========");
    }
}
  • 一般只用写preHandle,来对请求进行拦截
  • postHandle和afterCompletion一般用来日志
  • request和response实现转发和重定向,不让过就跳转

applicationContext.xml

<!-- 拦截器配置 -->
<mvc:interceptors>
    <mvc:interceptor>
        <!-- /** 包括这个请求下面的所有的请求 /admin/asdf/asdf -->
        <!-- /* 这个请求下面一级的请求 /admin -->
        <mvc:mapping path="/**"/>
        <bean class="com.tangyixing.config.MyInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

17.2 登录拦截器

index.jsp

<%@ 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/main">首页</a></h1>
  </body>
</html>

main.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>首页</h1>
    <span>${username}</span>
    <p>
        <a href="${pageContext.request.contextPath}/user/logout">注销</a>
    </p>
</body>
</html>

login.jsp

<%@ 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">
        用户名: <input type="text" name="username"/>
        密码: <input type="password" name="password"/>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>

LoginController.java

@Controller
@RequestMapping("/user")
public class LoginController {
    @RequestMapping("/main")
    public String main() {
        return "main";
    }

    @RequestMapping("/gologin")
    public String login() {
        return "login";
    }

    @RequestMapping("/login")
    public String login(HttpSession session, String username, String password, Model model) {
        System.out.println("login==>" + username);
        // 把用户的信息存在session中
        session.setAttribute("userLoginInfo", username);
        model.addAttribute("username", username);
        return "main";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        // 移除session节点
        session.removeAttribute("userLoginInfo");
        return "redirect:/";
    }
}

LoginInterceptor

public class LoginInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        // 放行: 判断什么情况下登录

        // 登录页面也会放行
        if (request.getRequestURI().contains("goLogin")) {
            return true;
        }
        // 第一次登录, 也是没有session的
        if (request.getRequestURI().contains("login")) {
            return true;
        }
        // 有登录信息才放行
        if (session.getAttribute("userLoginInfo") != null) {
            return true;
        }
        // 判断什么情况下没有登录
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
        return false;
    }
}

applicationContext.xml

<mvc:interceptors>
    <mvc:interceptor>
        <!-- /** 包括这个请求下面的所有的请求 /admin/asdf/asdf -->
        <!-- /* 这个请求下面的一个请求 -->
        <mvc:mapping path="/user/**"/>
        <bean class="com.tangyixing.config.LoginInterceptor"/>
    </mvc:interceptor>
</mvc:interceptors>

18、文件上传和下载

Spring MVC上下文中默认没有装配MultipartResolver,因此默认情况下其不能处理文件上传工作。如果想使用Spring的文件上传功能,则需要在上下文中配置MultipartResolver。

前端表单要求:为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data,只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器:

  1. pom.xml
<dependencies>
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
    </dependency>
</dependencies>
  1. index.jsp
<%@ 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" value="上传"/>
    </form>
  </body>
</html>
  1. 在applicationContext.xml中配置multipartResolver
<!-- 文件上传配置 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8"/>
    <!-- 上传文件大小上限, 单位为字节 -->
    <property name="maxUploadSize" value="10485760"/>
    <property name="maxInMemorySize" value="40960"/>
</bean>
  1. 保存上传的文件 - FileController.java
@Controller
public class FileController {
    // 批量上传CommonsMultipartFile则为数组即可
    @RequestMapping("/upload")
    public String fileUpload(@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);
        // 上传路径保存设置
        String path = request.getServletContext().getRealPath("/upload");
        // 如果路径不存在, 创建一个
        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. 下载文件
  • index.jsp
<a href="${pageContext.request.contextPath}/download">下载图片</a>
  • FileController.java
@RequestMapping("/download")
public String downloads(HttpServletResponse response, HttpServletRequest request) throws IOException {
    // 要下载的图片地址
    String path = request.getServletContext().getRealPath("/upload");
    String fileName = "1.jpg";

    // 1. 设置response响应头
    response.reset();   // 设置页面不缓存, 清空buffer
    response.setCharacterEncoding("UTF-8"); // 字符编码
    response.setContentType("mutipart/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 "ok";
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值