Spring入门

回顾MVC架构

MVC是一种架构模型,本身没有什么功能,只是让我们的项目结构更加合理,流程控制更加清晰,一般包含三个组件:
Model(模型):数据模型,用于提供要展示的数据。一般包含数据和行为(也就是业务),在JavaWEB中,数据和业务往往是分离开的。
View(视图):负责对模型数据进行展示,例如我们看到的网页。概念比较广泛,可以是:html、JSP、excel、Word、PDF、json、XML等
Controller(控制器):接收用户请求,委托给业务层做处理,处理完毕返回数据,再交给视图做渲染,相当于调度员工作
image.png

什么是SpringMVC?

SpringMVC是Spring架构中的一部分:
image.png
Spring Web MVC是一种基于Java的,实现了Web MVC设计模式的轻量级Web框架,即使用了MVC架构模式的思想,将web层进行职责解耦,采用了松散耦合可插拔组件结构,比其它MVC框架更具扩展性和灵活性。

可以让我们实现:

  • 进行更简洁的Web层的开发;
  • 天生与Spring框架集成(如IoC容器、AOP等);
  • 提供强大的约定大于配置的契约式编程支持;
  • 支持灵活的URL到页面控制器的映射;
  • 非常容易与其他视图技术集成,如Velocity、FreeMarker等等,因为模型数据不放在特定的API里,而是放在一个Model里(Map数据结构实现,因此很容易被其他框架使用);
  • 非常灵活的数据验证、格式化和数据绑定机制,能使用任何对象进行数据绑定,不必实现特定框架的API;
  • 支持RESTful风格。

SpringMVC在架构设计、扩展性、灵活性方面已经全面超越了Struts、WebWork等MVC框架,从原来的追赶着一跃成为MVC的领跑者!Springmvc处理流程
如下图所示:
image.png

入门程序

需求:使用浏览器显示商品列表

创建web工程

springMVC是表现层框架,需要搭建web工程开发。
如下图创建动态web工程:
image.png
输入工程名,选择配置Tomcat(如果已有,则直接使用),如下图:
image.png
创建效果如下图:
image.png

导入jar包

从资料中导入springMVC的jar包,位置如下图:
image.png
复制jar到lib目录,工程直接加载jar包,如下图:
image.png

加入配置文件

创建config资源文件夹,存放配置文件,如下图:
image.png

创建springmvc.xml

创建SpringMVC的核心配置文件
SpringMVC本身就是Spring的子项目,对Spring兼容性很好,不需要做很多配置。
这里只配置一个Controller扫描就可以了,让Spring对页面控制层Controller进行管理。

创建springmvc.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" xmlns:p="http://www.springframework.org/schema/p"
  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 http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  7. http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  8. http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
  9. <!-- 配置controller扫描包 -->
  10. <context:component-scan base-package="com.igeek.springmvc.controller" />
  11. <!-- 这个是配置映射器、适配器等等,不然springMVC不起作用 -->
  12. <mvc:annotation-driven />
  13. </beans>

配置文件需要的约束文件,位置如下图:
image.png
创建包com.igeek.springmvc.controller
效果如下图:
image.png

配置前端控制器

配置SpringMVC的前端控制器DispatcherServlet
在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_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>springmvc-first</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <!-- 配置SpringMVC前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- 指定SpringMVC配置文件 -->
        <!-- SpringMVC的配置文件的默认路径是/WEB-INF/${servlet-name}-servlet.xml -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!-- 设置所有以action结尾的请求进入SpringMVC -->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

/:代表拦截除后缀名以外的路径,即它只拦截路径,不拦截带后缀的url,若请求为/user/login.jsp,jsp不会进入DispatcherServlet类,即不会被过滤。但会拦截.jpg , .html 等静态文件。加入注解既可访问静态资源。
/*:代表拦截所有路径和后缀,会匹配所有的url,若请求为/user/login.jsp,会出现jsp进入DispatcherServlet类,导致找不到对应的controller,所以报404错误。

加入jsp页面

把参考资料中的itemList.jsp复制到工程的/WEB-INF/jsp目录下,如下图:
image.png
image.png

实现显示商品列表页

创建pojo

分析页面,查看页面需要的数据,如下图:
image.png
创建商品pojo

public class Item {
    // 商品id
    private int id;
    // 商品名称
    private String name;
    // 商品价格
    private double price;
    // 商品创建时间
    private Date createtime;
    // 商品描述
    private String detail;

//创建带参数的构造器
//set/get。。。
}

创建ItemController

ItemController是一个普通的java类,不需要实现任何接口。
需要在类上添加@Controller注解,把Controller交由Spring管理
在方法上面添加@RequestMapping注解,里面指定请求的url。其中“.action”可以加也可以不加。

@Controller
public class ItemController {

    // @RequestMapping:里面放的是请求的url,和用户请求的url进行匹配
    // action可以写也可以不写
    @RequestMapping("/itemList.action")
    public ModelAndView queryItemList() {
        // 创建页面需要显示的商品数据
        List<Item> list = new ArrayList<>();
        list.add(new Item(1, "1华为 荣耀8", 2399, new Date(), "质量好!1"));
        list.add(new Item(2, "2华为 荣耀8", 2399, new Date(), "质量好!2"));
        list.add(new Item(3, "3华为 荣耀8", 2399, new Date(), "质量好!3"));
        list.add(new Item(4, "4华为 荣耀8", 2399, new Date(), "质量好!4"));
        list.add(new Item(5, "5华为 荣耀8", 2399, new Date(), "质量好!5"));
        list.add(new Item(6, "6华为 荣耀8", 2399, new Date(), "质量好!6"));

        // 创建ModelAndView,用来存放数据和视图
        ModelAndView modelAndView = new ModelAndView();
        // 设置数据到模型中
        modelAndView.addObject("itemList", list);
        // 设置视图jsp,需要设置视图的物理地址
        modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");

        return modelAndView;
    }
}

启动项目测试

启动项目,浏览器访问地址
http://localhost:8080/springmvc_d01_c02/itemList.action

效果如下图:
image.png
为什么可以用呢?我们需要分析一下springMVC的架构图。

Springmvc架构

框架结构

框架结构如下图:
image.png

架构流程

1、用户发送请求至前端控制器DispatcherServlet
2、DispatcherServlet收到请求调用HandlerMapping处理器映射器。
3、处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。
4、DispatcherServlet通过HandlerAdapter处理器适配器调用处理器
5、执行处理器(Controller,也叫后端控制器)。
6、Controller执行完成返回ModelAndView
7、HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet
8、DispatcherServlet将ModelAndView传给ViewReslover视图解析器
9、ViewReslover解析后返回具体View
10、DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)。
11、DispatcherServlet响应用户

组件说明

以下组件通常使用框架提供实现:

  • DispatcherServlet:前端控制器:用户请求到达前端控制器,它就相当于mvc模式中的c,dispatcherServlet是整个流程控制的中心,由它调用其它组件处理用户的请求,dispatcherServlet的存在降低了组件之间的耦合性。
  • HandlerMapping:处理器映射器:HandlerMapping负责根据用户请求url找到Handler即处理器,springmvc提供了不同的映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。
  • Handler:处理器:Handler 是继DispatcherServlet前端控制器的后端控制器,在DispatcherServlet的控制下Handler对具体的用户请求进行处理。由于Handler涉及到具体的用户业务请求,所以一般情况需要程序员根据业务需求开发Handler。
  • HandlAdapter:处理器适配器:通过HandlerAdapter对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行。

下图是许多不同的适配器,最终都可以使用usb接口连接
image.png

  • ViewResolver:视图解析器:View Resolver负责将处理结果生成View视图,View Resolver首先根据逻辑视图名解析成物理视图名即具体的页面地址,再生成View视图对象,最后对View进行渲染将处理结果通过页面展示给用户。
  • View:视图:springmvc框架提供了很多的View视图类型的支持,包括:jstlView、freemarkerView、pdfView等。我们最常用的视图就是jsp。

一般情况下需要通过页面标签或页面模版技术将模型数据通过页面展示给用户,需要由程序员根据业务需求开发具体的页面。

说明:在springmvc的各个组件中,处理器映射器、处理器适配器、视图解析器称为springmvc的三大组件。
需要用户开发的组件有handler、view

默认加载的组件

我们没有做任何配置,就可以使用这些组件
因为框架已经默认加载这些组件了,配置文件位置如下图:
image.png

# Default implementation classes for DispatcherServlet’s strategy interfaces.
# Used as fallback when no matching beans are found in the DispatcherServlet context.
# Not meant to be customized by application developers.
org.springframework.web.servlet.LocaleResolver=org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver
org.springframework.web.servlet.ThemeResolver=org.springframework.web.servlet.theme.FixedThemeResolver
org.springframework.web.servlet.HandlerMapping=org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,\
org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping
org.springframework.web.servlet.HandlerAdapter=org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,\
org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,\
org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
org.springframework.web.servlet.HandlerExceptionResolver=org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,\
org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,\
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver
org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator
org.springframework.web.servlet.ViewResolver=org.springframework.web.servlet.view.InternalResourceViewResolver
org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager

组件扫描器

使用组件扫描器省去在spring容器配置每个Controller类的繁琐。
使用自动扫描标记@Controller的控制器类,
在springmvc.xml配置文件中配置如下:

<!-- 配置controller扫描包,多个包之间用,分隔 -->
<context:component-scan base-package="com.igeek.springmvc.controller" />

注解映射器和适配器

配置处理器映射器

注解式处理器映射器,对类中标记了@ResquestMapping的方法进行映射。根据@ResquestMapping定义的url匹配@ResquestMapping标记的方法,匹配成功返回HandlerMethod对象给前端控制器。
HandlerMethod对象中封装url对应的方法Method。
从spring3.1版本开始,废除了DefaultAnnotationHandlerMapping的使用,推荐使用RequestMappingHandlerMapping完成注解式处理器映射。

在springmvc.xml配置文件中配置如下:

<!-- 配置处理器映射器 -->
<bean
    class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />

注解描述:
@RequestMapping:定义请求url到处理器功能方法的映射

配置处理器适配器

注解式处理器适配器,对标记@ResquestMapping的方法进行适配。
从spring3.1版本开始,废除了AnnotationMethodHandlerAdapter的使用,推荐使用RequestMappingHandlerAdapter完成注解式处理器适配。
在springmvc.xml配置文件中配置如下:

<!-- 配置处理器适配器 -->
<bean
    class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />

注解驱动

直接配置处理器映射器和处理器适配器比较麻烦,可以使用注解驱动来加载。
SpringMVC使用自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter
可以在springmvc.xml配置文件中使用替代注解处理器和适配器的配置。
< mvc:annotation-driven /> 还提供json自动转换等功能,需要依赖json解析jar包。

视图解析器

视图解析器使用SpringMVC框架默认的InternalResourceViewResolver,这个视图解析器支持JSP视图解析
在springmvc.xml配置文件中配置如下:

<!-- Example: prefix="/WEB-INF/jsp/", suffix=".jsp", viewname="test" -> 
        "/WEB-INF/jsp/test.jsp" -->
    <!-- 配置视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置逻辑视图的前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 配置逻辑视图的后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>

逻辑视图名需要在controller中返回ModelAndView指定,比如逻辑视图名为ItemList,则最终返回的jsp视图地址:
“WEB-INF/jsp/itemList.jsp”

最终jsp物理地址:前缀+逻辑视图名+后缀

修改ItemController

修改ItemController中设置视图的代码

// @RequestMapping:里面放的是请求的url,和用户请求的url进行匹配
// action可以写也可以不写
@RequestMapping("/itemList.action")
public ModelAndView queryItemList() {
    // 创建页面需要显示的商品数据
    List<Item> list = new ArrayList<>();
    list.add(new Item(1, "1华为 荣耀8", 2399, new Date(), "质量好!1"));
    list.add(new Item(2, "2华为 荣耀8", 2399, new Date(), "质量好!2"));
    list.add(new Item(3, "3华为 荣耀8", 2399, new Date(), "质量好!3"));
    list.add(new Item(4, "4华为 荣耀8", 2399, new Date(), "质量好!4"));
    list.add(new Item(5, "5华为 荣耀8", 2399, new Date(), "质量好!5"));
    list.add(new Item(6, "6华为 荣耀8", 2399, new Date(), "质量好!6"));

    // 创建ModelAndView,用来存放数据和视图
    ModelAndView modelAndView = new ModelAndView();
    // 设置数据到模型中
    modelAndView.addObject("itemList", list);
    // 设置视图jsp,需要设置视图的物理地址
    // modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
    // 配置好视图解析器前缀和后缀,这里只需要设置逻辑视图就可以了。
    // 视图解析器根据前缀+逻辑视图名+后缀拼接出来物理路径
    modelAndView.setViewName("itemList");

    return modelAndView;
}

效果

效果和之前一样,如下图:
image.png

整合mybatis

为了进一步的学习,我们将把mybatis整合到springmvc中。
整合目标:控制层采用springmvc、持久层使用mybatis实现。

创建数据库表

sql脚本,位置如下图:
image.png
创建数据库表springmvc,导入到数据库中,如下图:
image.png

需要的jar包

1.spring(包括springmvc)
2.mybatis
3.mybatis-spring整合包
4.数据库驱动
5.第三方连接池。

jar包位置如下图:
image.png

整合思路

Dao层:
1、SqlMapConfig.xml,空文件即可,但是需要文件头。
2、applicationContext-dao.xml
a)数据库连接池
b)SqlSessionFactory对象,需要spring和mybatis整合包下的。
c)配置mapper文件扫描器。

Service层:
1、applicationContext-service.xml包扫描器,扫描@service注解的类。
2、applicationContext-trans.xml配置事务。

Controller层:
1、Springmvc.xml
a)包扫描器,扫描@Controller注解的类。
b)配置注解驱动
c)配置视图解析器

Web.xml文件:
1、配置spring
2、配置前端控制器。

创建工程

创建动态web工程springmvc_d01_c04,如下图:
image.png
image.png

加入jar包

复制jar包到/WEB-INF/lib中
工程自动加载jar包

加入配置文件

创建资源文件夹config
在其下创建mybatis和spring文件夹,用来存放配置文件,如下图:
image.png

sqlMapConfig.xml

使用逆向工程来生成Mapper相关代码,不需要配置别名。
在config/mybatis下创建SqlMapConfig.xml

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

</configuration>

applicationContext-dao.xml

配置数据源、配置SqlSessionFactory、mapper扫描器。

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

    <!-- 加载配置文件 -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 数据库连接池 -->
    <bean id="dataSource"
    class="com.alibaba.druid.pool.DruidDataSource" init-method="init"
    destroy-method="close">
    <!-- 基本属性 url、user、password -->
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/igeekspring?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=FALSE&amp;serverTimezone=UTC" />
    <property name="username" value="root" />
    <property name="password" value="root" />

    <!-- 配置监控统计拦截的filters -->
    <property name="filters" value="stat" />

    <!-- 配置初始化大小、最小、最大 -->
    <property name="maxActive" value="20" />
    <property name="initialSize" value="1" />
    <property name="minIdle" value="1" />

    <!-- 配置获取连接等待超时的时间 -->
    <property name="maxWait" value="60000" />

    <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
    <property name="timeBetweenEvictionRunsMillis" value="60000" />

    <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
    <property name="minEvictableIdleTimeMillis" value="300000" />

    <property name="testWhileIdle" value="true" />
    <property name="testOnBorrow" value="false" />
    <property name="testOnReturn" value="false" />

    <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
    <property name="poolPreparedStatements" value="true" />
    <property name="maxOpenPreparedStatements" value="20" />
  </bean>

    <!-- 配置SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 加载mybatis的全局配置文件 -->
        <property name="configLocation" value="classpath:mybatis/sqlMapConfig.xml" />
    </bean>

    <!-- 配置Mapper扫描 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 配置Mapper扫描包 -->
        <property name="basePackage" value="com.igeek.ssm.mapper" />
    </bean>

</beans>

db.properties

配置数据库相关信息

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/igeekspring?useUnicode=true&characterEncoding=utf-8&useSSL=FALSE&serverTimezone=UTC
jdbc.username=root
jdbc.password=root

applicationContext-service.xml

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

    <!-- 配置service扫描 -->
    <context:component-scan base-package="com.igeek.ssm.service" />

</beans>

applicationContext-trans.xml

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

    <!-- 事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 数据源 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 通知 -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 传播行为 -->
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="insert*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />
            <tx:method name="query*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>

    <!-- 切面 -->
    <aop:config>
        <aop:advisor advice-ref="txAdvice"
            pointcut="execution(* com.igeek.ssm.service..*.*(..))" />
    </aop:config>

</beans>

springmvc.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:p="http://www.springframework.org/schema/p"
    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-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 配置controller扫描包 -->
    <context:component-scan base-package="com.igeek.ssm.controller" />

    <!-- 注解驱动 -->
    <mvc:annotation-driven />

    <!-- Example: prefix="/WEB-INF/jsp/", suffix=".jsp", viewname="test" -> 
        "/WEB-INF/jsp/test.jsp" -->
    <!-- 配置视图解析器 -->
    <bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置逻辑视图的前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 配置逻辑视图的后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

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_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>springmvc</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <!-- 配置spring -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/applicationContext*.xml</param-value>
    </context-param>

    <!-- 使用监听器加载Spring配置文件 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 配置SrpingMVC的前端控制器 -->
    <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:spring/springmvc.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!-- 配置所有以action结尾的请求进入SpringMVC -->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

</web-app>

加入jsp页面

复制课前资料的itemList.jsp和itemEdit.jsp到工程中

效果

image.png

实现商品列表显示

需求

实现商品查询列表,从mysql数据库查询商品信息。

DAO开发

使用逆向工程,生成代码

注意修改逆向工程的配置文件,参考MyBatis第二天
逆向工程生成代码如下图:
image.png

ItemService接口

public interface ItemService {

    /**
     * 查询商品列表
     * 
     * @return
     */
    List<Item> queryItemList();

}

ItemServiceImpl实现类

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemMapper itemMapper;

    @Override
    public List<Item> queryItemList() {
        // 从数据库查询商品数据
        List<Item> list = this.itemMapper.selectByExample(null);

        return list;
    }

}

ItemController

@Controller
public class ItemController {

    @Autowired
    private ItemService itemService;

    /**
     * 显示商品列表
     * 
     * @return
     */
    @RequestMapping("/itemList")
    public ModelAndView queryItemList() {
        // 获取商品数据
        List<Item> list = this.itemService.queryItemList();

        ModelAndView modelAndView = new ModelAndView();
        // 把商品数据放到模型中
        modelAndView.addObject("itemList", list);
        // 设置逻辑视图
        modelAndView.setViewName("itemList");

        return modelAndView;
    }

}

测试

访问url:
http://localhost:8080/springmvc_d01_c04/itemList.action

效果如下图:
image.png

参数绑定

默认支持的参数类型

需求

打开商品编辑页面,展示商品信息。

需求分析

编辑商品信息,首先要显示商品详情
需要根据商品id查询商品信息,然后展示到页面。
请求的url:/itemEdit.action
参数:id(商品id)
响应结果:商品编辑页面,展示商品详细信息。

ItemService接口

编写ItemService接口如下图:
image.png

ItemServiceImpl实现类

@Override
public Item queryItemById(int id) {
    Item item = this.itemMapper.selectByPrimaryKey(id);

    return item;
}

ItemController

页面点击修改按钮,发起请求
http://localhost:8080/springmvc_d01_c04/itemEdit.action?id=1
需要从请求的参数中把请求的id取出来。
Id包含在Request对象中。可以从Request对象中取id。
想获得Request对象只需要在Controller方法的形参中添加一个参数即可。Springmvc框架会自动把Request对象传递给方法。

代码实现

/**
 * 根据id查询商品
 * 
 * @param request
 * @return
 */
@RequestMapping("/itemEdit")
public ModelAndView queryItemById(HttpServletRequest request) {
    // 从request中获取请求参数
    String strId = request.getParameter("id");
    Integer id = Integer.valueOf(strId);

    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);

    // 把结果传递给页面
    ModelAndView modelAndView = new ModelAndView();
    // 把商品数据放在模型中
    modelAndView.addObject("item", item);
    // 设置逻辑视图
    modelAndView.setViewName("itemEdit");

    return modelAndView;
}

默认支持的参数类型

处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值。

HttpServletRequest

通过request对象获取请求信息

HttpServletResponse

通过response处理响应信息

HttpSession

通过session对象得到session中存放的对象

Model/ModelMap

Model

除了ModelAndView以外,还可以使用Model来向页面传递数据,
Model是一个接口,在参数里直接声明model即可。
如果使用Model则可以不使用ModelAndView对象,Model对象可以向页面传递数据,View对象则可以使用String返回值替代。
不管是Model还是ModelAndView,其本质都是使用Request对象向jsp传递数据。

代码实现:

/**
 * 根据id查询商品,使用Model
 * 
 * @param request
 * @param model
 * @return
 */
@RequestMapping("/itemEdit")
public String queryItemById(HttpServletRequest request, Model model) {
    // 从request中获取请求参数
    String strId = request.getParameter("id");
    Integer id = Integer.valueOf(strId);

    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);

    // 把结果传递给页面
    // ModelAndView modelAndView = new ModelAndView();
    // 把商品数据放在模型中
    // modelAndView.addObject("item", item);
    // 设置逻辑视图
    // modelAndView.setViewName("itemEdit");

    // 把商品数据放在模型中
    model.addAttribute("item", item);

    return "itemEdit";
}

ModelMap

ModelMap是Model接口的实现类,也可以通过ModelMap向页面传递数据
使用Model和ModelMap的效果一样,如果直接使用Model,springmvc会实例化ModelMap。

/**
 * 根据id查询商品,使用ModelMap
 * 
 * @param request
 * @param model
 * @return
 */
@RequestMapping("/itemEdit")
public String queryItemById(HttpServletRequest request, ModelMap model) {
    // 从request中获取请求参数
    String strId = request.getParameter("id");
    Integer id = Integer.valueOf(strId);

    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);

    // 把结果传递给页面
    // ModelAndView modelAndView = new ModelAndView();
    // 把商品数据放在模型中
    // modelAndView.addObject("item", item);
    // 设置逻辑视图
    // modelAndView.setViewName("itemEdit");

    // 把商品数据放在模型中
    model.addAttribute("item", item);

    return "itemEdit";
}

绑定简单类型

当请求的参数名称和处理器形参名称一致时会将请求参数与形参进行绑定。
这样,从Request取参数的方法就可以进一步简化。

/**
 * 根据id查询商品,绑定简单数据类型
 * 
 * @param id
 * @param model
 * @return
 */
@RequestMapping("/itemEdit")
public String queryItemById(int id, ModelMap model) {
    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);

    // 把商品数据放在模型中
    model.addAttribute("item", item);

    return "itemEdit";
}

支持的数据类型

参数类型推荐使用包装数据类型,因为基础数据类型不可以为null
整形:Integer、int
字符串:String
单精度:Float、float
双精度:Double、double
布尔型:Boolean、boolean
说明:对于布尔类型的参数,请求的参数值为true或false。或者1或0
请求url:
http://localhost:8080/xxx.action?id=2&status=false

处理器方法:
public String editItem(Model model,Integer id,Boolean status)

@RequestParam

使用@RequestParam常用于处理简单类型的绑定。
value:参数名字,即入参的请求参数名字,如value=“itemId”表示请求的参数区中的名字为itemId的参数的值将传入
required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报错
HTTP Status 400 - Required Integer parameter ‘XXXX’ is not present
defaultValue:默认值,表示如果请求中没有同名参数时的默认值

@RequestMapping("/itemEdit")
public String queryItemById(
    @RequestParam(value="itemId", required = true, defaultValue = "1") Integer id, 
    ModelMap modelMap) {

    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);

    // 把商品数据放在模型中
    modelMap.addAttribute("item", item);

    return "itemEdit";
}

绑定pojo类型

需求

将页面修改后的商品信息保存到数据库中。

需求分析

请求的url:/updateItem.action
参数:表单中的数据。
响应内容:更新成功页面

使用pojo接收表单数据

如果提交的参数很多,或者提交的表单中的内容很多的时候,可以使用简单类型接受数据,也可以使用pojo接收数据。
要求:pojo对象中的属性名和表单中input的name属性一致。

页面定义如下图:
image.png
Pojo(逆向工程生成)如下图:
image.png
请求的参数名称和pojo的属性名称一致,会自动将请求参数赋值给pojo的属性。

ItemService接口

ItemService里编写接口方法

/**
 * 根据id更新商品
 * 
 * @param item
 */
void updateItemById(Item item);

ItemServiceImpl实现类

ItemServiceImpl里实现接口方法
使用updateByPrimaryKeySelective(item)方法,忽略空参数

@Override
public void updateItemById(Item item) {
    this.itemMapper.updateByPrimaryKeySelective(item);
}

ItemController

/**
 * 更新商品,绑定pojo类型
 * 
 * @param item
 * @param model
 * @return
 */
@RequestMapping("/updateItem")
public String updateItem(Item item) {
    // 调用服务更新商品
    this.itemService.updateItemById(item);

    // 返回逻辑视图
    return "success";
}

注意:
提交的表单中不要有日期类型的数据,否则会报400错误。如果想提交日期类型的数据需要用到后面的自定义参数绑定的内容。

编写success页面

如下图创建success.jsp页面
image.png
页面代码:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<h1>商品修改成功!</h1>

</body>
</html>

解决post乱码问题

提交发现,保存成功,但是保存的是乱码
在web.xml中加入:

<!-- 解决post乱码问题 -->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!-- 设置编码参是UTF8 -->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

以上可以解决post请求乱码问题。
对于get请求中文参数出现乱码解决方法如下:
修改tomcat配置文件添加编码与工程编码一致,如下:

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

绑定包装pojo

需求

使用包装的pojo接收商品信息的查询条件。

需求分析

包装对象定义如下:

public class QueryVo {
    private Item item;
//set/get。。。
}

页面定义如下图:
image.png

<td>商品id<input type="text" name="item.id"/> </td>
<td>商品名称<input type="text" name="item.name"/> </td>

接收查询条件

// 绑定包装数据类型
@RequestMapping("/queryItem")
public String queryItem(QueryVo queryVo) {
    System.out.println(queryVo.getItem().getId());
    System.out.println(queryVo.getItem().getName());

    return "success";
}

自定义参数绑定

需求

在商品修改页面可以修改商品的生产日期,并且根据业务需求自定义日期格式。

需求分析

由于日期数据有很多种格式,springmvc没办法把字符串转换成日期类型。所以需要自定义参数绑定。
前端控制器接收到请求后,找到注解形式的处理器适配器,对RequestMapping标记的方法进行适配,并对方法中的形参进行参数绑定。可以在springmvc处理器适配器上自定义转换器Converter进行参数绑定。

一般使用注解驱动加载处理器适配器,可以在此标签上进行配置。

修改jsp页面

如下图修改itemEdit.jsp页面,显示时间
image.png

自定义Converter

//Converter<S, T>
//S:source,需要转换的源的类型
//T:target,需要转换的目标类型
public class DateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String source) {
        try {
            // 把字符串转换为日期类型
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = simpleDateFormat.parse(source);

            return date;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 如果转换异常则返回空
        return null;
    }
}

配置Converter

我们同时可以配置多个的转换器。
类似下图的usb设备,可以接入多个usb设备
image.png

<!-- 配置注解驱动 -->
<!-- 如果配置此标签,可以不用配置... -->
<mvc:annotation-driven conversion-service="conversionService" />

<!-- 转换器配置 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="com.igeek.ssm.converter.DateConverter" />
        </set>
    </property>
</bean>

配置方式2(了解)

<!--注解适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="webBindingInitializer" ref="customBinder"></property>
</bean>

<!-- 自定义webBinder -->
<bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
    <property name="conversionService" ref="conversionService" />
</bean>

<!-- 转换器配置 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="com.igeek.springmvc.convert.DateConverter" />
        </set>
    </property>
</bean>

注意:此方法需要独立配置处理器映射器、适配器,
不再使用

高级参数绑定

复制工程

把springmvc_d01_c04工程复制一份,作为今天开发的工程
工程名为springmvc_d02_c02:
工程右键点击,如下图:

修改发布的工程名,如下图:
image.png

绑定数组

需求

在商品列表页面选中多个商品,然后删除。

需求分析

功能要求商品列表页面中的每个商品前有一个checkbok,选中多个商品后点击删除按钮把商品id传递给Controller,根据商品id删除商品信息。

我们演示可以获取id的数组即可

Jsp修改

修改itemList.jsp页面,增加多选框,提交url是queryItem.action

<form action="${pageContext.request.contextPath }/queryItem.action" method="post">
查询条件:
<table width="100%" border=1>
<tr>
<td>商品id<input type="text" name="item.id" /></td>
<td>商品名称<input type="text" name="item.name" /></td>
<td><input type="submit" value="查询"/></td>
</tr>
</table>
商品列表:
<table width="100%" border=1>
<tr>
    <td>选择</td>
    <td>商品名称</td>
    <td>商品价格</td>
    <td>生产日期</td>
    <td>商品描述</td>
    <td>操作</td>
</tr>
<c:forEach items="${itemList }" var="item">
<tr>
    <td><input type="checkbox" name="ids" value="${item.id}"/></td>
    <td>${item.name }</td>
    <td>${item.price }</td>
    <td><fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
    <td>${item.detail }</td>

    <td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>

</tr>
</c:forEach>

</table>
</form>

页面选中多个checkbox向controller方法传递
本身属于一个form表单,提交url是queryItem.action

Controller

Controller方法中可以用String[]接收,或者pojo的String[]属性接收。两种方式任选其一即可。

定义QueryVo
ItemController修改queryItem方法:

/**
 * 包装类型 绑定数组类型,可以使用两种方式,pojo的属性接收,和直接接收
 * 
 * @param queryVo
 * @return
 */
@RequestMapping("queryItem")
public String queryItem(QueryVo queryVo, Integer[] ids) {

    System.out.println(queryVo.getItem().getId());
    System.out.println(queryVo.getItem().getName());

    System.out.println(queryVo.getIds().length);
    System.out.println(ids.length);

    return "success";
}

效果,如下图:
image.png

将表单的数据绑定到List

需求

实现商品数据的批量修改。

开发分析

开发分析
1.在商品列表页面中可以对商品信息进行修改。
可以批量提交修改后的商品数据。

定义pojo

List中存放对象,并将定义的List放在包装类QueryVo中
使用包装pojo对象接收,如下图:
image.png

Jsp改造

前端页面应该显示的html代码,如下图:
image.png
分析发现:name属性必须是list属性名+下标+元素属性。
Jsp做如下改造:

<c:forEach items="${itemList }" var="item" varStatus="s">
<tr>
    <td><input type="checkbox" name="ids" value="${item.id}"/></td>
    <td>
        <input type="hidden" name="itemList[${s.index}].id" value="${item.id }"/>
        <input type="text" name="itemList[${s.index}].name" value="${item.name }"/>
    </td>
    <td><input type="text" name="itemList[${s.index}].price" value="${item.price }"/></td>
    <td><input type="text" name="itemList[${s.index}].createtime" value="<fmt:formatDate value="${item.createtime}" pattern="yyyy-MM-dd HH:mm:ss"/>"/></td>
    <td><input type="text" name="itemList[${s.index}].detail" value="${item.detail }"/></td>

    <td><a href="${pageContext.request.contextPath }/itemEdit.action?id=${item.id}">修改</a></td>

</tr>
</c:forEach>

效果

这里只演示List的绑定,能够接收到list数据。
可以拿到数据即可,不做数据库的操作。

测试效果如下图:
image.png
注意:接收List类型的数据必须是pojo的属性,如果方法的形参为ArrayList类型则无法正确接收到数据。

@RequestMapping

通过@RequestMapping注解可以定义不同的处理器映射规则。

URL路径映射

@RequestMapping(value=”item”)或@RequestMapping(“/item”)
value的值是数组,可以将多个url映射到同一个方法

/**
 * 查询商品列表
 * @return
 */
@RequestMapping(value = { "itemList", "itemListAll" })
public ModelAndView queryItemList() {
    // 查询商品数据
    List<Item> list = this.itemService.queryItemList();

    // 创建ModelAndView,设置逻辑视图名
    ModelAndView mv = new ModelAndView("itemList");

    // 把商品数据放到模型中
    mv.addObject("itemList", list);
    return mv;
}

添加在类上面

在class上添加@RequestMapping(url)指定通用请求前缀, 限制此类下的所有方法请求url必须以请求前缀开头

可以使用此方法对url进行分类管理,如下图:
image.png
此时需要进入queryItemList()方法的请求url为:
http://localhost:8080/springmvc_d02_c02/item/itemList.action
或者
http://localhost:8080/springmvc_d02_c02/item/itemListAll.action

请求方法限定

除了可以对url进行设置,还可以限定请求进来的方法

  • 限定GET方法

@RequestMapping(method = RequestMethod.GET) 等同于 @GetMapping
如果通过POST访问则报错:
HTTP Status 405 - Request method ‘POST’ not supported

  • 限定POST方法

@RequestMapping(method = RequestMethod.POST) 等同于 @PostMapping
如果通过GET访问则报错:
HTTP Status 405 - Request method ‘GET’ not supported

  • GET和POST都可以

@RequestMapping(method = {RequestMethod.GET,RequestMethod.POST}) 等同于@RequestMapping

Controller方法返回值

返回ModelAndView

controller方法中定义ModelAndView对象并返回,对象中可添加model数据、指定view。参考之前的内容

返回void

在Controller方法形参上可以定义request和response,使用request或response指定响应结果:
1、使用request转发页面,如下:
request.getRequestDispatcher(“页面路径”).forward(request, response);

request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request, response);

2、可以通过response页面重定向:
response.sendRedirect(“url”)

response.sendRedirect("/springmvc_d02_c02/itemEdit.action");

3、可以通过response指定响应结果,例如响应json数据如下:

response.getWriter().print("{\"abc\":123}");

代码演示

以下代码一次测试,演示上面的效果

/**
 * 返回void测试
 * 
 * @param request
 * @param response
 * @throws Exception
 */
@RequestMapping("queryItem")
public void queryItem(HttpServletRequest request, HttpServletResponse response) throws Exception {
    // 1 使用request进行转发
    // request.getRequestDispatcher("/WEB-INF/jsp/success.jsp").forward(request,
    // response);

    // 2 使用response进行重定向到编辑页面
    // response.sendRedirect("/springmvc_d02_c02/itemEdit.action");

    // 3 使用response直接显示
    response.getWriter().print("{\"abc\":123}");
}

返回字符串

逻辑视图名

controller方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址。

//指定逻辑视图名,经过视图解析器解析为jsp物理路径:/WEB-INF/jsp/itemList.jsp
return "itemList";

参考之前的内容

Redirect重定向

Contrller方法返回字符串可以重定向到一个url地址
如下商品修改提交后重定向到商品编辑页面。

/**
 * 更新商品
 * 
 * @param item
 * @return
 */
@RequestMapping("updateItem")
public String updateItemById(Item item) {
    // 更新商品
    this.itemService.updateItemById(item);

    // 修改商品成功后,重定向到商品编辑页面
    // 重定向后浏览器地址栏变更为重定向的地址,
    // 重定向相当于执行了新的request和response,所以之前的请求参数都会丢失
    // 如果要指定请求参数,需要在重定向的url后面添加 ?itemId=1 这样的请求参数
    return "redirect:/itemEdit.action?itemId=" + item.getId();
}

forward转发

Controller方法执行后继续执行另一个Controller方法
如下商品修改提交后转向到商品修改页面,修改商品的id参数可以带到商品修改方法中。

/**
 * 更新商品
 * 
 * @param item
 * @return
 */
@RequestMapping("updateItem")
public String updateItemById(Item item) {
    // 更新商品
    this.itemService.updateItemById(item);

    // 修改商品成功后,重定向到商品编辑页面
    // 重定向后浏览器地址栏变更为重定向的地址,
    // 重定向相当于执行了新的request和response,所以之前的请求参数都会丢失
    // 如果要指定请求参数,需要在重定向的url后面添加 ?itemId=1 这样的请求参数
    // return "redirect:/itemEdit.action?itemId=" + item.getId();

    // 修改商品成功后,继续执行另一个方法
    // 使用转发的方式实现。转发后浏览器地址栏还是原来的请求地址,
    // 转发并没有执行新的request和response,所以之前的请求参数都存在
    // 结果转发到editItem.action,request可以带过去
    return "forward:/itemEdit.action";
}

异常处理器

springmvc在处理请求过程中出现异常信息交由异常处理器进行处理,自定义异常处理器可以实现一个系统的异常处理逻辑。

异常处理思路

Throwable(error,Exception)
系统中异常根据Exception异常进行分类,可分为运行时异常和非运行时异常。前者通过捕获异常从而获取异常信息,后者主要通过规范代码开发、测试,通过技术手段减少运行时异常的发生。
系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:
image.png

自定义异常类

为了区别不同的异常,通常根据异常类型进行区分,这里我们创建一个自定义系统异常。
如果controller、service、dao抛出此类异常说明是系统预期处理的异常信息。

创建包:com.igeek.ssm.exception

public class MyException extends Exception {
    // 异常信息
    private String message;

    public MyException() {
        super();
    }

    public MyException(String message) {
        super();
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

自定义异常处理器

public class CustomHandleException implements HandlerExceptionResolver {

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
            Exception exception) {
        // 定义异常信息
        String msg;

        // 判断异常类型
        if (exception instanceof MyException) {
            // 如果是自定义异常,读取异常信息
            msg = exception.getMessage();
        } else {
            // 如果是非自定义异常,则取错误堆栈,从堆栈中获取异常信息
            Writer out = new StringWriter();
            PrintWriter s = new PrintWriter(out);
            exception.printStackTrace(s);
            msg = out.toString();

        }

        // 把错误信息发给相关人员,邮件,短信等方式
        // TODO

        // 返回错误页面,给用户友好页面显示错误信息
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("msg", msg);
        modelAndView.setViewName("error");

        return modelAndView;
    }
}

异常处理器配置

在springmvc.xml中添加:

<!-- 配置全局异常处理器 -->
<bean id="customHandleException"     class="com.igeek.ssm.exception.CustomHandleException"/>

错误页面

创建jsp页面:error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

    <h1>系统发生异常了!</h1>
    <br />
    <h1>异常信息</h1>
    <br />
    <h2>${msg }</h2>

</body>
</html>

异常测试

修改ItemController方法“queryItemList”,抛出异常:

/**
 * 查询商品列表
 * 
 * @return
 * @throws Exception
 */
@RequestMapping(value = { "itemList", "itemListAll" })
public ModelAndView queryItemList() throws Exception {
    // 自定义异常
    if (true) {
        throw new MyException("自定义异常出现了~");
    }

    // 运行时异常
    int a = 1 / 0;

    // 查询商品数据
    List<Item> list = this.itemService.queryItemList();
    // 创建ModelAndView,设置逻辑视图名
    ModelAndView mv = new ModelAndView("itemList");
    // 把商品数据放到模型中
    mv.addObject("itemList", list);

    return mv;
}

上传图片

配置虚拟目录

在tomcat上配置图片虚拟目录,在tomcat下conf/server.xml中添加:

访问http://localhost:8080/pic即可访问D:\develop\upload\temp下的图片。
放在节点中
idea里面需要勾选 Deploy applications configured in Tomcat instance
![%%_8X4MHWL$YJ{K8~%W8(C.png
复制一张图片到存放图片的文件夹,使用浏览器访问
测试效果,如下图:
image.png

加入jar包

实现图片上传需要加入的jar包,如下图:
image.png
或者通过maven引入

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.4</version>
</dependency>

把两个jar包放到工程的lib文件夹中

配置上传解析器

在springmvc.xml中配置文件上传解析器

<!-- 文件上传,id必须设置为multipartResolver -->
<bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置文件上传大小 -->
    <property name="maxUploadSize" value="5000000" />
</bean>

jsp页面修改

在商品修改页面,打开图片上传功能,如下图:
image.png
设置表单可以进行文件上传,如下图:
image.png

图片上传

@RequestMapping(value = "/itemEditPost", method = RequestMethod.POST)
public String itemEditPost(Item item, MultipartFile pictureFile) throws IOException {
    String picBasePath = "E:/develop/upload/temp/";

    // 图片上传
    // 获取文件名
    String oriName = pictureFile.getOriginalFilename();
    if(StringUtils.isNotBlank(oriName)) {
        // 获取图片后缀
        String extName = FilenameUtils.getExtension(oriName);
        String fullPicName = UUID.randomUUID().toString() + "." +extName;
        // 开始上传
        pictureFile.transferTo(new File(picBasePath + fullPicName));
        //删除旧图片
        if(StringUtils.isNotBlank(item.getPic())) {
            String oldPicPath = picBasePath + item.getPic().replaceAll("/pic/", "");
            FileUtils.deleteQuietly(new File(oldPicPath));
        }
        // 设置图片名到商品中
        item.setPic("/pic/" + fullPicName);
    }

    // 调用服务更新商品
    itemService.updateById(item);
    return "redirect:/item/itemEdit?id=" + item.getId();
}

在更新商品方法中添加图片上传逻辑

/**
 * 更新商品
 * 
 * @param item
 * @return
 * @throws Exception
 */
@RequestMapping("updateItem")
public String updateItemById(Item item, MultipartFile pictureFile) throws Exception {
    // 图片上传
    // 设置图片名称,不能重复,可以使用uuid
    String picName = UUID.randomUUID().toString();

    // 获取文件名
    String oriName = pictureFile.getOriginalFilename();
    // 获取图片后缀
    String extName = oriName.substring(oriName.lastIndexOf("."));

    // 开始上传
    pictureFile.transferTo(new File("D:/develop/upload/temp/" + picName + extName));

    // 设置图片名到商品中
    item.setPic(picName + extName);
    // ---------------------------------------------
    // 更新商品
    this.itemService.updateItemById(item);

    return "forward:/itemEdit.action";
}

效果,如下图:
image.png

<!-- 上传文件拦截,设置最大上传文件大小   10M=10*1024*1024(B)=10485760 bytes -->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <property name="maxUploadSize" value="10485760" />  
    </bean>

json数据交互

@RequestBody

作用:
@RequestBody注解用于读取http请求的内容,通过springmvc提供的HttpMessageConverter接口将读到的内容(json数据)转换为java对象并绑定到Controller方法的参数上。

传统的请求参数:
itemEdit.action?id=1&name=zhangsan&age=12
现在的请求参数:
使用POST请求,在请求体里面加入json数据

{
"id": 1,
"name": "测试商品",
"price": 99.9,
"detail": "测试商品描述",
"pic": "123456.jpg"
}

本例子应用:
@RequestBody注解实现接收http请求的json数据,将json数据转换为java对象进行绑定

@ResponseBody

作用:
@ResponseBody注解用于将Controller的方法返回的对象,通过springmvc提供的HttpMessageConverter接口转换为指定格式的数据如:json,xml等,通过Response响应给客户端

本例子应用:
@ResponseBody注解实现将Controller方法返回java对象转换为json响应给客户端。

请求json,响应json实现:

加入jar包

如果需要springMVC支持json,必须加入json的处理jar
我们使用Jackson这个jar,如下图:
image.png

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

ItemController编写

/**
 * 测试json的交互
 * @param item
 * @return
 */
@RequestMapping("testJson")
// @ResponseBody
public @ResponseBody Item testJson(@RequestBody Item item) {
    return item;
}

测试方法

在资料中找到js,拷贝到项目中
image.pngimage.png
在itemEdit.jsp中添加测试方法:

<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
$(function(){
    //alert(1);
    var params = '{"id": 1,"name": "测试商品","price": 99.9,"detail": "测试商品描述","pic": "123456.jpg"}';

//     $.post(url,params,function(data){
        //回调
//     },"json");//
    $.ajax({
        url : "${pageContext.request.contextPath }/testJson.action",
        data : params,
        contentType : "application/json;charset=UTF-8",//发送数据的格式
        type : "post",
        dataType : "json",//回调
        success : function(data){
            alert(data.name);
        }

    });
});
</script>

配置json转换器

如果不使用注解驱动,就需要给处理器适配器配置json转换器,参考之前学习的自定义参数绑定;如果使用了注解驱动,就不用下面的配置了。

在springmvc.xml配置文件中,给处理器适配器加入json转换器:

<!--处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <property name="messageConverters">
        <list>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
        </list>
        </property>
    </bean>

RESTful支持

什么是restful?

Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。
资源:互联网所有的事物都可以被抽象为资源
资源操作:使用POST、DELETE、PUT、GET,使用不同方法对资源进行操作。
分别对应添加、删除、修改、查询。

传统方式操作资源
http://127.0.0.1/item/queryItem.action?id=1查询,GET
http://127.0.0.1/item/saveItem.action新增,POST
http://127.0.0.1/item/updateItem.action更新,POST
http://127.0.0.1/item/deleteItem.action?id=1删除,GET或POST

使用RESTful操作资源
http://127.0.0.1/item/1查询, GET
http://127.0.0.1/item新增,POST
http://127.0.0.1/item更新,PUT
http://127.0.0.1/item/1删除,DELETE

需求

RESTful方式实现商品信息查询,返回json数据

从URL上获取参数

使用RESTful风格开发的接口,根据id查询商品,接口地址是:
http://127.0.0.1/item/1.action
我们需要从url上获取商品id,步骤如下:

  1. 使用注解@RequestMapping(“item/{id}”)声明请求的url,{xxx}叫做占位符,请求的URL可以是“item /1”或“item/2”
  2. 使用(@PathVariable() Integer id)获取url上的数据
    /**
    * 使用RESTful风格开发接口,实现根据id查询商品
    * 
    * @param id
    * @return
    */
    @RequestMapping("item/{id}")
    @ResponseBody
    public Item queryItemById(@PathVariable() Integer id) {
     Item item = this.itemService.queryItemById(id);
     return item;
    }
    
    如果@RequestMapping中表示为”item/{id}”,id和形参名称一致,@PathVariable不用指定名称。如果不一致,例如”item/{ItemId}”则需要指定名称@PathVariable(“itemId”)。

http://127.0.0.1/item.action?id=1
http://127.0.0.1/item/1.action

注意两个区别

  1. @PathVariable是获取url上数据的。@RequestParam获取请求参数的(包括post表单提交)
  2. 如果加上@ResponseBody注解,就不会走视图解析器,不会返回页面,就会返回json数据。如果不加,就走视图解析器,返回页面

拦截器

定义

Spring Web MVC 的处理器拦截器类似于Servlet 开发中的过滤器Filter,用于对处理器进行预处理和后处理。

拦截器定义

实现HandlerInterceptor接口,如下:

public class HandlerInterceptor1 implements HandlerInterceptor {
    // controller执行后且视图返回后调用此方法
    // 这里可得到执行controller时的异常信息
    // 这里可记录操作日志
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {
        System.out.println("HandlerInterceptor1....afterCompletion");
    }

    // controller执行后但未返回视图前调用此方法
    // 这里可在返回用户前对模型数据进行加工处理,比如这里加入公用信息以便页面显示
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {
        System.out.println("HandlerInterceptor1....postHandle");
    }

    // Controller执行前调用此方法
    // 返回true表示继续执行,返回false中止执行
    // 这里可以加入登录校验、权限拦截等
    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        System.out.println("HandlerInterceptor1....preHandle");
        // 设置为true,测试使用
        return true;
    }
}

拦截器配置

上面定义的拦截器再复制一份HandlerInterceptor2,注意新的拦截器修改代码:
System.out.println(“HandlerInterceptor2….preHandle”);

在springmvc.xml中配置拦截器

<!-- 配置拦截器 -->
<mvc:interceptors>
    <mvc:interceptor>
        <!-- 所有的请求都进入拦截器 -->
        <mvc:mapping path="/**" />
        <!-- 配置具体的拦截器 -->
        <bean class="com.igeek.ssm.interceptor.HandlerInterceptor1" />
    </mvc:interceptor>
    <mvc:interceptor>
        <!-- 所有的请求都进入拦截器 -->
        <mvc:mapping path="/**" />
        <!-- 配置具体的拦截器 -->
        <bean class="com.igeek.ssm.interceptor.HandlerInterceptor2" />
    </mvc:interceptor>
</mvc:interceptors>

正常流程测试

浏览器访问地址
http://localhost:8080/springmvc_d02_c02/itemList.action

运行流程

控制台打印:
HandlerInterceptor1..preHandle..
HandlerInterceptor2..preHandle..
HandlerInterceptor2..postHandle..
HandlerInterceptor1..postHandle..
HandlerInterceptor2..afterCompletion..
HandlerInterceptor1..afterCompletion..

中断流程测试

浏览器访问地址
http://localhost:8080/springmvc_d02_c02/itemList.action

运行流程

HandlerInterceptor1的preHandler方法返回false,HandlerInterceptor2返回true,运行流程如下:

HandlerInterceptor1..preHandle..

从日志看出第一个拦截器的preHandler方法返回false后第一个拦截器只执行了preHandler方法,其它两个方法没有执行,第二个拦截器的所有方法不执行,且Controller也不执行了。

HandlerInterceptor1的preHandler方法返回true,HandlerInterceptor2返回false,运行流程如下:

HandlerInterceptor1..preHandle..
HandlerInterceptor2..preHandle..
HandlerInterceptor1..afterCompletion..

从日志看出第二个拦截器的preHandler方法返回false后第一个拦截器的postHandler没有执行,第二个拦截器的postHandler和afterCompletion没有执行,且controller也不执行了。

总结:
preHandle按拦截器定义顺序调用
postHandler按拦截器定义逆序调用
afterCompletion按拦截器定义逆序调用

postHandler在拦截器链内所有拦截器返成功调用
afterCompletion只有preHandle返回true才调用

拦截器应用

处理流程

1、有一个登录页面,需要写一个Controller访问登录页面
2、登录页面有一提交表单的动作。需要在Controller中处理。
a) 判断用户名密码是否正确(在控制台打印)
b) 如果正确,向session中写入用户信息(写入用户名username)
c) 跳转到商品列表
3、拦截器。
a) 拦截用户请求,判断用户是否登录(登录请求不能拦截)
b) 如果用户已经登录。放行
c) 如果用户未登录,跳转到登录页面。

编写登录jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

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

</form>

</body>
</html>

用户登陆Controller

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

    /**
     * 跳转到登录页面
     * 
     * @return
     */
    @RequestMapping("toLogin")
    public String toLogin() {
        return "login";
    }

    /**
     * 用户登录
     * 
     * @param username
     * @param password
     * @param session
     * @return
     */
    @RequestMapping("login")
    public String login(String username, String password, HttpSession session) {
        // 校验用户登录
        System.out.println(username);
        System.out.println(password);

        // 把用户名放到session中
        session.setAttribute("username", username);

        return "redirect:/item/itemList.action";
    }

}

编写拦截器

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
    // 从request中获取session
    HttpSession session = request.getSession();
    // 从session中获取username
    Object username = session.getAttribute("username");
    // 判断username是否为null
    if (username != null) {
        // 如果不为空则放行
        return true;
    } else {
        // 如果为空则跳转到登录页面
        response.sendRedirect(request.getContextPath() + "/user/toLogin.action");
    }

    return false;
}

配置拦截器

只能拦截商品的url,所以需要修改ItemController,让所有的请求都必须以item开头,如下图:
image.png
在springmvc.xml配置拦截器

<mvc:interceptor>
    <!-- 配置商品被拦截器拦截 -->
    <mvc:mapping path="/item/**" />
    <!-- 配置具体的拦截器 -->
    <bean class="com.igeek.ssm.interceptor.LoginHandlerInterceptor" />
</mvc:interceptor>