SpringMVC狂神说笔记

idea tips:

  1. 1. 只要了改了java代码就要reload一下 ( 只要没改xml )
  2. 2. 只要改了配置文件就刷新tomcat
  3. 3. 只要改了前端页面 就刷新一下就好了

1、回顾MVC

1.1、什么是MVC

  • MVC是模型(Model)、视图(View)、控制器(Controller)的简写,是一种软件设计规范。
  • 是将业务逻辑、数据、显示分离的方法来组织代码。
  • MVC主要作用是降低了视图与业务逻辑间的双向偶合
  • MVC不是一种设计模式,MVC是一种架构模式。当然不同的MVC存在差异。

Model(模型):数据模型,提供要展示的数据,因此包含数据和行为,可以认为是领域模型或JavaBean组件(包含数据和行为),不过现在一般都分离开来:Value Object(数据Dao) 和 服务层(行为Service)。也就是模型提供了模型数据查询和模型数据的状态更新等功能,包括数据和业务。

View(视图):负责进行模型的展示,一般就是我们见到的用户界面,客户想看到的东西。

Controller(控制器):接收用户请求,委托给模型进行处理(状态改变),处理完毕后把返回的模型数据返回给视图,由视图负责展示。也就是说控制器做了个调度员的工作。

最典型的MVC就是JSP + servlet + javabean的模式。

SpringMVC狂神说最全笔记 - 图1

1.2、Model1时代

  • 在web早期的开发中,通常采用的都是Model1。
  • Model1中,主要分为两层,视图层和模型层。

SpringMVC狂神说最全笔记 - 图2

Model1优点:架构简单,比较适合小型项目开发;

Model1缺点:JSP职责不单一,职责过重,不便于维护;

1.3、Model2时代

Model2把一个项目分成三部分,包括视图、控制、模型。

SpringMVC狂神说最全笔记 - 图3

  1. 用户发请求
  2. Servlet接收请求数据,并调用对应的业务逻辑方法
  3. 业务处理完毕,返回更新后的数据给servlet
  4. servlet转向到JSP,由JSP来渲染页面
  5. 响应给前端更新后的页面

职责分析:

Controller:控制器

  1. 取得表单数据
  2. 调用业务逻辑
  3. 转向指定的页面

Model:模型

  1. 业务逻辑
  2. 保存数据的状态

View:视图

  1. 显示页面

Model2这样不仅提高的代码的复用率与项目的扩展性,且大大降低了项目的维护成本。Model 1模式的实现比较简单,适用于快速开发小规模项目,Model1中JSP页面身兼View和Controller两种角色,将控制逻辑和表现逻辑混杂在一起,从而导致代码的重用性非常低,增加了应用的扩展性和维护的难度。Model2消除了Model1的缺点。

1.4、回顾Servlet

  1. 新建一个Maven工程当做父工程!pom依赖!
    1. <dependencies>
    2. <dependency>
    3. <groupId>junit</groupId>
    4. <artifactId>junit</artifactId>
    5. <version>4.12</version>
    6. </dependency>
    7. <dependency>
    8. <groupId>org.springframework</groupId>
    9. <artifactId>spring-webmvc</artifactId>
    10. <version>5.1.9.RELEASE</version>
    11. </dependency>
    12. <dependency>
    13. <groupId>javax.servlet</groupId>
    14. <artifactId>servlet-api</artifactId>
    15. <version>2.5</version>
    16. </dependency>
    17. <dependency>
    18. <groupId>javax.servlet.jsp</groupId>
    19. <artifactId>jsp-api</artifactId>
    20. <version>2.2</version>
    21. </dependency>
    22. <dependency>
    23. <groupId>javax.servlet</groupId>
    24. <artifactId>jstl</artifactId>
    25. <version>1.2</version>
    26. </dependency>
    27. </dependencies>
  1. 建立一个Moudle:springmvc-01-servlet , 添加Web app的支持!
  2. 导入servlet 和 jsp 的 jar 依赖
    1. <dependency>
    2. <groupId>javax.servlet</groupId>
    3. <artifactId>servlet-api</artifactId>
    4. <version>2.5</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>javax.servlet.jsp</groupId>
    8. <artifactId>jsp-api</artifactId>
    9. <version>2.2</version>
    10. </dependency>
  1. 编写一个Servlet类,用来处理用户的请求 ```java package com.kuang.servlet;

//实现Servlet接口 public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //取得参数 String method = req.getParameter(“method”); if (method.equals(“add”)){ req.getSession().setAttribute(“msg”,”执行了add方法”); } if (method.equals(“delete”)){ req.getSession().setAttribute(“msg”,”执行了delete方法”); } //业务逻辑 //视图跳转 req.getRequestDispatcher(“/WEB-INF/jsp/hello.jsp”).forward(req,resp); }

@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req,resp); } }

  1. 5. 编写Hello.jsp,在WEB-INF目录下新建一个jsp的文件夹,新建hello.jsp
  2. ```html
  3. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  4. <html>
  5. <head>
  6. <title>Kuangshen</title>
  7. </head>
  8. <body>
  9. ${msg}
  10. </body>
  11. </html>
  1. 在web.xml中注册Servlet ```xml <?xml version=”1.0” encoding=”UTF-8”?> <web-app xmlns=”http://xmlns.jcp.org/xml/ns/javaee
    1. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    2. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    3. version="4.0">
    HelloServlet com.kuang.servlet.HelloServlet HelloServlet /user

  1. 7. 配置Tomcat,并启动测试
  2. 8.
  3. - localhost:8080/user?method=add
  4. - localhost:8080/user?method=delete
  5. **MVC框架要做哪些事情**
  6. 1. url映射到java类或java类的方法 .
  7. 2. 封装用户提交的数据 .
  8. 3. 处理请求--调用相关的业务处理--封装响应数据 .
  9. 4. 将响应的数据进行渲染 . jsp / html 等表示层数据 .
  10. **说明:**
  11. 常见的服务器端MVC框架有:StrutsSpring MVCASP.NET MVCZend FrameworkJSF;常见前端MVC框架:vueangularjsreactbackbone;由MVC演化出了另外一些模式如:MVPMVVM 等等....
  12. <a name="2f73ee94"></a>
  13. ## 2、什么是SpringMVC
  14. <a name="91461e1e"></a>
  15. ### 2.1、概述
  16. Spring MVCSpring Framework的一部分,是基于Java实现MVC的轻量级Web框架。
  17. 查看官方文档:[https://docs.spring.io/spring/docs/5.2.0.RELEASE/spring-framework-reference/web.html#spring-web](https://docs.spring.io/spring/docs/5.2.0.RELEASE/spring-framework-reference/web.html#spring-web)
  18. **我们为什么要学习SpringMVC呢?**
  19. Spring MVC的特点:
  20. 1. 轻量级,简单易学
  21. 2. 高效 , 基于请求响应的MVC框架
  22. 3. Spring兼容性好,无缝结合
  23. 4. 约定优于配置
  24. 5. 功能强大:RESTful、数据验证、格式化、本地化、主题等
  25. 6. 简洁灵活
  26. Springweb框架围绕**DispatcherServlet** [ 调度Servlet ] 设计。
  27. DispatcherServlet的作用是将请求分发到不同的处理器。从Spring 2.5开始,使用Java 5或者以上版本的用户可以采用基于注解形式进行开发,十分简洁;
  28. 正因为SpringMVC , 简单 , 便捷 , 易学 , 天生和Spring无缝集成(使用SpringIoCAop) , 使用约定优于配置 . 能够进行简单的junit测试 . 支持Restful风格 .异常处理 , 本地化 , 国际化 , 数据验证 , 类型转换 , 拦截器 等等......所以我们要学习 .
  29. **最重要的一点还是用的人多 , 使用的公司多 .**
  30. <a name="dc6f89ee"></a>
  31. ### 2.2、中心控制器
  32. Springweb框架围绕DispatcherServlet设计。DispatcherServlet的作用是将请求分发到不同的处理器。从Spring 2.5开始,使用Java 5或者以上版本的用户可以采用基于注解的controller声明方式。
  33. Spring MVC框架像许多其他MVC框架一样, **以请求为驱动** , **围绕一个中心Servlet分派请求及提供其他功能**,**DispatcherServlet是一个实际的Servlet (它继承自HttpServlet 基类)**。
  34. SpringMVC的原理如下图所示:
  35. 当发起请求时被前置的控制器拦截到请求,根据请求参数生成代理请求,找到请求对应的实际控制器,控制器处理请求,创建数据模型,访问数据库,将模型响应给中心控制器,控制器使用模型与视图渲染视图结果,将结果返回给中心控制器,再将结果返回给请求者。
  36. ![](https://mmbiz.qpic.cn/mmbiz_png/uJDAUKrGC7KwPOPWq00pMJiaK86lF6BjIaosVziclWLEJQkzobxHrpHcmtu2yTeVWPmEI4Yq5PaicS52VaJt8dYfQ/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1#crop=0&crop=0&crop=1&crop=1&id=FoYZg&originHeight=457&originWidth=930&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
  37. <a name="2c8d09c4"></a>
  38. ### 2.3、SpringMVC执行原理
  39. ![](https://mmbiz.qpic.cn/mmbiz_png/uJDAUKrGC7KwPOPWq00pMJiaK86lF6BjIbmPOkY8TxF6qvGAGXxC7dArYcr8uJlWoVC4aF4bfxgCGCD8sHg8mgw/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1#crop=0&crop=0&crop=1&crop=1&id=yN3Ir&originHeight=507&originWidth=952&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
  40. 图为SpringMVC的一个较完整的流程图,实线表示SpringMVC框架提供的技术,不需要开发者实现,虚线表示需要开发者实现。
  41. **简要分析执行流程**
  42. 1. DispatcherServlet表示前置控制器,是整个SpringMVC的控制中心。用户发出请求,DispatcherServlet接收请求并拦截请求。<br />我们假设请求的url : [http://localhost:8080/SpringMVC/hello](http://localhost:8080/SpringMVC/hello)<br />**如上url拆分成三部分:**<br />http://localhost:8080服务器域名<br />SpringMVC部署在服务器上的web站点<br />hello表示控制器<br />通过分析,如上url表示为:请求位于服务器localhost:8080上的SpringMVC站点的hello控制器。
  43. 2. HandlerMapping为处理器映射。DispatcherServlet调用HandlerMapping,HandlerMapping根据请求url查找Handler
  44. 3. HandlerExecution表示具体的Handler,其主要作用是根据url查找控制器,如上url被查找控制器为:hello
  45. 4. HandlerExecution将解析后的信息传递给DispatcherServlet,如解析控制器映射等。
  46. 5. HandlerAdapter表示处理器适配器,其按照特定的规则去执行Handler。(就是去找controller)
  47. 6. Handler让具体的Controller执行。
  48. 7. Controller将具体的执行信息返回给HandlerAdapter,如ModelAndView
  49. 8. HandlerAdapter将视图逻辑名或模型传递给DispatcherServlet
  50. 9. DispatcherServlet调用视图解析器(ViewResolver)来解析HandlerAdapter传递的逻辑视图名。
  51. 1. 获取了ModuleAndView 中的数据
  52. 1. 解析ModuleAndView 的视图名字
  53. 1. 拼接视图名字,找到对应的视图
  54. 1. 将数据渲染到视图
  55. 10. 视图解析器将解析的逻辑视图名传给DispatcherServlet
  56. 11. DispatcherServlet根据视图解析器解析的视图结果,调用具体的视图。
  57. 12. 最终视图呈现给用户。
  58. 在这里先听一遍原理,不理解没有关系,我们马上来写一个对应的代码实现大家就明白了,如果不明白,那就写10遍,没有笨人,只有懒人!
  59. 在上一节中,我们讲解了 什么是SpringMVC以及它的执行原理!
  60. [狂神说SpringMVC01:什么是SpringMVC](http://mp.weixin.qq.com/s?__biz=Mzg2NTAzMTExNg==&mid=2247483970&idx=1&sn=352e571ee88957ce391e972344e2a3d7&chksm=ce6104e1f9168df7f98eea39bd8478bb5082853ec8727c9da58c894625c43d44ebd64d36e2a8&scene=21#wechat_redirect)
  61. 现在我们来看看如何快速使用SpringMVC编写我们的程序吧!
  62. <a name="f0c3f0e0"></a>
  63. ### 配置版
  64. 1、新建一个Moudle springmvc-02-hello 添加web的支持!
  65. 2、确定导入了SpringMVC 的依赖!
  66. 3、配置web.xml 注册DispatcherServlet
  67. ```xml
  68. <?xml version="1.0" encoding="UTF-8"?>
  69. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  70. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  71. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  72. version="4.0">
  73. <!--1.注册DispatcherServlet-->
  74. <servlet>
  75. <servlet-name>springmvc</servlet-name>
  76. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  77. <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
  78. <init-param>
  79. <param-name>contextConfigLocation</param-name>
  80. <param-value>classpath:springmvc-servlet.xml</param-value>
  81. </init-param>
  82. <!--启动级别-1-->
  83. <load-on-startup>1</load-on-startup>
  84. </servlet>
  85. <!--/ 匹配所有的请求;(不包括.jsp)-->
  86. <!--/* 匹配所有的请求;(包括.jsp)-->
  87. <servlet-mapping>
  88. <servlet-name>springmvc</servlet-name>
  89. <url-pattern>/</url-pattern>
  90. </servlet-mapping>
  91. </web-app>

4、编写SpringMVC 的 配置文件!名称:springmvc-servlet.xml : [servletname]-servlet.xml

说明,这里的名称要求是按照官方来的

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. </beans>

5、添加 处理映射器

  1. <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

6、添加 处理器适配器

  1. <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

7、添加 视图解析器

  1. <!--视图解析器:DispatcherServlet给他的ModelAndView-->
  2. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
  3. <!--前缀-->
  4. <property name="prefix" value="/WEB-INF/jsp/"/>
  5. <!--后缀-->
  6. <property name="suffix" value=".jsp"/>
  7. </bean>

8、编写我们要操作业务Controller ,要么实现Controller接口,要么增加注解;需要返回一个ModelAndView,装数据,封视图;

  1. package com.zzb.controller;
  2. import org.springframework.web.servlet.ModelAndView;
  3. import org.springframework.web.servlet.mvc.Controller;
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6. //注意:这里我们先导入Controller接口
  7. public class HelloController implements Controller {
  8. @Override
  9. public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
  10. //ModelAndView 模型和视图
  11. ModelAndView mv = new ModelAndView();
  12. //封装对象,放在ModelAndView中。Model
  13. mv.addObject("msg","HelloSpringMVC!");
  14. // 封装要跳转的视图,放在ModelAndView中
  15. mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp
  16. return mv; }
  17. }

9、将自己的类交给SpringIOC容器,注册bean

  1. <!--Handler-->
  2. <bean id="/hello" class="com.zzb.controller.HelloController"/>

10、写要跳转的jsp页面,显示ModelandView存放的数据,以及我们的正常页面;

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>Title</title>
  5. </head>
  6. <body>
  7. ${msg}
  8. </body>
  9. </html>

11、配置Tomcat 启动测试!

SpringMVC狂神说最全笔记 - 图4

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

  1. 查看控制台输出,看一下是不是缺少了什么jar包。
  2. 如果jar包存在,显示无法输出,就在IDEA的项目发布中,添加lib依赖!
  3. 重启Tomcat 即可解决!

小结:看这个估计大部分同学都能理解其中的原理了,但是我们实际开发才不会这么写,不然就疯了,还学这个玩意干嘛!我们来看个注解版实现,这才是SpringMVC的精髓,到底有多么简单,看这个图就知道了。

SpringMVC狂神说最全笔记 - 图5

注解版

1. 新建一个Moudle,springmvc-03-hello-annotation 。添加web支持!

2. 由于Maven可能存在资源过滤的问题,我们将配置完善

  1. <build>
  2. <!--处理资源导出问题-->
  3. <resources>
  4. <resource>
  5. <directory>src/main/java</directory>
  6. <includes>
  7. <include>**/*.properties</include>
  8. <include>**/*.xml</include>
  9. </includes>
  10. <filtering>false</filtering>
  11. </resource>
  12. <resource>
  13. <directory>src/main/resources</directory>
  14. <includes>
  15. <include>**/*.properties</include>
  16. <include>**/*.xml</include>
  17. </includes>
  18. <filtering>false</filtering>
  19. </resource>
  20. </resources>
  21. </build>

3. 在pom.xml文件引入相关的依赖:主要有Spring框架核心库、Spring MVC、servlet , JSTL等。我们在父依赖中已经引入了!

4. 配置web.xml

注意点:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  5. version="4.0">
  6. <!--1.注册DispatcherServlet-->
  7. <servlet>
  8. <servlet-name>springmvc</servlet-name>
  9. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10. <!--关联一个springmvc的配置文件:【servlet-name】-servlet.xml-->
  11. <init-param>
  12. <param-name>contextConfigLocation</param-name>
  13. <param-value>classpath:springmvc-servlet.xml</param-value>
  14. </init-param>
  15. <!--启动级别-1: 服务器一启动就开始启动-->
  16. <load-on-startup>1</load-on-startup>
  17. </servlet>
  18. <!--/ 匹配所有的请求;(不包括.jsp)-->
  19. <!--/* 匹配所有的请求;(包括.jsp)-->
  20. <servlet-mapping>
  21. <servlet-name>springmvc</servlet-name>
  22. <url-pattern>/</url-pattern>
  23. </servlet-mapping>
  24. </web-app>

/ 和 /* 的区别:< url-pattern > / </ url-pattern > 不会匹配到.jsp, 只针对我们编写的请求;即:.jsp 不会进入spring的 DispatcherServlet类 。< url-pattern > / </ url-pattern > 会匹配 .jsp,会出现返回 jsp视图 时再次进入spring的DispatcherServlet 类,导致找不到对应的controller所以报404错。

  • 注意web.xml版本问题,要最新版!
  • 注册DispatcherServlet
  • 关联SpringMVC的配置文件
  • 启动级别为1
  • 映射路径为 / 【不要用/*,会404】

5. 添加Spring MVC配置文件

  1. resource目录下添加springmvc-servlet.xml配置文件,配置的形式与Spring容器配置基本类似,为了支持基于注解的IOC,设置了自动扫描包的功能,具体配置信息如下:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context
  9. https://www.springframework.org/schema/context/spring-context.xsd
  10. http://www.springframework.org/schema/mvc
  11. https://www.springframework.org/schema/mvc/spring-mvc.xsd">
  12. <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
  13. <context:component-scan base-package="com.zzb.controller"/>
  14. <!-- 让Spring MVC不处理静态资源 -->
  15. <mvc:default-servlet-handler />
  16. <!-- 支持mvc注解驱动
  17. 在spring中一般采用@RequestMapping注解来完成映射关系
  18. 要想使@RequestMapping注解生效
  19. 必须向上下文中注册DefaultAnnotationHandlerMapping
  20. 和一个AnnotationMethodHandlerAdapter实例
  21. 这两个实例分别在类级别和方法级别处理。
  22. 而annotation-driven配置帮助我们自动完成上述两个实例的注入。 -->
  23. <mvc:annotation-driven />
  24. <!-- 视图解析器 -->
  25. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
  26. id="internalResourceViewResolver">
  27. <!-- 前缀 -->
  28. <property name="prefix" value="/WEB-INF/jsp/" />
  29. <!-- 后缀 -->
  30. <property name="suffix" value=".jsp" />
  31. </bean>
  32. </beans>
  1. 在视图解析器中我们把所有的视图都存放在/WEB-INF/目录下,这样可以保证视图安全,因为这个目录下的文件,客户端不能直接访问。
  • 让IOC的注解生效
  • 静态资源过滤 :HTML . JS . CSS . 图片 , 视频 …..
  • MVC的注解驱动
  • 配置视图解析器

6. 创建Controller

编写一个Java控制类:com.kuang.controller.HelloController , 注意编码规范

  1. package com.zzb.controller;
  2. import org.springframework.stereotype.Controller;
  3. import org.springframework.ui.Model;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @Controller
  7. @RequestMapping("/hello")
  8. //@RestController 不会被视图解析器解析
  9. public class HelloController {
  10. //真实访问地址 : 项目名/hello/hi
  11. @RequestMapping("/hi")
  12. public String hello(Model model){
  13. //封装数据
  14. model.addAttribute("msg","hello,springMVCAnnotation");
  15. return "hello"; //会被视图解析器处理
  16. }
  17. }
  • @Controller是为了让Spring IOC容器初始化时自动扫描到;
  • @RequestMapping是为了映射请求路径,这里因为类与方法上都有映射所以访问时应该是/HelloController/hello;
  • 方法中声明Model类型的参数是为了把Action中的数据带到视图中;
  • 方法返回的结果是视图的名称hello,加上配置文件中的前后缀变成WEB-INF/jsp/hello.jsp。

7. 创建视图层

在WEB-INF/ jsp目录中创建hello.jsp , 视图可以直接取出并展示从Controller带回的信息;

可以通过EL表示取出Model中存放的值,或者对象;

  1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  2. <html>
  3. <head>
  4. <title>SpringMVC</title>
  5. </head>
  6. <body>
  7. ${msg}
  8. </body>
  9. </html>

8. 配置Tomcat运行

配置Tomcat , 开启服务器 , 访问 对应的请求路径!

SpringMVC狂神说最全笔记 - 图6

OK,运行成功!

小结

实现步骤其实非常的简单:

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

使用springMVC必须配置的三大件:

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

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

再来回顾下原理吧~

SpringMVC狂神说最全笔记 - 图7

在上一节中,我们编写了我们的第一个SpringMVC程序!

狂神说SpringMVC02:第一个MVC程序

现在我们来看看里面的控制器和路径请求的具体内容吧!

控制器Controller

  • 控制器复杂提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现。
  • 控制器负责解析用户的请求并将其转换为一个模型。
  • 在Spring MVC中一个控制器类可以包含多个方法
  • 在Spring MVC中,对于Controller的配置方式有很多种

实现Controller接口

Controller是一个接口,在org.springframework.web.servlet.mvc包下,接口中只有一个方法;

  1. //实现该接口的类获得控制器功能
  2. public interface Controller {
  3. //处理请求且返回一个模型与视图对象
  4. ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
  5. }

测试

  1. 新建一个Moudle,springmvc-04-controller 。将刚才的03 拷贝一份, 我们进行操作!
    • 删掉HelloController
    • mvc的配置文件只留下 视图解析器!
  2. 编写一个Controller类,ControllerTest1

    1. //定义控制器
    2. //注意点:不要导错包,实现Controller接口,重写方法;
    3. public class ControllerTest1 implements Controller {
    4. public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
    5. //返回一个模型视图对象
    6. ModelAndView mv = new ModelAndView();
    7. mv.addObject("msg","Test1Controller");
    8. mv.setViewName("test");
    9. return mv;
    10. }
    11. }
  1. 编写完毕后,去Spring配置文件中注册请求的bean;name对应请求路径,class对应处理请求的类
    1. <bean name="/t1" class="com.kuang.controller.ControllerTest1"/>
  1. 编写前端test.jsp,注意在WEB-INF/jsp目录下编写,对应我们的视图解析器
    1. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    2. <html>
    3. <head>
    4. <title>Kuangshen</title>
    5. </head>
    6. <body>
    7. ${msg}
    8. </body>
    9. </html>
  1. 配置Tomcat运行测试,我这里没有项目发布名配置的就是一个 / ,所以请求不用加项目名,OK!
    SpringMVC狂神说最全笔记 - 图8

说明:

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

使用注解@Controller

注解等效:

  1. @controller 组件
  2. @Service service
  3. @Controller controller
  4. @Repository dao
  • @Controller注解类型用于声明Spring类的实例是一个控制器(在讲IOC时还提到了另外3个注解);
  • Spring可以使用扫描机制来找到应用程序中所有基于注解的控制器类,为了保证Spring能找到你的控制器,需要在配置文件中声明组件扫描。
    1. <!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
    2. <context:component-scan base-package="com.kuang.controller"/>
  • 增加一个ControllerTest2类,使用注解实现; ```java //@Controller注解的类会自动添加到Spring上下文中 @Controller public class ControllerTest2{

    //映射访问路径 @RequestMapping(“/t2”) public String index(Model model){

    1. //Spring MVC会自动实例化一个Model对象用于向视图中传值
    2. model.addAttribute("msg", "ControllerTest2");
    3. //返回视图位置
    4. return "test";

    }

}

  1. - 运行tomcat测试
  2. **可以发现,我们的两个请求都可以指向一个视图,但是页面结果的结果是不一样的,从这里可以看出视图是被复用的,而控制器与视图之间是弱偶合关系。**
  3. **注解方式是平时使用的最多的方式!**
  4. <a name="RequestMapping"></a>
  5. ### RequestMapping
  6. [**@RequestMapping **](/RequestMapping )** **
  7. - @RequestMapping注解用于映射url到控制器类或一个特定的处理程序方法。可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。
  8. - 为了测试结论更加准确,我们可以加上一个项目名测试 myweb
  9. - 只注解在方法上面
  10. ```java
  11. @Controller
  12. public class TestController {
  13. @RequestMapping("/h1")
  14. public String test(){
  15. return "test";
  16. }
  17. }


访问路径:http://localhost:8080 / 项目名 / h1

  • 同时注解类与方法
    1. @Controller
    2. @RequestMapping("/admin")
    3. public class TestController {
    4. @RequestMapping("/h1")
    5. public String test(){
    6. return "test";
    7. }
    8. }

    访问路径:http://localhost:8080 / 项目名/ admin /h1 , 需要先指定类的路径再指定方法的路径;

RestFul 风格

概念

Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

功能

资源:互联网所有的事物都可以被抽象为资源

资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。

分别对应 添加、 删除、修改、查询。

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

  1. [http://127.0.0.1/item/queryItem.action?id=1](http://127.0.0.1/item/queryItem.action?id=1) 查询,GET
  2. [http://127.0.0.1/item/saveItem.action](http://127.0.0.1/item/saveItem.action) 新增,POST
  3. [http://127.0.0.1/item/updateItem.action](http://127.0.0.1/item/updateItem.action) 更新,POST
  4. [http://127.0.0.1/item/deleteItem.action?id=1](http://127.0.0.1/item/deleteItem.action?id=1) 删除,GET或POST

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

  1. [http://127.0.0.1/item/1](http://127.0.0.1/item/1) 查询,GET
  2. [http://127.0.0.1/item](http://127.0.0.1/item) 新增,POST
  3. [http://127.0.0.1/item](http://127.0.0.1/item) 更新,PUT
  4. [http://127.0.0.1/item/1](http://127.0.0.1/item/1) 删除,DELETE

学习测试

  1. 在新建一个类 RestFulController
    1. @Controller
    2. public class RestFulController {
    3. }
  1. 在Spring MVC中可以使用 @PathVariable 注解,让方法参数的值对应绑定到一个URI模板变量上。
    ```java @Controller public class RestFulController {

    //映射访问路径 @RequestMapping(“/commit/{p1}/{p2}”) public String index(@PathVariable int p1, @PathVariable int p2, Model model){

    int result = p1+p2; //Spring MVC会自动实例化一个Model对象用于向视图中传值 model.addAttribute(“msg”, “结果:”+result); //返回视图位置 return “test”;

    }

}

  1. 3. 我们来测试请求查看下<br />![](https://mmbiz.qpic.cn/mmbiz_png/uJDAUKrGC7JOmNdhqNbrRK9XaseXIDsu5BqyAspPK6GlhgxeV1nS0RWPnUfVBuaiadicaicQepibic2EVkyDflUh3qQ/640?wx_fmt=png&tp=webp&wxfrom=5&wx_lazy=1&wx_co=1#crop=0&crop=0&crop=1&crop=1&id=mPqqT&originHeight=240&originWidth=735&originalType=binary&ratio=1&rotation=0&showTitle=false&status=done&style=none&title=)
  2. 4. 思考:使用路径变量的好处?
  3. 1. 使路径变得更加简洁;
  4. 1. 高效
  5. 1. 获得参数更加方便,框架会自动进行类型转换。
  6. 1. 通过路径变量的类型可以约束访问参数,如果类型不一样,则访问不到对应的请求方法,如这里访问是的路径是/commit/1/a,则路径与方法不匹配,而不会是参数转换失败。
  7. 1. 安全 隐藏参数详情
  8. 5. 我们来修改下对应的参数类型,再次测试
  9. ```java
  10. //映射访问路径
  11. @RequestMapping("/commit/{p1}/{p2}")
  12. public String index(@PathVariable int p1, @PathVariable String p2, Model model){
  13. String result = p1+p2;
  14. //Spring MVC会自动实例化一个Model对象用于向视图中传值
  15. model.addAttribute("msg", "结果:"+result);
  16. //返回视图位置
  17. return "test";
  18. }

使用method属性指定请求类型

用于约束请求的类型,可以收窄请求范围。指定请求谓词的类型如GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE等

我们来测试一下:

  • 增加一个方法
    1. //映射访问路径,必须是POST请求
    2. @RequestMapping(value = "/hello",method = {RequestMethod.POST})
    3. public String index2(Model model){
    4. model.addAttribute("msg", "hello!");
    5. return "test";
    6. }
  • 我们使用浏览器地址栏进行访问默认是Get请求,会报错405:
    SpringMVC狂神说最全笔记 - 图9
  • 如果将POST修改为GET则正常了;
    1. //映射访问路径,必须是Get请求
    2. @RequestMapping(value = "/hello",method = {RequestMethod.GET})
    3. public String index2(Model model){
    4. model.addAttribute("msg", "hello!");
    5. return "test";
    6. }

小结:

Spring MVC 的 @RequestMapping 注解能够处理 HTTP 请求的方法, 比如 GET, PUT, POST, DELETE 以及 PATCH。

所有的地址栏请求默认都会是 HTTP GET 类型的。

方法级别的注解变体有如下几个:组合注解

  1. @GetMapping
  2. @PostMapping
  3. @PutMapping
  4. @DeleteMapping
  5. @PatchMapping

@GetMapping 是一个组合注解,平时使用的会比较多!

它所扮演的是 @RequestMapping(method =RequestMethod.GET) 的一个快捷方式。

扩展:小黄鸭调试法

场景一:我们都有过向别人(甚至可能向完全不会编程的人)提问及解释编程问题的经历,但是很多时候就在我们解释的过程中自己却想到了问题的解决方案,然后对方却一脸茫然。

场景二:你的同行跑来问你一个问题,但是当他自己把问题说完,或说到一半的时候就想出答案走了,留下一脸茫然的你。

其实上面两种场景现象就是所谓的小黄鸭调试法(Rubber Duck Debuging),又称橡皮鸭调试法,它是我们软件工程中最常使用调试方法之一。

SpringMVC狂神说最全笔记 - 图10

此概念据说来自《程序员修炼之道》书中的一个故事,传说程序大师随身携带一只小黄鸭,在调试代码的时候会在桌上放上这只小黄鸭,然后详细地向鸭子解释每行代码,然后很快就将问题定位修复了。

在上一节中,我们了解了控制器和Restful风格操作

狂神说SpringMVC03:RestFul和控制器

现在我们来看看SpringMVC参数接收处理和结果跳转处理吧!

3、结果跳转方式

ModelAndView

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

页面 : {视图解析器前缀} + viewName +{视图解析器后缀}

  1. <!-- 视图解析器 -->
  2. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
  3. id="internalResourceViewResolver">
  4. <!-- 前缀 -->
  5. <property name="prefix" value="/WEB-INF/jsp/" />
  6. <!-- 后缀 -->
  7. <property name="suffix" value=".jsp" />
  8. </bean>

对应的controller类

  1. public class ControllerTest1 implements Controller {
  2. public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
  3. //返回一个模型视图对象
  4. ModelAndView mv = new ModelAndView();
  5. mv.addObject("msg","ControllerTest1");
  6. mv.setViewName("test");
  7. return mv;
  8. }
  9. }

ServletAPI

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

1、通过HttpServletResponse进行输出

2、通过HttpServletResponse实现重定向

3、通过HttpServletResponse实现转发

  1. @Controller
  2. public class ResultGo {
  3. @RequestMapping("/result/t1")
  4. public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
  5. rsp.getWriter().println("Hello,Spring BY servlet API");
  6. }
  7. @RequestMapping("/result/t2")
  8. public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
  9. rsp.sendRedirect("/index.jsp");
  10. }
  11. @RequestMapping("/result/t3")
  12. public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
  13. //转发
  14. req.setAttribute("msg","/result/t3");
  15. req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);
  16. }
  17. }

SpringMVC

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

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

  1. @Controller
  2. public class ResultSpringMVC {
  3. @RequestMapping("/rsm/t1")
  4. public String test1(){
  5. //转发
  6. return "/index.jsp";
  7. }
  8. @RequestMapping("/rsm/t2")
  9. public String test2(){
  10. //转发二
  11. return "forward:/index.jsp";
  12. }
  13. @RequestMapping("/rsm/t3")
  14. public String test3(){
  15. //重定向
  16. return "redirect:/index.jsp";
  17. }
  18. }

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

重定向 , 不需要视图解析器 , 本质就是重新请求一个新地方嘛 , 所以注意路径问题.

可以重定向到另外一个请求实现 .

  1. @Controller
  2. public class ResultSpringMVC2 {
  3. @RequestMapping("/rsm2/t1")
  4. public String test1(){
  5. //转发
  6. return "test";
  7. }
  8. @RequestMapping("/rsm2/t2")
  9. public String test2(){
  10. //重定向
  11. return "redirect:/index.jsp";
  12. //return "redirect:hello.do"; //hello.do为另一个请求/
  13. }
  14. }

4、数据处理

处理提交数据

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

提交数据 : http://localhost:8080/hello?name=kuangshen

处理方法 :

  1. @RequestMapping("/hello")
  2. public String hello(String name){
  3. System.out.println(name);
  4. return "hello";
  5. }

后台输出 : kuangshen

2、提交的域名称和处理方法的参数名不一致

提交数据 : http://localhost:8080/hello?username=kuangshen

处理方法 :

  1. //@RequestParam("username") : username提交的域的名称 .
  2. @RequestMapping("/hello")
  3. public String hello(@RequestParam("username") String name){
  4. System.out.println(name);
  5. return "hello";
  6. }

后台输出 : kuangshen

3、提交的是一个对象

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

1、实体类

  1. public class User {
  2. private int id;
  3. private String name;
  4. private int age;
  5. //构造
  6. //get/set
  7. //tostring()
  8. }

2、提交数据 : http://localhost:8080/mvc04/user?name=kuangshen&id=1&age=15

3、处理方法 :

  1. @Controller
  2. @RequestMapping("/user")
  3. public String user(User user){
  4. //localhost: 8080/user/t1?name=xxx;
  5. @GetMapping("/t1")
  6. public String test1(String name , Model model){
  7. //1. 接受前端参数
  8. System.out.println("接受的前端的参数为: " + name);
  9. //2. 将返回的结果传递给前端 , Model
  10. model.addAttribute("msg" + name);
  11. //3. 视图跳转
  12. return "test";
  13. }
  14. }

后台输出 : User { id=1, name=’kuangshen’, age=15 }

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

数据显示到前端

第一种 : 通过ModelAndView

我们前面一直都是如此 . 就不过多解释

  1. public class ControllerTest1 implements Controller {
  2. public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
  3. //返回一个模型视图对象
  4. ModelAndView mv = new ModelAndView();
  5. mv.addObject("msg","ControllerTest1");
  6. mv.setViewName("test");
  7. return mv;
  8. }
  9. }

第二种 : 通过ModelMap

ModelMap

  1. @RequestMapping("/hello")
  2. public String hello(@RequestParam("username") String name, ModelMap model){
  3. //封装要显示到视图中的数据
  4. //相当于req.setAttribute("name",name);
  5. model.addAttribute("name",name);
  6. System.out.println(name);
  7. return "hello";
  8. }

第三种 : 通过Model

Model

  1. @RequestMapping("/ct2/hello")
  2. public String hello(@RequestParam("username") String name, Model model){
  3. //封装要显示到视图中的数据
  4. //相当于req.setAttribute("name",name);
  5. model.addAttribute("msg",name);
  6. System.out.println(name);
  7. return "test";
  8. }

对比

就对于新手而言简单来说使用区别就是:

  1. Model 只有寥寥几个方法只适合用于储存数据,简化了新手对于Model对象的操作和理解;
  2. ModelMap 继承了 LinkedMap ,除了实现了自身的一些方法,同样的继承 LinkedMap 的方法和特性;
  3. ModelAndView 可以在储存数据的同时,可以进行设置返回的逻辑视图,进行控制展示层的跳转。

当然更多的以后开发考虑的更多的是性能和优化,就不能单单仅限于此的了解。

请使用80%的时间打好扎实的基础,剩下18%的时间研究框架,2%的时间去学点英文,框架的官方文档永远是最好的教程。

乱码问题

测试步骤:

1、我们可以在首页编写一个提交的表单

  1. <form action="/e/t" method="post">
  2. <input type="text" name="name">
  3. <input type="submit">
  4. </form>

2、后台编写对应的处理类

  1. @Controller
  2. public class Encoding {
  3. @RequestMapping("/e/t")
  4. public String test(Model model,String name){
  5. model.addAttribute("msg",name); //获取表单提交的值
  6. return "test"; //跳转到test页面显示输入的值
  7. }
  8. }

3、输入中文测试,发现乱码

SpringMVC狂神说最全笔记 - 图11

不得不说,乱码问题是在我们开发中十分常见的问题,也是让我们程序猿比较头大的问题!

以前乱码问题通过过滤器解决 , 而SpringMVC给我们提供了一个过滤器 , 可以在web.xml中配置 .

修改了xml文件需要重启服务器!

  1. <filter>
  2. <filter-name>encoding</filter-name>
  3. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  4. <init-param>
  5. <param-name>encoding</param-name>
  6. <param-value>utf-8</param-value>
  7. </init-param>
  8. </filter>
  9. <filter-mapping>
  10. <filter-name>encoding</filter-name>
  11. <url-pattern>/*</url-pattern>
  12. </filter-mapping>

但是我们发现 , 有些极端情况下.这个过滤器对get的支持不好 .

处理方法 :

1、修改tomcat配置文件 :设置编码!

  1. <Connector URIEncoding="utf-8" port="8080" protocol="HTTP/1.1"
  2. connectionTimeout="20000"
  3. redirectPort="8443" />

2、自定义过滤器

  1. package com.kuang.filter;
  2. import javax.servlet.*;
  3. import javax.servlet.http.HttpServletRequest;
  4. import javax.servlet.http.HttpServletRequestWrapper;
  5. import javax.servlet.http.HttpServletResponse;
  6. import java.io.IOException;
  7. import java.io.UnsupportedEncodingException;
  8. import java.util.Map;
  9. /**
  10. * 解决get和post请求 全部乱码的过滤器
  11. */
  12. public class GenericEncodingFilter implements Filter {
  13. @Override
  14. public void destroy() {
  15. }
  16. @Override
  17. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  18. //处理response的字符编码
  19. HttpServletResponse myResponse=(HttpServletResponse) response;
  20. myResponse.setContentType("text/html;charset=UTF-8");
  21. // 转型为与协议相关对象
  22. HttpServletRequest httpServletRequest = (HttpServletRequest) request;
  23. // 对request包装增强
  24. HttpServletRequest myrequest = new MyRequest(httpServletRequest);
  25. chain.doFilter(myrequest, response);
  26. }
  27. @Override
  28. public void init(FilterConfig filterConfig) throws ServletException {
  29. }
  30. }
  31. //自定义request对象,HttpServletRequest的包装类
  32. class MyRequest extends HttpServletRequestWrapper {
  33. private HttpServletRequest request;
  34. //是否编码的标记
  35. private boolean hasEncode;
  36. //定义一个可以传入HttpServletRequest对象的构造函数,以便对其进行装饰
  37. public MyRequest(HttpServletRequest request) {
  38. super(request);// super必须写
  39. this.request = request;
  40. }
  41. // 对需要增强方法 进行覆盖
  42. @Override
  43. public Map getParameterMap() {
  44. // 先获得请求方式
  45. String method = request.getMethod();
  46. if (method.equalsIgnoreCase("post")) {
  47. // post请求
  48. try {
  49. // 处理post乱码
  50. request.setCharacterEncoding("utf-8");
  51. return request.getParameterMap();
  52. } catch (UnsupportedEncodingException e) {
  53. e.printStackTrace();
  54. }
  55. } else if (method.equalsIgnoreCase("get")) {
  56. // get请求
  57. Map<String, String[]> parameterMap = request.getParameterMap();
  58. if (!hasEncode) { // 确保get手动编码逻辑只运行一次
  59. for (String parameterName : parameterMap.keySet()) {
  60. String[] values = parameterMap.get(parameterName);
  61. if (values != null) {
  62. for (int i = 0; i < values.length; i++) {
  63. try {
  64. // 处理get乱码
  65. values[i] = new String(values[i]
  66. .getBytes("ISO-8859-1"), "utf-8");
  67. } catch (UnsupportedEncodingException e) {
  68. e.printStackTrace();
  69. }
  70. }
  71. }
  72. }
  73. hasEncode = true;
  74. }
  75. return parameterMap;
  76. }
  77. return super.getParameterMap();
  78. }
  79. //取一个值
  80. @Override
  81. public String getParameter(String name) {
  82. Map<String, String[]> parameterMap = getParameterMap();
  83. String[] values = parameterMap.get(name);
  84. if (values == null) {
  85. return null;
  86. }
  87. return values[0]; // 取回参数的第一个值
  88. }
  89. //取所有值
  90. @Override
  91. public String[] getParameterValues(String name) {
  92. Map<String, String[]> parameterMap = getParameterMap();
  93. String[] values = parameterMap.get(name);
  94. return values;
  95. }
  96. }

这个也是我在网上找的一些大神写的,一般情况下,SpringMVC默认的乱码处理就已经能够很好的解决了!

然后在web.xml中配置这个过滤器即可!

乱码问题,需要平时多注意,在尽可能能设置编码的地方,都设置为统一编码 UTF-8!

5、整合SSM

环境要求

环境:

  • IDEA
  • MySQL 5.7.19
  • Tomcat 9
  • Maven 3.6

要求:

  • 需要熟练掌握MySQL数据库,Spring,JavaWeb及MyBatis知识,简单的前端知识;

结构

  • spring-dao.xml
    • 整合mybatis
      • 关联数据库文件 prperties
      • 配置数据库连接池
      • 配置sqlSessionFactory对象
        • 注入数据库连接池
        • 配置MyBaties全局配置文件:mybatis-config.xml
      • 配置扫描Dao接口包,动态实现Dao接口注入到spring容器中
        • 注入sqlSessionFactory
        • 给出需要扫描Dao接口包
  • spring-mvc.xml
    • 扫描包
    • 静态资源过滤
    • 注册驱动
    • 视图解析器
  • spring-service.xml
    • 扫描包
    • 手动配置bean
    • 事务管理
  • database.properties
    • 数据库连接
  • applicationContext
    • 整合以上
  • mybatis-config.xml
    • 设置别名
    • 扫描包
  • web.xml
    • servlet
    • 配置过滤器
    • session

数据库环境

创建一个存放书籍数据的数据库表

  1. CREATE DATABASE `ssmbuild`;
  2. USE `ssmbuild`;
  3. CREATE TABLE `books`(
  4. `bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书id',
  5. `bookName` VARCHAR(100) NOT NULL COMMENT '书名',
  6. `bookCounts` INT(11) NOT NULL COMMENT '数量',
  7. `detail` VARCHAR(200) NOT NULL COMMENT '描述',
  8. KEY `bookID`(`bookID`)
  9. )ENGINE=INNODB DEFAULT CHARSET=utf8;
  10. INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`) VALUES
  11. (1,'Java',1,'从入门到放弃'),
  12. (2,'MySQL',10,'从删库到跑路'),
  13. (3,'Linux',5,'从进门到进牢');

基本环境搭建

1、新建一Maven项目!ssmbuild , 添加web的支持

2、导入相关的pom依赖!

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.kuang</groupId>
  6. <artifactId>SSM-build1</artifactId>
  7. <version>1.0-SNAPSHOT</version>
  8. <packaging>war</packaging>
  9. <name>SSM-build1 Maven Webapp</name>
  10. <!-- FIXME change it to the project's website -->
  11. <url>http://www.example.com</url>
  12. <properties>
  13. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  14. <maven.compiler.source>1.7</maven.compiler.source>
  15. <maven.compiler.target>1.7</maven.compiler.target>
  16. </properties>
  17. <dependencies>
  18. <dependency>
  19. <groupId>junit</groupId>
  20. <artifactId>junit</artifactId>
  21. <version>4.11</version>
  22. <scope>test</scope>
  23. </dependency>
  24. <!--Mybatis部分-->
  25. <!--数据库驱动包-->
  26. <dependency>
  27. <groupId>mysql</groupId>
  28. <artifactId>mysql-connector-java</artifactId>
  29. <version>5.1.47</version>
  30. </dependency>
  31. <!--mybatis的包-->
  32. <dependency>
  33. <groupId>org.mybatis</groupId>
  34. <artifactId>mybatis</artifactId>
  35. <version>3.5.9</version>
  36. </dependency>
  37. <!--Mybatis部分完结-->
  38. <!--Spring部分-->
  39. <!--mybatis-srping整合包-->
  40. <dependency>
  41. <groupId>org.mybatis</groupId>
  42. <artifactId>mybatis-spring</artifactId>
  43. <version>2.0.6</version>
  44. </dependency>
  45. <!--第三方数据源:c3p0-->
  46. <dependency>
  47. <groupId>com.mchange</groupId>
  48. <artifactId>c3p0</artifactId>
  49. <version>0.9.5.5</version>
  50. </dependency>
  51. <!--spring系列-->
  52. <dependency>
  53. <groupId>org.springframework</groupId>
  54. <artifactId>spring-webmvc</artifactId>
  55. <version>5.3.15</version>
  56. </dependency>
  57. <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
  58. <dependency>
  59. <groupId>org.springframework</groupId>
  60. <artifactId>spring-jdbc</artifactId>
  61. <version>5.3.15</version>
  62. </dependency>
  63. <!--Spring部分完结-->
  64. <!--SpringMVC需要的前端和Servlet包-->
  65. <!--servlet-->
  66. <dependency>
  67. <groupId>javax.servlet</groupId>
  68. <artifactId>javax.servlet-api</artifactId>
  69. <version>4.0.1</version>
  70. </dependency>
  71. <!--jsp-->
  72. <dependency>
  73. <groupId>javax.servlet.jsp</groupId>
  74. <artifactId>jsp-api</artifactId>
  75. <version>2.2</version>
  76. </dependency>
  77. <!--jstl-->
  78. <dependency>
  79. <groupId>javax.servlet</groupId>
  80. <artifactId>jstl</artifactId>
  81. <version>1.2</version>
  82. </dependency>
  83. <!--Servlet - JSP -->
  84. <dependency>
  85. <groupId>javax.servlet</groupId>
  86. <artifactId>servlet-api</artifactId>
  87. <version>2.5</version>
  88. </dependency>
  89. <!--lombok-->
  90. <dependency>
  91. <groupId>org.projectlombok</groupId>
  92. <artifactId>lombok</artifactId>
  93. <version>1.18.22</version>
  94. <scope>provided</scope>
  95. </dependency>
  96. </dependencies>
  97. </project>

3、Maven资源过滤设置

  1. <build>
  2. <resources>
  3. <resource>
  4. <directory>src/main/java</directory>
  5. <includes>
  6. <include>**/*.properties</include>
  7. <include>**/*.xml</include>
  8. </includes>
  9. <filtering>false</filtering>
  10. </resource>
  11. <resource>
  12. <directory>src/main/resources</directory>
  13. <includes>
  14. <include>**/*.properties</include>
  15. <include>**/*.xml</include>
  16. </includes>
  17. <filtering>false</filtering>
  18. </resource>
  19. </resources>
  20. </build>

4、建立基本结构和配置框架!

  • com.kuang.pojo
  • com.kuang.dao
  • com.kuang.service
  • com.kuang.controller
  • mybatis-config.xml ```xml <?xml version=”1.0” encoding=”UTF-8” ?> <!DOCTYPE configuration
    1. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    2. "http://mybatis.org/dtd/mybatis-3-config.dtd">

  1. - applicationContext.xml
  2. ```xml
  3. <?xml version="1.0" encoding="UTF-8"?>
  4. <beans xmlns="http://www.springframework.org/schema/beans"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd">
  8. </beans>

Mybatis层编写

1、数据库配置文件 database.properties

  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=utf8
  3. # 如果要是使用mysql8.0以上 增加一个时区的配置; &serverTimezone=Asia/Beijing
  4. jdbc.username=root
  5. jdbc.password=123456

2、IDEA关联数据库

3、编写MyBatis的核心配置文件

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration
  3. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  5. <configuration>
  6. <!--可以添加日志 但是不加的话比较清楚-->
  7. <setting>
  8. <setting name="logImpl" value="STDOUT_LOGGING"/>
  9. </setting>
  10. <typeAliases>
  11. <package name="com.kuang.pojo"/>
  12. </typeAliases>
  13. <mappers>
  14. <mapper resource="com/kuang/dao/BookMapper.xml"/>
  15. <!-- 适用于类路径下,直接加载mybatis对应的映射文件,用/进行分割,对于文件名称和文件位置没有强制限制条件,比较灵活,不容易出错 -->
  16. <!-- 不建议使用 class
  17. <mapper class= "com.kuang.dao.BookMapper">
  18. 仅适用于类路径下,接口文件与映射文件在同一路径下,且接口名与映射文件名相同,并且映射文件命名为接口全类名的情况,使用.分割,有智能提示,限制条件较多,容易出错-->
  19. </mappers>
  20. </configuration>

4、编写数据库对应的实体类 com.kuang.pojo.Books

使用lombok插件!

  1. package com.kuang.pojo;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.NoArgsConstructor;
  5. @Data
  6. @AllArgsConstructor
  7. @NoArgsConstructor
  8. public class Books {
  9. private int bookID;
  10. private String bookName;
  11. private int bookCounts;
  12. private String detail;
  13. }

5、编写Dao层的 Mapper接口!

  1. package com.kuang.dao;
  2. import com.kuang.pojo.Books;
  3. import java.util.List;
  4. public interface BookMapper {
  5. //增加一个Book
  6. int addBook(Books book);
  7. //根据id删除一个Book
  8. int deleteBookById(@Param("bookID") int id);
  9. //更新Book
  10. int updateBook(Books books);
  11. //根据id查询,返回一个Book
  12. Books queryBookById(@Param("bookID") int id);
  13. //查询全部Book,返回list集合
  14. List<Books> queryAllBook();
  15. }

6、编写接口对应的 Mapper.xml 文件。需要导入MyBatis的包;

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper
  3. PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  4. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="com.kuang.dao.BookMapper">
  6. <!--增加一个Book-->
  7. <insert id="addBook" parameterType="Books">
  8. insert into ssmbuild.books(bookName,bookCounts,detail)
  9. values (#{bookName}, #{bookCounts}, #{detail})
  10. </insert>
  11. <!--根据id删除一个Book-->
  12. <delete id="deleteBookById" parameterType="int">
  13. delete from ssmbuild.books where bookID=#{bookID}
  14. </delete>
  15. <!--更新Book-->
  16. <update id="updateBook" parameterType="Books">
  17. update ssmbuild.books
  18. set bookName = #{bookName},bookCounts = #{bookCounts},detail = #{detail}
  19. where bookID = #{bookID}
  20. </update>
  21. <!--根据id查询,返回一个Book-->
  22. <select id="queryBookById" resultType="Books">
  23. select * from ssmbuild.books
  24. where bookID = #{bookID}
  25. </select>
  26. <!--查询全部Book-->
  27. <select id="queryAllBook" resultType="Books">
  28. SELECT * from ssmbuild.books
  29. </select>
  30. </mapper>

7、编写Service层的接口和实现类

接口:

  1. package com.kuang.service;
  2. import com.kuang.pojo.Books;
  3. import java.util.List;
  4. //BookService:底下需要去实现,调用dao层
  5. public interface BookService {
  6. //增加一个Book
  7. int addBook(Books book);
  8. //根据id删除一个Book
  9. int deleteBookById(int id);
  10. //更新Book
  11. int updateBook(Books books);
  12. //根据id查询,返回一个Book
  13. Books queryBookById(int id);
  14. //查询全部Book,返回list集合
  15. List<Books> queryAllBook();
  16. }

实现类:

  1. package com.kuang.service;
  2. import com.kuang.dao.BookMapper;
  3. import com.kuang.pojo.Books;
  4. import java.util.List;
  5. public class BookServiceImpl implements BookService {
  6. //service层调用dao层的操作,设置一个set接口,方便Spring管理
  7. private BookMapper bookMapper;
  8. public void setBookMapper(BookMapper bookMapper) {
  9. this.bookMapper = bookMapper;
  10. }//set方法Spring就可以注入了
  11. public int addBook(Books book) {
  12. return bookMapper.addBook(book);
  13. }
  14. public int deleteBookById(int id) {
  15. return bookMapper.deleteBookById(id);
  16. }
  17. public int updateBook(Books books) {
  18. return bookMapper.updateBook(books);
  19. }
  20. public Books queryBookById(int id) {
  21. return bookMapper.queryBookById(id);
  22. }
  23. public List<Books> queryAllBook() {
  24. return bookMapper.queryAllBook();
  25. }
  26. }

OK,到此,底层需求操作编写完毕!

Spring层

1、配置Spring整合MyBatis,我们这里数据源使用c3p0连接池;

2、我们去编写Spring整合Mybatis的相关的配置文件;spring-dao.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/context
  8. https://www.springframework.org/schema/context/spring-context.xsd">
  9. <!-- 配置整合mybatis -->
  10. <!-- 1.关联数据库文件 -->
  11. <context:property-placeholder location="classpath:database.properties"/>
  12. <!-- 2.数据库连接池 -->
  13. <!--数据库连接池
  14. dbcp 半自动化操作 不能自动连接
  15. c3p0 自动化操作(自动的加载配置文件 并且设置到对象里面)
  16. -->
  17. <!--<bean id="dataSource" class="java.sql.DriverManager"></bean>-->
  18. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
  19. <!-- 配置连接池属性 -->
  20. <property name="driverClass" value="${jdbc.driver}"/>
  21. <property name="jdbcUrl" value="${jdbc.url}"/>
  22. <property name="user" value="${jdbc.username}"/>
  23. <property name="password" value="${jdbc.password}"/>
  24. <!-- c3p0连接池的私有属性 -->
  25. <!-- 设置最大连接大小 -->
  26. <property name="maxPoolSize" value="30"/>
  27. <!-- 设置最小连接大小 -->
  28. <property name="minPoolSize" value="10"/>
  29. <!-- 关闭连接后不自动commit -->
  30. <property name="autoCommitOnClose" value="false"/>
  31. <!-- 获取连接超时时间 -->
  32. <property name="checkoutTimeout" value="10000"/>
  33. <!-- 当获取连接失败重试次数 -->
  34. <property name="acquireRetryAttempts" value="2"/>
  35. </bean>
  36. <!-- 3.配置SqlSessionFactory对象 -->
  37. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  38. <!-- 注入数据库连接池 -->
  39. <property name="dataSource" ref="dataSource"/>
  40. <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
  41. <property name="configLocation" value="classpath:mybatis-config.xml"/>
  42. </bean>
  43. <!-- 4.配置扫描Dao接口包,动态实现Dao接口注入到spring容器中 -->
  44. <!--解释 :https://www.cnblogs.com/jpfss/p/7799806.html-->
  45. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  46. <!-- 注入sqlSessionFactory -->
  47. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
  48. <!-- 给出需要扫描Dao接口包 -->
  49. <property name="basePackage" value="com.kuang.dao"/>
  50. </bean>
  51. </beans>

3、Spring整合service层

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/context
  8. http://www.springframework.org/schema/context/spring-context.xsd">
  9. <!-- 1.扫描service相关的bean -->
  10. <context:component-scan base-package="com.kuang.service" />
  11. <!-- 2.将所有的业务类,注入到Spring,可以通过配置,或者注解实现.(BookServiceImpl注入到IOC容器中)-->
  12. <bean id="BookServiceImpl" class="com.kuang.service.BookServiceImpl">
  13. <property name="bookMapper" ref="bookMapper"/>
  14. </bean>
  15. <!-- 3.声明式配置事务管理器 -->
  16. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  17. <!-- 注入数据库连接池(注入数据源) -->
  18. <property name="dataSource" ref="dataSource" />
  19. </bean>
  20. </beans>

Spring层搞定!再次理解一下,Spring就是一个大杂烩,一个容器!对吧!

SpringMVC层

1、web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  5. version="4.0">
  6. <!--DispatcherServlet-->
  7. <servlet>
  8. <servlet-name>DispatcherServlet</servlet-name>
  9. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  10. <init-param>
  11. <param-name>contextConfigLocation</param-name>
  12. <!--一定要注意:我们这里加载的是总的配置文件,之前被这里坑了!-->
  13. <param-value>classpath:applicationContext.xml</param-value>
  14. </init-param>
  15. <load-on-startup>1</load-on-startup>
  16. </servlet>
  17. <servlet-mapping>
  18. <servlet-name>DispatcherServlet</servlet-name>
  19. <url-pattern>/</url-pattern>
  20. </servlet-mapping>
  21. <!--encodingFilter-->
  22. <filter>
  23. <filter-name>encodingFilter</filter-name>
  24. <filter-class>
  25. org.springframework.web.filter.CharacterEncodingFilter
  26. </filter-class>
  27. <init-param>
  28. <param-name>encoding</param-name>
  29. <param-value>utf-8</param-value>
  30. </init-param>
  31. </filter>
  32. <filter-mapping>
  33. <filter-name>encodingFilter</filter-name>
  34. <url-pattern>/*</url-pattern>
  35. </filter-mapping>
  36. <!--Session过期时间-->
  37. <session-config>
  38. <session-timeout>15</session-timeout>
  39. </session-config>
  40. </web-app>

排错思路

步骤:

  1. 1. 查看这个bean是否注入成功
  2. 2. Junit单元测试类,看我们的代码是否能够查询出来结果
  3. 3. 问题,一定不在我们的底层 Spring出了问题
  4. 4. SpringMVC, 整合的时候没有调用我们的service层的bean;
  5. 1. applicantionContext.xml 没有注入bean
  6. 2. web.xml 中,我们也绑定过配置文件! 发现问题 我们配置的是Spring-mvc.xml 这里面确实没有service bean 所以报空指针

2、spring-mvc.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context.xsd
  10. http://www.springframework.org/schema/mvc
  11. https://www.springframework.org/schema/mvc/spring-mvc.xsd">
  12. <!-- 配置SpringMVC -->
  13. <!-- 1.开启SpringMVC注解驱动 -->
  14. <mvc:annotation-driven />
  15. <!-- 2.静态资源默认servlet配置(静态资源过滤)-->
  16. <mvc:default-servlet-handler/>
  17. <!-- 3.配置jsp 显示ViewResolver视图解析器 -->
  18. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  19. <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
  20. <property name="prefix" value="/WEB-INF/jsp/" />
  21. <property name="suffix" value=".jsp" />
  22. </bean>
  23. <!-- 4.扫描web相关的bean -->
  24. <context:component-scan base-package="com.kuang.controller" />
  25. </beans>

3、Spring配置整合文件,applicationContext.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans
  5. http://www.springframework.org/schema/beans/spring-beans.xsd">
  6. <import resource="spring-dao.xml"/>
  7. <import resource="spring-service.xml"/>
  8. <import resource="spring-mvc.xml"/>
  9. <!-- 整合三个容器 -->
  10. </beans>

配置文件,暂时结束!Controller 和 视图层编写

Controller 和 视图层编写

1、BookController 类编写 , 方法一:查询全部书籍

  1. @Controller
  2. @RequestMapping("/book")
  3. public class BookController {
  4. //controller层调用service层
  5. @Autowired
  6. @Qualifier("BookServiceImpl")
  7. private BookService bookService;
  8. //查询全部书籍,并且返回带一个书籍展示页面
  9. @RequestMapping("/allBook")
  10. public String list(Model model) {
  11. List<Books> list = bookService.queryAllBook();
  12. model.addAttribute("list", list);
  13. return "allBook";
  14. }
  15. }

2、编写首页 index.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
  2. <!DOCTYPE HTML>
  3. <html>
  4. <head>
  5. <title>首页</title>
  6. <style type="text/css">
  7. a {
  8. text-decoration: none;
  9. color: black;
  10. font-size: 18px;
  11. }
  12. h3 {
  13. width: 180px;
  14. height: 38px;
  15. margin: 100px auto;
  16. text-align: center;
  17. line-height: 38px;
  18. background: deepskyblue;
  19. border-radius: 4px;
  20. }
  21. </style>
  22. </head>
  23. <body>
  24. <h3>
  25. <a href="${pageContext.request.contextPath}/book/allBook">点击进入列表页</a>
  26. </h3>
  27. </body>
  28. </html>

3、书籍列表页面 allbook.jsp

  1. <taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" />
  2. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  3. <html>
  4. <head>
  5. <title>书籍列表</title>
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <!-- 引入 Bootstrap -->
  8. <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  9. </head>
  10. <body>
  11. <div class="container">
  12. <div class="row clearfix">
  13. <div class="col-md-12 column">
  14. <div class="page-header">
  15. <h1>
  16. <small>书籍列表 —— 显示所有书籍</small>
  17. </h1>
  18. </div>
  19. </div>
  20. </div>
  21. <div class="row">
  22. <div class="col-md-4 column">
  23. <a class="btn btn-primary" href="${pageContext.request.contextPath}/book/toAddBook">新增</a>
  24. </div>
  25. </div>
  26. <div class="row clearfix">
  27. <div class="col-md-12 column">
  28. <table class="table table-hover table-striped">
  29. <thead>
  30. <tr>
  31. <th>书籍编号</th>
  32. <th>书籍名字</th>
  33. <th>书籍数量</th>
  34. <th>书籍详情</th>
  35. <th>操作</th>
  36. </tr>
  37. </thead>
  38. <tbody>
  39. <c:forEach var="book" items="${requestScope.get('list')}">
  40. <tr>
  41. <td>${book.getBookID()}</td>
  42. <td>${book.getBookName()}</td>
  43. <td>${book.getBookCounts()}</td>
  44. <td>${book.getDetail()}</td>
  45. <td>
  46. <a href="${pageContext.request.contextPath}/book/toUpdateBook?id=${book.getBookID()}">更改</a>
  47. &nbsp; | &nbsp;
  48. <a href="${pageContext.request.contextPath}/book/del/${book.getBookID()}">删除</a>
  49. </td>
  50. </tr>
  51. </c:forEach>
  52. </tbody>
  53. </table>
  54. </div>
  55. </div>
  56. </div>

4、BookController 类编写 , 方法二:添加书籍

  1. //跳转到添加书籍界面
  2. @RequestMapping("/toAddBook")
  3. public String toAddPaper() {
  4. return "addBook";
  5. }
  6. //添加书籍的请求
  7. @RequestMapping("/addBook")
  8. public String addPaper(Books books) {
  9. System.out.println(books);
  10. bookService.addBook(books);
  11. return "redirect:/book/allBook";
  12. }

5、添加书籍页面:addBook.jsp

  1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  2. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  3. <html>
  4. <head>
  5. <title>新增书籍</title>
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <!-- 引入 Bootstrap -->
  8. <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  9. </head>
  10. <body>
  11. <div class="container">
  12. <div class="row clearfix">
  13. <div class="col-md-12 column">
  14. <div class="page-header">
  15. <h1>
  16. <small>新增书籍</small>
  17. </h1>
  18. </div>
  19. </div>
  20. </div>
  21. <form action="${pageContext.request.contextPath}/book/addBook" method="post">
  22. <div class="form-group">
  23. <label>书籍名称:</label>
  24. <input type="text" name="bookName" class="form-control" required>
  25. <!-- 这里的name要和实体类的属性一样 否则报none-->
  26. </div>
  27. <div class="form-group">
  28. <label>书籍数量:</label>
  29. <input type="text" name="bookCounts" class="form-control" required>
  30. </div>
  31. <div class="form-group">
  32. <label>书籍描述:</label>
  33. <input type="text" name="detail" class="form-control" required>
  34. </div>
  35. <div class="form-group">
  36. <input type="submit" class="form-control" value="添加">
  37. </div>
  38. </form>
  39. </div>

6、BookController 类编写 , 方法三:修改书籍

  1. //跳转到修改页面
  2. @RequestMapping("/toUpdateBook")
  3. public String toUpdateBook(Model model, int id) {
  4. Books books = bookService.queryBookById(id);
  5. System.out.println(books);
  6. model.addAttribute("book",books );
  7. return "updateBook";
  8. }
  9. //修改书籍
  10. @RequestMapping("/updateBook")
  11. public String updateBook(Model model, Books book) {
  12. System.out.println(book);
  13. bookService.updateBook(book);
  14. Books books = bookService.queryBookById(book.getBookID());
  15. model.addAttribute("books", books);
  16. return "redirect:/book/allBook";
  17. }

7、修改书籍页面 updateBook.jsp

  1. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  2. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  3. <html>
  4. <head>
  5. <title>修改信息</title>
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <!-- 引入 Bootstrap -->
  8. <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  9. </head>
  10. <body>
  11. <div class="container">
  12. <div class="row clearfix">
  13. <div class="col-md-12 column">
  14. <div class="page-header">
  15. <h1>
  16. <small>修改信息</small>
  17. </h1>
  18. </div>
  19. </div>
  20. </div>
  21. <form action="${pageContext.request.contextPath}/book/updateBook" method="post">
  22. <%--
  23. 出现的问题:我们提交了修改的sql请求,但是修改失败,初次考虑,是事务问题.配置完毕事务依旧失败
  24. 看一下sql语句,是否执行成功: Sql执行失败,修改未完成
  25. 修改 : 前端传递隐藏域
  26. --%>
  27. <input type="hidden" name="bookID" value="${book.bookID}">
  28. <div class="form-group">
  29. <label>书籍名称:</label>
  30. <input type="text" name="bookName" class="form-control" value="${book.bookName})" required>
  31. <!-- 这里的name要和实体类的属性一样 否则报none-->
  32. </div>
  33. <div class="form-group">
  34. <label>书籍数量:</label>
  35. <input type="text" name="bookCounts" class="form-control" value="${book.bookCount
  36. s})" required>
  37. </div>
  38. <div class="form-group">
  39. <label>书籍描述:</label>
  40. <input type="text" name="detail" class="form-control" value="${book.detail})" required>
  41. </div>
  42. <div class="form-group">
  43. <input type="submit" class="form-control" value="添加">
  44. </div>
  45. </form>
  46. </div>

8、BookController 类编写 , 方法四:删除书籍

  1. @RequestMapping("/del/{bookId}")
  2. public String deleteBook(@PathVariable("bookId") int id) {
  3. bookService.deleteBookById(id);
  4. return "redirect:/book/allBook";
  5. }

配置Tomcat,进行运行!

到目前为止,这个SSM项目整合已经完全的OK了,可以直接运行进行测试!这个练习十分的重要,大家需要保证,不看任何东西,自己也可以完整的实现出来!

新增查询功能

项目结构图

SpringMVC狂神说最全笔记 - 图12

SpringMVC狂神说最全笔记 - 图13

小结及展望

这个是同学们的第一个SSM整合案例,一定要烂熟于心!

SSM框架的重要程度是不言而喻的,学到这里,大家已经可以进行基本网站的单独开发。但是这只是增删改查的基本操作。可以说学到这里,大家才算是真正的步入了后台开发的门。也就是能找一个后台相关工作的底线。

或许很多人,工作就做这些事情,但是对于个人的提高来说,还远远不够!

我们后面还要学习一些 SpringMVC 的知识!

  • Ajax 和 Json
  • 文件上传和下载
  • 拦截器

6. 什么是JSON?

  • JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式,目前使用特别广泛。
  • 采用完全独立于编程语言的文本格式来存储和表示数据。
  • 简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。
  • 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

在 JavaScript 语言中,一切都是对象。因此,任何JavaScript 支持的类型都可以通过 JSON 来表示,例如字符串、数字、对象、数组等。看看他的要求和语法格式:

  • 对象表示为键值对,数据由逗号分隔
  • 花括号保存对象
  • 方括号保存数组

JSON 键值对是用来保存 JavaScript 对象的一种方式,和 JavaScript 对象的写法也大同小异,键/值对组合中的键名写在前面并用双引号 “” 包裹,使用冒号 : 分隔,然后紧接着值:

  1. {"name": "QinJiang"}
  2. {"age": "3"}
  3. {"sex": "男"}

很多人搞不清楚 JSON 和 JavaScript 对象的关系,甚至连谁是谁都不清楚。其实,可以这么理解:

JSON 是 JavaScript 对象的字符串表示法,它使用文本表示一个 JS 对象的信息,本质是一个字符串。

  1. var obj = {a: 'Hello', b: 'World'}; //这是一个对象,注意键名也是可以使用引号包裹的
  2. var json = '{"a": "Hello", "b": "World"}'; //这是一个 JSON 字符串,本质是一个字符串

JSON 和 JavaScript 对象互转

要实现从JSON字符串转换为JavaScript 对象,使用 JSON.parse() 方法:

  1. var obj = JSON.parse('{"a": "Hello", "b": "World"}');
  2. //结果是 {a: 'Hello', b: 'World'}

要实现从JavaScript 对象转换为JSON字符串,使用 JSON.stringify() 方法:

var json = JSON.stringify({a: 'Hello', b: 'World'});
//结果是 '{"a": "Hello", "b": "World"}'

代码测试

1、新建一个module ,springmvc-05-json , 添加web的支持

2、在web目录下新建一个 json-1.html , 编写测试内容

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>JSON_秦疆</title>
</head>
<body>

<script type="text/javascript">
   //编写一个js的对象
   var user = {
       name:"秦疆",
       age:3,
       sex:"男"
  };
   //将js对象转换成json字符串
   var str = JSON.stringify(user);
   console.log(str);

   //将json字符串转换为js对象
   var user2 = JSON.parse(str);
   console.log(user2.age,user2.name,user2.sex);

</script>

</body>
</html>

3、在IDEA中使用浏览器打开,查看控制台输出!

SpringMVC狂神说最全笔记 - 图14

Controller返回JSON数据

Jackson应该是目前比较好的json解析工具了

当然工具不止这一个,比如还有阿里巴巴的 fastjson 等等。

我们这里使用Jackson,使用它需要导入它的jar包;

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

配置SpringMVC需要的配置

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         id="WebApp_ID" version="3.0">

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath: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>myFilter</filter-name>
    <!--<filter-class>com.kuang.filter.GenericEncodingFilter</filter-class>-->
    <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>
  <!--/*  包括.jsp-->
  <filter-mapping>
    <filter-name>myFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


</web-app>

springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">


    <context:component-scan base-package="com.kuang.controller"/>
    <mvc:default-servlet-handler/>

    <!--JSON格式乱码处理方式-->
    <mvc:annotation-driven>
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                <property name="objectMapper">
                    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                        <property name="failOnEmptyBeans" value="false"/>
                    </bean>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

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


</beans>

我们随便编写一个User的实体类,然后我们去编写我们的测试Controller;

package com.kuang.pojo;


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

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

这里我们需要两个新东西,一个是@ResponseBody,一个是ObjectMapper对象,我们看下具体的用法

编写一个Controller;

package com.kuang.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kuang.pojo.User;
import com.kuang.utils.JsonUtils;
import com.sun.xml.internal.ws.developer.SerializationFeature;
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.ArrayList;
import java.util.Date;
import java.util.List;

@Controller  //经过视图解析器
//@RestController  只返回字符串
public class UserController {

    @RequestMapping("/json1")
    //思考问题,我们正常返回他会走视图解析器,而json需要返回的是一个字符串;
    //市面上有很多的第三方jar包可以实现这个功能,jackson.只需要一个简单的注解就可以实现了;
    //@ResponseBody , 将服务器端返回的对象转换为json对象响应回去;
    @ResponseBody //和@Controller配合使用
    public String json1() throws JsonProcessingException {
        //需要一个jackson的对象映射器,就是一个类,使用它可以直接将对象转换为json字符串;
        ObjectMapper mapper = new ObjectMapper();

        //创建一个对象
        User user = new User("秦疆1号",1,"男");
        System.out.println(user);

        //将Java对象转换为json字符串;
        String str = mapper.writeValueAsString(user);
        System.out.println(str);

        return str; //由于使用了@ResponseBody注解,这里会将str以json格式的字符串返回,十分方便;
    }

    //发现一个问题,乱码了,怎么解决?给@RequestMapping加一个属性
    //发现出现了乱码问题,我们需要设置一下他的编码格式为utf-8,以及它返回的类型;
    // 通过@RequestMaping的produces属性来实现,修改下代码
    //produces:指定响应体返回类型和编码
    @RequestMapping(value = "/json2",produces = "application/json;charset=utf-8")
    @ResponseBody //不会走视图解析器,会直接给返回一个字符串
    public String json2() throws JsonProcessingException {

        User user = new User("秦疆1号",1,"男");

        return new ObjectMapper().writeValueAsString(user);
    }

    @RequestMapping(value = "/json3")
    @ResponseBody
    public String json3() throws JsonProcessingException {

        List<User> list = new ArrayList<>();

        User user1 = new User("秦疆1号",1,"男");
        User user2 = new User("秦疆2号",1,"男");
        User user3 = new User("秦疆3号",1,"男");
        User user4 = new User("秦疆4号",1,"男");
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);

        return new ObjectMapper().writeValueAsString(list);
    }

    @RequestMapping(value = "/time1")
    @ResponseBody
    public String json4() throws JsonProcessingException {

        Date date = new Date();
        System.out.println(date);
        //发现问题:时间默认返回的json字符串变成了时间戳的格式:1564711481926 Timestamp。

        return new ObjectMapper().writeValueAsString(date);
    }

    @RequestMapping(value = "/time2")
    @ResponseBody
    public String json5() throws JsonProcessingException {

        ObjectMapper mapper = new ObjectMapper();
        //1.如何让他不返回时间戳!所以我们要关闭它的时间戳功能
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        //2.时间格式化问题!自定日期格式对象;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //3.让mapper指定时间日期格式为simpleDateFormat;
        mapper.setDateFormat(sdf);

        //写一个日期对象
        Date date = new Date();

        return mapper.writeValueAsString(date);
    }

    //发现问题,重复代码太多,给它编写一个工具类;
    @RequestMapping(value = "/time3")
    @ResponseBody
    public String json6() throws JsonProcessingException {
        return JsonUtils.getJson(new Date());
    }

}

配置Tomcat , 启动测试一下!

http://localhost:8080/json1

SpringMVC狂神说最全笔记 - 图15

发现出现了乱码问题,我们需要设置一下他的编码格式为utf-8,以及它返回的类型;

通过@RequestMaping的produces属性来实现,修改下代码

//produces:指定响应体返回类型和编码
@RequestMapping(value = "/json1",produces = "application/json;charset=utf-8")

再次测试, http://localhost:8080/json1 , 乱码问题OK!

【注意:使用json记得处理乱码问题】

代码优化(乱码)

乱码统一解决

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

我们可以在springmvc的配置文件上添加一段消息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>

返回json字符串统一解决

在类上直接使用 @RestController ,这样子,里面所有的方法都只会返回 json 字符串了,不用再每一个都添加@ResponseBody !我们在前后端分离开发中,一般都使用 @RestController ,十分便捷!

@RestController
public class UserController {

   //produces:指定响应体返回类型和编码
   @RequestMapping(value = "/json1")
   public String json1() throws JsonProcessingException {
       //创建一个jackson的对象映射器,用来解析数据
       ObjectMapper mapper = new ObjectMapper();
       //创建一个对象
       User user = new User("秦疆1号", 3, "男");
       //将我们的对象解析成为json格式
       String str = mapper.writeValueAsString(user);
       //由于@ResponseBody注解,这里会将str转成json格式返回;十分方便
       return str;
  }

}

启动tomcat测试,结果都正常输出!

测试集合输出

增加一个新的方法

@RequestMapping("/json2")
public String json2() throws JsonProcessingException {

   //创建一个jackson的对象映射器,用来解析数据
   ObjectMapper mapper = new ObjectMapper();
   //创建一个对象
   User user1 = new User("秦疆1号", 3, "男");
   User user2 = new User("秦疆2号", 3, "男");
   User user3 = new User("秦疆3号", 3, "男");
   User user4 = new User("秦疆4号", 3, "男");
   List<User> list = new ArrayList<User>();
   list.add(user1);
   list.add(user2);
   list.add(user3);
   list.add(user4);

   //将我们的对象解析成为json格式
   String str = mapper.writeValueAsString(list);
   return str;
}

运行结果 : 十分完美,没有任何问题!

SpringMVC狂神说最全笔记 - 图16

输出时间对象

增加一个新的方法

@RequestMapping("/json3")
public String json3() throws JsonProcessingException {

   ObjectMapper mapper = new ObjectMapper();

   //创建时间一个对象,java.util.Date
   Date date = new Date();
   //将我们的对象解析成为json格式
   String str = mapper.writeValueAsString(date);
   return str;
}

运行结果 :

SpringMVC狂神说最全笔记 - 图17

  • 默认日期格式会变成一个数字,是1970年1月1日到当前日期的毫秒数!
  • Jackson 默认是会把时间转成timestamps形式

解决方案:取消timestamps形式 , 自定义时间格式

@RequestMapping("/json4")
public String json4() throws JsonProcessingException {

   ObjectMapper mapper = new ObjectMapper();

   //不使用时间戳的方式
   mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
   //自定义日期格式对象
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
   //指定日期格式
   mapper.setDateFormat(sdf);

   Date date = new Date();
   String str = mapper.writeValueAsString(date);

   return str;
}

运行结果 : 成功的输出了时间!

抽取为工具类

如果要经常使用的话,这样是比较麻烦的,我们可以将这些代码封装到一个工具类中;我们去编写下

package com.kuang.utils;


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

import java.text.SimpleDateFormat;

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

    public static String getJson(Object object,String dateFormat){
        ObjectMapper mapper = new ObjectMapper();
        //1.如何让他不返回时间戳!所以我们要关闭它的时间戳功能
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        //2.时间格式化问题!自定日期格式对象;
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        //3.让mapper指定时间日期格式为simpleDateFormat;
        mapper.setDateFormat(sdf);

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

}

我们使用工具类,代码就更加简洁了!

@RequestMapping("/json5")
public String json5() throws JsonProcessingException {
   Date date = new Date();
   String json = JsonUtils.getJson(date);
   return json;
}

大功告成!完美!

FastJson

fastjson.jar是阿里开发的一款专门用于Java开发的包,可以方便的实现json对象与JavaBean对象的转换,实现JavaBean对象与json字符串的转换,实现json对象与json字符串的转换。实现json的转换方法很多,最后的实现结果都是一样的。

fastjson 的 pom依赖!

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

fastjson 三个主要的类:

JSONObject 代表 json 对象

  • JSONObject实现了Map接口, 猜想 JSONObject底层操作是由Map实现的。
  • JSONObject对应json对象,通过各种形式的get()方法可以获取json对象中的数据,也可利用诸如size(),isEmpty()等方法获取”键:值”对的个数和判断是否为空。其本质是通过实现Map接口并调用接口中的方法完成的。

JSONArray 代表 json 对象数组

  • 内部是有List接口中的方法来完成操作的。

JSON代表 JSONObject和JSONArray的转化

  • JSON类源码分析与使用
  • 仔细观察这些方法,主要是实现json对象,json对象数组,javabean对象,json字符串之间的相互转化。

代码测试,我们新建一个FastJsonDemo 类

package com.kuang.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kuang.pojo.User;

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

public class FastJsonDemo {
   public static void main(String[] args) {
       //创建一个对象
       User user1 = new User("秦疆1号", 3, "男");
       User user2 = new User("秦疆2号", 3, "男");
       User user3 = new User("秦疆3号", 3, "男");
       User user4 = new User("秦疆4号", 3, "男");
       List<User> list = new ArrayList<User>();
       list.add(user1);
       list.add(user2);
       list.add(user3);
       list.add(user4);

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

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

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

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

这种工具类,我们只需要掌握使用就好了,在使用的时候在根据具体的业务去找对应的实现。和以前的commons-io那种工具包一样,拿来用就好了!

7. Ajax研究

简介

  • AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。
  • AJAX 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
  • Ajax 不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的Web应用程序的技术。
  • 在 2005 年,Google 通过其 Google Suggest 使 AJAX 变得流行起来。Google Suggest能够自动帮你完成搜索单词。
  • Google Suggest 使用 AJAX 创造出动态性极强的 web 界面:当您在谷歌的搜索框输入关键字时,JavaScript 会把这些字符发送到服务器,然后服务器会返回一个搜索建议的列表。
  • 就和国内百度的搜索框一样!
  • 传统的网页(即不用ajax技术的网页),想要更新内容或者提交一个表单,都需要重新加载整个网页。
  • 使用ajax技术的网页,通过在后台服务器进行少量的数据交换,就可以实现异步局部更新。
  • 使用Ajax,用户可以创建接近本地桌面应用的直接、高可用、更丰富、更动态的Web用户界面。

伪造Ajax

我们可以使用前端的一个标签来伪造一个ajax的样子。iframe标签

1、新建一个module :sspringmvc-06-ajax , 导入web支持!

2、编写一个 ajax-frame.html 使用 iframe 测试,感受下效果

<!DOCTYPE html>
<html>
<head lang="en">
   <meta charset="UTF-8"> 
   <title>kuangshen</title>
</head>
<body>

<script type="text/javascript">
   window.onload = function(){
       var myDate = new Date();
       document.getElementById('currentTime').innerText = myDate.getTime();
  };

   function LoadPage(){
       var targetUrl =  document.getElementById('url').value;
       console.log(targetUrl);
       document.getElementById("iframePosition").src = targetUrl;
  }

</script>

<div>
   <p>请输入要加载的地址:<span id="currentTime"></span></p>
   <p>
       <input id="url" type="text" value="https://www.baidu.com/"/>
       <input type="button" value="提交" onclick="LoadPage()">
   </p>
</div>

<div>
   <h3>加载页面位置:</h3>
   <iframe id="iframePosition" style="width: 100%;height: 500px;"></iframe>
</div>

</body>
</html>

3、使用IDEA开浏览器测试一下!

利用AJAX可以做:

  • 注册时,输入用户名自动检测用户是否已经存在。
  • 登陆时,提示用户名密码错误
  • 删除数据行时,将行ID发送到后台,后台在数据库中删除,数据库删除成功后,在页面DOM中将数据行也删除。
  • ….等等

jQuery.ajax

纯JS原生实现Ajax我们不去讲解这里,直接使用jquery提供的,方便学习和使用,避免重复造轮子,有兴趣的同学可以去了解下JS原生XMLHttpRequest !

Ajax的核心是XMLHttpRequest对象(XHR)。XHR为向服务器发送请求和解析服务器响应提供了接口。能够以异步方式从服务器获取新数据。

jQuery 提供多个与 AJAX 有关的方法。

通过 jQuery AJAX 方法,您能够使用 HTTP Get 和 HTTP Post 从远程服务器上请求文本、HTML、XML 或 JSON – 同时您能够把这些外部数据直接载入网页的被选元素中。

jQuery 不是生产者,而是大自然搬运工。

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

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

我们来个简单的测试,使用最原始的HttpServletResponse处理 , .最简单 , 最通用

1、配置web.xml 和 springmvc的配置文件,复制上面案例的即可 【记得静态资源过滤和注解驱动配置上】

<?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.kuang.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>

</beans>

2、编写一个AjaxController

@Controller
public class AjaxController {

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

}

3、导入jquery , 可以使用在线的CDN , 也可以下载导入

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>

4、编写index.jsp测试

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
 <head>
   <title>$Title$</title>
  <%--<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>--%>
   <script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
   <script>
       function a1(){
           $.post({
               url:"${pageContext.request.contextPath}/a1",
               data:{'name':$("#txtName").val()},
               success:function (data,status) {
                   alert(data);
                   alert(status);
              }
          });
      }
   </script>
 </head>
 <body>

<%--onblur:失去焦点触发事件--%>
用户名:<input type="text" id="txtName" onblur="a1()"/>

 </body>
</html>

5、启动tomcat测试!打开浏览器的控制台,当我们鼠标离开输入框的时候,可以看到发出了一个ajax的请求!是后台返回给我们的结果!测试成功!

ajax的springmvc实现

Springmvc实现

实体类user

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

   private String name;
   private int age;
   private String sex;

}

我们来获取一个集合对象,展示到前端页面

@RequestMapping("/a2")
public List<User> ajax2(){
   List<User> list = new ArrayList<User>();
   list.add(new User("秦疆1号",3,"男"));
   list.add(new User("秦疆2号",3,"男"));
   list.add(new User("秦疆3号",3,"男"));
   return list; //由于@RestController注解,将list转成json格式返回
}

前端页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>
<body>
<input type="button" id="btn" value="获取数据"/>
<table width="80%" align="center">
   <tr>
       <td>姓名</td>
       <td>年龄</td>
       <td>性别</td>
   </tr>
   <tbody id="content">
   </tbody>
</table>

<script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.js"></script>
<script>

   $(function () {
       $("#btn").click(function () {
           $.post("${pageContext.request.contextPath}/a2",function (data) {
               console.log(data)
               var html="";
               for (var 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>
</body>
</html>

成功实现了数据回显!可以体会一下Ajax的好处!

注册提示效果

我们再测试一个小Demo,思考一下我们平时注册时候,输入框后面的实时提示怎么做到的;如何优化

我们写一个Controller

@RequestMapping("/a3")
public String ajax3(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; //由于@RestController注解,将msg转成json格式返回
}

前端页面 login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>ajax</title>
   <script src="${pageContext.request.contextPath}/statics/js/jquery-3.1.1.min.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" onblur="a1()"/>
   <span id="userInfo"></span>
</p>
<p>
  密码:<input type="text" id="pwd" onblur="a2()"/>
   <span id="pwdInfo"></span>
</p>
</body>
</html>

【记得处理json乱码问题】

测试一下效果,动态请求响应,局部刷新,就是如此!

SpringMVC狂神说最全笔记 - 图18

获取baidu接口Demo

<!DOCTYPE HTML>
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <title>JSONP百度搜索</title>
   <style>
       #q{
           width: 500px;
           height: 30px;
           border:1px solid #ddd;
           line-height: 30px;
           display: block;
           margin: 0 auto;
           padding: 0 10px;
           font-size: 14px;
      }
       #ul{
           width: 520px;
           list-style: none;
           margin: 0 auto;
           padding: 0;
           border:1px solid #ddd;
           margin-top: -1px;
           display: none;
      }
       #ul li{
           line-height: 30px;
           padding: 0 10px;
      }
       #ul li:hover{
           background-color: #f60;
           color: #fff;
      }
   </style>
   <script>

       // 2.步骤二
       // 定义demo函数 (分析接口、数据)
       function demo(data){
           var Ul = document.getElementById('ul');
           var html = '';
           // 如果搜索数据存在 把内容添加进去
           if (data.s.length) {
               // 隐藏掉的ul显示出来
               Ul.style.display = 'block';
               // 搜索到的数据循环追加到li里
               for(var i = 0;i<data.s.length;i++){
                   html += '<li>'+data.s[i]+'</li>';
              }
               // 循环的li写入ul
               Ul.innerHTML = html;
          }
      }

       // 1.步骤一
       window.onload = function(){
           // 获取输入框和ul
           var Q = document.getElementById('q');
           var Ul = document.getElementById('ul');

           // 事件鼠标抬起时候
           Q.onkeyup = function(){
               // 如果输入框不等于空
               if (this.value != '') {
                   // ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆JSONPz重点☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆
                   // 创建标签
                   var script = document.createElement('script');
                   //给定要跨域的地址 赋值给src
                   //这里是要请求的跨域的地址 我写的是百度搜索的跨域地址
                   script.src = 'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd='+this.value+'&cb=demo';
                   // 将组合好的带src的script标签追加到body里
                   document.body.appendChild(script);
              }
          }
      }
   </script>
</head>

<body>
<input type="text" id="q" />
<ul id="ul">

</ul>
</body>
</html>

8. 拦截器

概述

SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。开发者可以自己定义一些拦截器来实现特定的功能。

过滤器与拦截器的区别:拦截器是AOP思想的具体应用。

过滤器

  • servlet规范中的一部分,任何java web工程都可以使用
  • 在url-pattern中配置了/*之后,可以对所有要访问的资源进行拦截

拦截器

  • 拦截器是SpringMVC框架自己的,只有使用了SpringMVC框架的工程才能使用
  • 拦截器只会拦截访问的控制器方法, 如果访问的是jsp/html/css/image/js是不会进行拦截的

自定义拦截器

那如何实现拦截器呢?

想要自定义拦截器,必须实现 HandlerInterceptor 接口。

1、新建一个Moudule , springmvc-07-Interceptor , 添加web支持

2、配置web.xml 和 springmvc-servlet.xml 文件

3、编写一个拦截器

package com.kuang.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 {

   //在请求处理的方法之前执行
   //如果返回true执行下一个拦截器
   //如果返回false就不执行下一个拦截器
   public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
       System.out.println("------------处理前------------");
       return true;
  }

   //在请求处理方法执行之后执行
   public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
       System.out.println("------------处理后------------");
  }

   //在dispatcherServlet处理后执行,做清理工作.
   public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
       System.out.println("------------清理------------");
  }
}

4、在springmvc的配置文件中配置拦截器

<!--关于拦截器的配置-->
<mvc:interceptors>
   <mvc:interceptor>
       <!--/** 包括路径及其子路径-->
       <!--/admin/* 拦截的是/admin/add等等这种 , /admin/add/user不会被拦截-->
       <!--/admin/** 拦截的是/admin/下的所有-->
       <mvc:mapping path="/**"/>
       <!--bean配置的就是拦截器-->
       <bean class="com.kuang.interceptor.MyInterceptor"/>
   </mvc:interceptor>
</mvc:interceptors>

5、编写一个Controller,接收请求

package com.kuang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

//测试拦截器的控制器
@Controller
public class InterceptorController {

   @RequestMapping("/interceptor")
   @ResponseBody
   public String testFunction() {
       System.out.println("控制器中的方法执行了");
       return "hello";
  }
}

6、前端 index.jsp

<a href="${pageContext.request.contextPath}/interceptor">拦截器测试</a>

7、启动tomcat 测试一下!

SpringMVC狂神说最全笔记 - 图19

验证用户是否登录 (认证用户)

实现思路

1、有一个登陆页面,需要写一个controller访问页面。

2、登陆页面有一提交表单的动作。需要在controller中处理。判断用户名密码是否正确。如果正确,向session中写入用户信息。返回登陆成功。

3、拦截用户请求,判断用户是否登陆。如果用户已经登陆。放行, 如果用户未登陆,跳转到登陆页面

测试:

1、编写一个登陆页面 login.jsp

在web-inf 下的所有页面或者资源,只能通过 controller 或者 servlet 进行访问
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
   <title>Title</title>
</head>

<h1>登录页面</h1>
<hr>

<body>
<form action="${pageContext.request.contextPath}/user/login">
  用户名:<input type="text" name="username"> <br>
  密码:<input type="password" name="pwd"> <br>
   <input type="submit" value="提交">
</form>
</body>
</html>

2、编写一个Controller处理请求

package com.kuang.controller;

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

import javax.servlet.http.HttpSession;

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

   //跳转到登陆页面
   @RequestMapping("/jumplogin")
   public String jumpLogin() throws Exception {
       return "login";
  }

   //跳转到成功页面
   @RequestMapping("/jumpSuccess")
   public String jumpSuccess() throws Exception {
       return "success";
  }

   //登陆提交
   @RequestMapping("/login")
   public String login(HttpSession session, String username, String pwd) throws Exception {
       // 向session记录用户身份信息
       System.out.println("接收前端==="+username);
       session.setAttribute("user", username);
       return "success";
  }

   //退出登陆
   @RequestMapping("logout")
   public String logout(HttpSession session) throws Exception {
       // session 过期
       session.invalidate();
       return "login";
  }
}

3、编写一个登陆成功的页面 success.jsp

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

<h1>登录成功页面</h1>
<hr>

${user}
<a href="${pageContext.request.contextPath}/user/logout">注销</a>
</body>
</html>

4、在 index 页面上测试跳转!启动Tomcat 测试,未登录也可以进入主页!

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
 <head>
   <title>$Title$</title>
 </head>
 <body>
 <h1>首页</h1>
 <hr>
<%--登录--%>
 <a href="${pageContext.request.contextPath}/user/jumplogin">登录</a>
 <a href="${pageContext.request.contextPath}/user/jumpSuccess">成功页面</a>
 </body>
</html>

5、编写用户登录拦截器

package com.kuang.interceptor;

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

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginInterceptor implements HandlerInterceptor {

   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException {
       // 如果是登陆页面则放行
       System.out.println("uri: " + request.getRequestURI());
       if (request.getRequestURI().contains("login")) {
           return true;
      }

       HttpSession session = request.getSession();

       // 如果用户已登陆也放行
       if(session.getAttribute("user") != null) {
           return true;
      }

       // 用户没有登陆跳转到登陆页面
       request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
       return false;
  }

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

  }

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

  }
}

6、在Springmvc的配置文件中注册拦截器

<!--关于拦截器的配置-->
<mvc:interceptors>
   <mvc:interceptor>
       <mvc:mapping path="/**"/>
       <bean id="loginInterceptor" class="com.kuang.interceptor.LoginInterceptor"/>
   </mvc:interceptor>
</mvc:interceptors>

7、再次重启Tomcat测试!

OK,测试登录拦截功能无误.

文件上传和下载

准备工作

文件上传是项目开发中最常见的功能之一 ,springMVC 可以很好的支持文件上传,但是SpringMVC上下文中默认没有装配MultipartResolver,因此默认情况下其不能处理文件上传工作。如果想使用Spring的文件上传功能,则需要在上下文中配置MultipartResolver。

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

对表单中的 enctype 属性做个详细的说明:

  • application/x-www=form-urlencoded:默认方式,只处理表单域中的 value 属性值,采用这种编码方式的表单会将表单域中的值处理成 URL 编码方式。
  • multipart/form-data:这种编码方式会以二进制流的方式来处理表单数据,这种编码方式会把文件域指定文件的内容也封装到请求参数中,不会对字符编码。
  • text/plain:除了把空格转换为 “+” 号外,其他字符都不做编码处理,这种方式适用直接通过表单发送邮件。
<form action="" enctype="multipart/form-data" method="post">
   <input type="file" name="file"/>
   <input type="submit">
</form>

一旦设置了enctype为multipart/form-data,浏览器即会采用二进制流的方式来处理表单数据,而对于文件上传的处理则涉及在服务器端解析原始的HTTP响应。在2003年,Apache Software Foundation发布了开源的Commons FileUpload组件,其很快成为Servlet/JSP程序员上传文件的最佳选择。

  • Servlet3.0规范已经提供方法来处理文件上传,但这种上传需要在Servlet中完成。
  • 而Spring MVC则提供了更简单的封装。
  • Spring MVC为文件上传提供了直接的支持,这种支持是用即插即用的MultipartResolver实现的。
  • Spring MVC使用Apache Commons FileUpload技术实现了一个MultipartResolver实现类:
  • CommonsMultipartResolver。因此,SpringMVC的文件上传还需要依赖Apache Commons FileUpload的组件。

文件上传

1、导入文件上传的jar包,commons-fileupload , Maven会自动帮我们导入他的依赖包 commons-io包;

<!--文件上传-->
<dependency>
   <groupId>commons-fileupload</groupId>
   <artifactId>commons-fileupload</artifactId>
   <version>1.3.3</version>
</dependency>
<!--servlet-api导入高版本的-->
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>4.0.1</version>
</dependency>

2、配置bean:multipartResolver

注意!!!这个bean的id必须为:multipartResolver , 否则上传文件会报400的错误!在这里栽过坑,教训!

<!--文件上传配置-->
<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
   <property name="defaultEncoding" value="utf-8"/>
   <!-- 上传文件大小上限,单位为字节(10485760=10M) -->
   <property name="maxUploadSize" value="10485760"/>
   <property name="maxInMemorySize" value="40960"/> 
</bean>

CommonsMultipartFile 的 常用方法:

  • String getOriginalFilename():获取上传文件的原名
  • InputStream getInputStream():获取文件流
  • void transferTo(File dest):将上传文件保存到一个目录文件中

我们去实际测试一下

3、编写前端页面

<form action="/upload" enctype="multipart/form-data" method="post">
 <input type="file" name="file"/>
 <input type="submit" value="upload">
</form>

4、Controller

package com.kuang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

@Controller
public class FileController {
   //@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
   //批量上传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";
  }
}

5、测试上传文件,OK!

采用file.Transto 来保存上传的文件

1、编写Controller

/*
* 采用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";
}

2、前端表单提交地址修改

3、访问提交测试,OK!

文件下载

文件下载步骤:

1、设置 response 响应头

2、读取文件 — InputStream

3、写出文件 — OutputStream

4、执行操作

5、关闭流 (先开后关)

代码实现:

@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
   //要下载的图片地址
   String  path = request.getServletContext().getRealPath("/upload");
   String  fileName = "基础语法.jpg";

   //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;
}

前端

<a href="/download">点击下载</a>

测试,文件下载OK,大家可以和我们之前学习的JavaWeb原生的方式对比一下,就可以知道这个便捷多了!

拦截器及文件操作在我们开发中十分重要,一定要学会使用!