SpringMvc(一)

内容:

1、Springmvc介绍
2、入门程序
3、Springmvc架构讲解

a) 框架结构
b) 组件说明

4、Springmvc整合mybatis
5、参数绑定(重要)

a) Springmvc默认支持的类型
b) 简单数据类型
c) Pojo类型
d) Pojo包装类型
e) 自定义参数绑定

6、Springmvc和struts2的区别

2 Spring web mvc介绍

2.1 Springmvc是什么?

springMvc:是一个表现层框架,作用:就是从请求中接收传入的参数,将处理后的结果数据返回给页面展示。
Spring web mvc和Struts2都属于表现层的框架,它是Spring框架的一部分,我们可以从Spring的整体结构中看得出来:
这里写图片描述

2.2 SpringMVC处理流程

这里写图片描述
这里写图片描述

3 入门程序

3.1 开发环境

本教程使用环境:
Jdk:jdk1.7.0_72
Eclipse:mars
Tomcat:apache-tomcat-7.0.53
Springmvc:4.1.3

3.2 需求

使用springmvc实现商品列表的展示。

3.3 需求分析

请求的url:/itemList.action
参数:无
数据:静态数据

3.4 开发步骤

3.4.1 第一步:创建一个javaweb工程

3.4.2 第二步:导入jar包

这里写图片描述

3.4.3 第三步:创建itemList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!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>查询商品列表</title>
</head>
<body>
    <form
        action="${pageContext.request.contextPath }/item/queryitem.action"
        method="post">
        查询条件:
        <table width="100%" border=1>
            <tr>
                <td><input type="submit" value="查询" /></td>
            </tr>
        </table>
        商品列表:
        <table width="100%" border=1>
            <tr>
                <td>商品名称</td>
                <td>商品价格</td>
                <td>生产日期</td>
                <td>商品描述</td>
                <td>操作</td>
            </tr>
            <c:forEach items="${itemList }" var="item">
                <tr>
                    <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>
</body>

</html>

把参考资料中的itemList.jsp放到工程的/WEB-INF/jsp目录下。

3.4.4 第四步:创建ItemsController

ItemController是一个普通的java类,不需要实现任何接口,只需要在类上添加@Controller注解即可。@RequestMapping注解指定请求的url,其中“.action”可以加也可以不加。在ModelAndView对象中,将视图设置为“/WEB-INF/jsp/itemList.jsp”

@Controller
public class ItemsController {

    // 指定url到请求方法的映射
    // url中输入一个地址,找到这个方法,例如:localhost:8080/springmvc/list.acion
    //                      http://localhost:8080/springmvc/list.action
    @RequestMapping("/list")
    public ModelAndView itemsList() throws Exception {
        List<Items> itemList = new ArrayList<>();

        // 商品列表
        Items items_1 = new Items();
        items_1.setName("联想笔记本_3");
        items_1.setPrice(6000f);
        items_1.setDetail("ThinkPad T430 联想笔记本电脑!");

        Items items_2 = new Items();
        items_2.setName("苹果手机");
        items_2.setPrice(5000f);
        items_2.setDetail("iphone6苹果手机!");

        itemList.add(items_1);
        itemList.add(items_2);

        // 创建modelandView对象
        // model模型:模型对象中存放了返回给页面的数据
        // view视图:视图对象中指定了返回的页面的位置
        ModelAndView modelAndView = new ModelAndView();

        // 将返回给页面的数据放入模型和视图对象中
        modelAndView.addObject("itemList", itemList);

        // 指定返回的页面位置
        modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
        // modelAndView.setViewName("itemsList");

        return modelAndView;

    }
}

商品数据使用Items类描述,可以使用参考资料中提供的pojo类,

3.4.5 第五步:创建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:dubbo="http://code.alibabatech.com/schema/dubbo"
    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://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 配置Controller注解扫描 -->
    <context:component-scan base-package="cn.oath.controller"/>
</beans>

3.4.6 第六步:配置前端控制器

在web.xml中添加DispatcherServlet的配置。

<!-- springMvc前端控制器 -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <!-- 如果没有指定springMvc核心配置文件,那么默认会去加载/WEB-INF/+<servlet-name>中的内容+ -servlet.xml配置文件 -->
        <!-- 指定springMvc核心配置文件位置 -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:SpringMvc.xml</param-value>
        </init-param>

        <!-- tomcat启动的时候就加载这个servlet -->
        <load-on-startup>1</load-on-startup>

    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

测试:访问 http://localhost:8080/springmvc/list.action,显示如下:
这里写图片描述

4 Springmvc架构

4.1 框架结构

这里写图片描述

4.2 架构流程

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响应用户

4.3 组件说明

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

 HandlAdapter:处理器适配器
通过HandlerAdapter对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行。
 View Resolver:视图解析器
View Resolver负责将处理结果生成View视图,View Resolver首先根据逻辑视图名解析成物理视图名即具体的页面地址,再生成View视图对象,最后对View进行渲染将处理结果通过页面展示给用户。
 View:视图,springmvc框架提供了很多的View视图类型的支持,包括:jstlView、freemarkerView、pdfView等。我们最常用的视图就是jsp。
一般情况下需要通过页面标签或页面模版技术将模型数据通过页面展示给用户,需要由程序员根据业务需求开发具体的页面。

说明:在springmvc的各个组件中,处理器映射器、处理器适配器、视图解析器称为springmvc的三大组件。

需要用户开放的组件有handler、view

4.4 框架默认加载组件

这里写图片描述

4.5 注解映射器和适配器

4.5.1 组件扫描器

使用组件扫描器省去在spring容器配置每个controller类的繁琐。使用<context:component-scan>自动扫描标记@controller的控制器类,配置如下:

<!-- 配置Controller注解扫描 -->
    <context:component-scan base-package="cn.oath.controller"/>

4.5.2 RequestMappingHandlerMapping注解式处理器映射器

注解式处理器映射器,对类中标记@ResquestMapping的方法进行映射,
根据ResquestMapping定义的url匹配ResquestMapping标记的方法,
匹配成功返回HandlerMethod对象给前端控制器,
HandlerMethod对象中封装url对应的方法Method。

从spring3.1版本开始,废除了DefaultAnnotationHandlerMapping的使用,
推荐使用RequestMappingHandlerMapping完成注解式处理器映射。

<!--注解映射器 -->
<beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
注解描述:
@RequestMapping:定义请求url到处理器功能方法的映射5.3   

4.5.3RequestMappingHandlerAdapter注解式处理器适配器

对标记@ResquestMapping的方法进行适配。

从spring3.1版本开始,废除了AnnotationMethodHandlerAdapter的使用,推荐使用RequestMappingHandlerAdapter完成注解式处理器适配。

配置如下:
<!--注解适配器 -->
    <beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>

4.5.4 mvc:annotation-driven(重要!!!)

**springmvc使用mvc:annotation-driven自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter,

可用在springmvc.xml配置文件中替代注解处理器和适配器的配置!!!

。**

<!-- 注解驱动:
    作用:替我们自动配置最新的注解的处理器映射器和处理器适配器
     -->
    <mvc:annotation-driven></mvc:annotation-driven>

4.6 视图解析器

在springmvc.xml文件配置如下:

<!-- 配置视图解析器 
    作用:在controller中指定页面路径的时候就不用写页面的完整路径名称了,可以直接写页面去掉扩展名的名称,
    modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
    modelAndView.setViewName("itemList");
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 真正的页面路径 =  前缀 + 去掉后缀名的页面名称 + 后缀 -->
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

InternalResourceViewResolver:支持JSP视图解析
viewClass:JstlView表示JSP模板页面需要使用JSTL标签库,所以classpath中必须包含jstl的相关jar 包。此属性可以不设置,默认为JstlView。
prefix 和suffix:查找视图页面的前缀和后缀,最终视图的址为:
前缀+逻辑视图名+后缀,逻辑视图名需要在controller中返回ModelAndView指定,比如逻辑视图名为hello,则最终返回的jsp视图地址 “WEB-INF/jsp/hello.jsp”

4.7整合后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:dubbo="http://code.alibabatech.com/schema/dubbo" 
    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://code.alibabatech.com/schema/dubbo 
        http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-4.0.xsd">

        <!-- 配置@Controller注解扫描 -->
        <context:component-scan base-package="cn.itheima.controller"></context:component-scan>

        <!-- 如果没有显示的配置处理器映射器和处理器适配那么springMvc会去默认的dispatcherServlet.properties中查找,
        对应的处理器映射器和处理器适配器去使用,这样每个请求都要扫描一次他的默认配置文件,效率非常低,会降低访问速度,所以要显示的配置处理器映射器和
        处理器适配器 -->

        <!-- 注解形式的处理器映射器 -->
<!--         <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> -->
        <!-- 注解形式的处理器适配器 -->
<!--         <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"></bean> -->

        <!-- 配置最新版的注解的处理器映射器 -->
<!--         <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean> -->
        <!-- 配置最新版的注解的处理器适配器 -->
<!--         <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean> -->

    <!-- 注解驱动:
        作用:替我们自动配置最新版的注解的处理器映射器和处理器适配器
     -->
    <mvc:annotation-driven></mvc:annotation-driven>


    <!-- 配置视图解析器 
    作用:在controller中指定页面路径的时候就不用写页面的完整路径名称了,可以直接写页面去掉扩展名的名称,
    modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
    modelAndView.setViewName("itemList");
    -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 真正的页面路径 =  前缀 + 去掉后缀名的页面名称 + 后缀 -->
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"></property>
    </bean>

</beans>

4.8 注解驱动与注解扫描的区别:

<!-- 配置@Controller注解扫描 -->
<context:component-scan base-package="cn.itheima.controller"></context:component-scan>

<!-- 注解驱动:
    作用:替我们自动配置最新版的注解的处理器映射器和处理器适配器
 -->
    <mvc:annotation-driven></mvc:annotation-driven>

    注解扫描简单来说就是用来扫描注解。注解驱动是替我们自动配置最新版的注解的处理器映射器和处理器适配器,
    有了注解驱动,我们无需配置最新版的注解的处理器映射器和最新版的注解的处理器适配器。

5 整合mybatis

为了更好的学习 springmvc和mybatis整合开发的方法,需要将springmvc和mybatis进行整合。
整合目标:控制层采用springmvc、持久层使用mybatis实现。

5.1 需求

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

5.2 jar包

包括:spring(包括springmvc)、mybatis、mybatis-spring整合包、数据库驱动、第三方连接池。
参考:“mybatis与springmvc整合全部jar包”目录

5.3 工程搭建

5.3.1 整合思路

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配置事务。

表现层:

Springmvc.xml
1、包扫描器,扫描@Controller注解的类。
2、配置注解驱动。
3、视图解析器
Web.xml
配置前端控制器。

5.3.2 sqlMapConfig.xml

在classpath下创建mybatis/sqlMapConfig.xml

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

5.3.3 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="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="10" />
        <property name="maxIdle" value="5" />
    </bean>

    <!-- mapper配置 -->
    <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 加载mybatis的全局配置文件 -->
        <property name="configLocation" value="classpath:SqlMapConfig.xml" />
    </bean>

    <!-- 配置Mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.oath.dao"/>
    </bean>

</beans>

Db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springmvc?characterEncoding=utf-8
jdbc.username=root
jdbc.password=1234

5.3.4 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="cn.oath.service"/>

</beans>    

5.3.5 applicationContext-transaction.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:attributes>
    </tx:advice>

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

</beans>

5.3.6 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:dubbo="http://code.alibabatech.com/schema/dubbo"
    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://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 配置Controller注解扫描 -->
    <context:component-scan base-package="cn.oath.controller"/>

    <!-- 注解驱动:
    作用:替我们自动配置最新的注解的处理器映射器和处理器适配器
     -->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

5.3.7 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>ssm</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:ApplicationContext-*.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 配置前端控制器 -->
    <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.xml</param-value>
        </init-param>
        <!-- 在tomcat启动的时候就加载这个servlet -->
<!--        <load-on-startup>1</load-on-startup> -->
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>
</web-app>

5.4 Dao

mybatis逆向工程。

5.5 Service

1、Service由spring管理
2、spring对Service进行事务控制。

5.5.1 ItemService接口

public interface ItemsService {

    public List<Items> list() throws Exception;
}

5.5.2 ItemServiceImpl实现类

@Service
public class ItemsServiceImpl implements ItemsService {

    @Autowired
    private ItemsMapper itemsMapper;

    @Override
    public List<Items> list() throws Exception {
        //如果不需要任何查询条件,直接将example对象new出来即可
        ItemsExample example = new ItemsExample();
        List<Items> list = itemsMapper.selectByExampleWithBLOBs(example);
        return list;
    }

}

5.6 Controller(方式一:)

@Controller
public class ItemsController {

    @Autowired
    private ItemsService itmesService;

    @RequestMapping("/list")
    public ModelAndView itemsList() throws Exception{
        List<Items> list = itmesService.list();

        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("itemList", list);
        modelAndView.setViewName("itemList");

        return modelAndView;
    }

}

5.7 测试

访问:http://localhost:8080/ssm/list.action
这里写图片描述

6 参数绑定

6.1 绑定简单数据类型

6.1.1 需求

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

6.1.2 需求分析

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

6.1.3 Service

接口:public Items getItemById(Integer id);
实现类:
@Override
    public Items getItemById(Integer id) {
        Items items = itemsMapper.selectByPrimaryKey(id);
        return items;
    }

6.1.4 Controller参数绑定(方式二:)

要根据id查询商品数据,需要从请求的参数中把请求的id取出来。Id应该包含在Request对象中。可以从Request对象中取id。

/**
     * springMvc中默认支持的参数类型:也就是说在controller方法中可以加入这些也可以不加,  加不加看自己需不需要,都行.
     *HttpServletRequest
     *HttpServletResponse
     *HttpSession
     *Model
     */
    @RequestMapping("/itemEdit")
    public String itemEdit(HttpServletRequest request, HttpServletResponse response, 
            HttpSession session, Model model) {

        String idStr = request.getParameter("id");
        Items items = itmesService.getItemById(Integer.parseInt(idStr));

        //Model模型:模型中放入了返回给页面的数据
        //model底层其实就是用的request域来传递数据,但是对request域进行了扩展
        model.addAttribute("item", items);

        return "editItem";
    }

如果想获得Request对象只需要在Controller方法的形参中添加一个参数即可。Springmvc框架会自动把Request对象传递给方法。

6.1.5 默认支持的参数类型

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

6.1.5.1 HttpServletRequest

通过request对象获取请求信息

6.1.5.2 HttpServletResponse

通过response处理响应信息

6.1.5.3 HttpSession

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

6.1.5.4 Model/ModelMap

ModelMap是Model接口的实现类,通过Model或ModelMap向页面传递数据,如下:

//调用service查询商品信息
Items item = itemService.findItemById(id);
model.addAttribute(“item”, item);

页面通过${item.XXXX}获取item对象的属性值。
使用Model和ModelMap的效果一样,如果直接使用Model,springmvc会实例化ModelMap。
如果使用Model则可以不使用ModelAndView对象,Model对象可以向页面传递数据,View对象则可以使用String返回值替代。不管是Model还是ModelAndView,其本质都是使用Request对象向jsp传递数据。
如果使用Model则方法可以改造成:

@RequestMapping("/itemEdit")
    publicString itemEdit(HttpServletRequest request, Model model) {
        //从Request中取id
        String strId = request.getParameter("id");
        Integer id = null;
        //如果id有值则转换成int类型
        if (strId != null&& !"".equals(strId)) {
            id = newInteger(strId);
        } else {
            //出错
            returnnull;
        }
        Items items = itemService.getItemById(id);
        //创建ModelAndView
        //ModelAndView modelAndView = new ModelAndView();
        //向jsp传递数据
        //modelAndView.addObject("item", items);
        model.addAttribute("item", items);
        //设置跳转的jsp页面
        //modelAndView.setViewName("editItem");
        //return modelAndView;
        return"editItem";
    }

6.1.6 绑定简单类型

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

@RequestMapping("/itemEdit")
    public String itemEdit(Integer id, HttpServletResponse response, 
            HttpSession session, Model model) {

        Items items = itmesService.getItemById(id);

        //Model模型:模型中放入了返回给页面的数据
        //model底层其实就是用的request域来传递数据,但是对request域进行了扩展
        model.addAttribute("item", items);

        //设置跳转的jsp页面
        return "editItem";
    }
6.1.6.1 支持的数据类型

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

6.1.6.2 @RequestParam

使用@RequestParam常用于处理简单类型的绑定。

value:参数名字,即入参的请求参数名字,如value=“item_id”表示请求的参数区中的名字为item_id的参数的值将传入;
required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报;
TTP Status 400 - Required Integer parameter ‘XXXX’ is not present

defaultValue:默认值,表示如果请求中没有同名参数时的默认值

定义如下:
public String editItem(@RequestParam(value=”item_id”,required=true) String id) {

}

形参名称为id,但是这里使用value=”item_id”限定请求的参数名为item_id,所以页面传递参数的名必须为item_id。
注意:如果请求参数中没有item_id将跑出异常:
HTTP Status 500 - Required Integer parameter ‘item_id’ is not present

这里通过required=true限定item_id参数为必需传递,如果不传递则报400错误,可以使用defaultvalue设置默认值,即使required=true也可以不传item_id参数值

6.2 绑定pojo类型

6.2.1 需求

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

6.2.2 需求分析

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

6.2.3 使用pojo接收表单数据

如果提交的参数很多,或者提交的表单中的内容很多的时候可以使用pojo接收数据。要求pojo对象中的属性名和表单中input的name属性一致。
页面定义如下;


Pojo定义:

请求的参数名称和pojo的属性名称一致,会自动将请求参数赋值给pojo的属性。

下面两种接收表单数据的方式功能一样,一种为简单数据类型参数方式,一种为pojo方式:

/**
     * springMvc可以直接接收基本数据类型,包括string.spirngMvc可以帮你自动进行类型转换.
     * controller方法接收的参数的变量名称必须要等于页面上input框的name属性值
     */
    @RequestMapping("/updateitem")
    public String update(Integer id, String name, Float price, String detail) throws Exception {

        Items items = new Items();
        items.setId(id);
        items.setName(name);
        items.setPrice(price);
        items.setDetail(detail);
        items.setCreatetime(new Date());

        itmesService.updateItems(items);

        return "success";
    }

    /**
     * spirngMvc可以直接接收pojo类型:要求页面上input框的name属性名称必须等于pojo的属性名称
     * 如果Controller中接收的是Vo,那么页面上input框的name属性值要等于vo的属性.属性.属性.....
     */
    @RequestMapping("/updateitem")
    public String update(Items items) throws Exception {

        items.setCreatetime(new Date());

        itmesService.updateItems(items);

        return "success";
    }

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

6.2.4 解决post乱码问题

在web.xml中加入:

<!-- post乱码处理 -->
<filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</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"/>

get方法使用另外一种方法对参数进行重新编码:

(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")

ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码

6.3 绑定包装pojo

6.3.1 需求

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

6.3.2 需求分析

包装对象定义如下:

public class QueryVo {

    private Items items;
}

页面定义:

<input type="text" name="items.name" />
<input type="text" name="items.price" />

Controller方法定义如下:

public String useraddsubmit(Model model,QueryVoqueryVo)throws Exception{
    System.out.println(queryVo.getItems());
}

6.3.3 接收查询条件

    @RequestMapping("/queryitem")
    public String queryItem(QueryVo queryVo) {
        System.out.println(queryVo.getItems().getName());
        System.out.println(queryVo.getItems().getPrice());
        returnnull;
}

6.4 自定义参数绑定

6.4.1 需求

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

6.4.2 需求分析

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

6.4.3 自定义Converter

publicclass DateConverter implements Converter

6.4.4 配置Converter

<!-- 注解驱动:
    作用:替我们自动配置最新的注解的处理器映射器和处理器适配器
     -->
    <mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!-- 配置转换器 -->
    <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="cn.oath.converter.DateConverter"></bean>
            </set>
        </property>
    </bean>

6.4.5 配置方式2(了解)

<?xmlversion="1.0"encoding="UTF-8"?>
<beansxmlns="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:dubbo="http://code.alibabatech.com/schema/dubbo"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://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 扫描带Controller注解的类 -->
    <context:component-scanbase-package="cn.itcast.springmvc.controller"/>

    <!-- 转换器配置 -->
    <beanid="conversionService"
        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
        <propertyname="converters">
            <set>
                <beanclass="cn.itcast.springmvc.convert.DateConverter"/>
            </set>
        </property>
    </bean>
    <!-- 自定义webBinder -->
    <beanid="customBinder"  class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
        <propertyname="conversionService"ref="conversionService"/>
    </bean>
    <!--注解适配器 -->
    <beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
        <propertyname="webBindingInitializer"ref="customBinder"></property>
    </bean>
    <!-- 注解处理器映射器 -->
    <beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
    <!-- 加载注解驱动 -->
    <!-- <mvc:annotation-driven/> -->
    <!-- 视图解析器 -->
    <beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <propertyname="viewClass"
            value="org.springframework.web.servlet.view.JstlView"/>
        <!-- jsp前缀 -->
        <propertyname="prefix"value="/WEB-INF/jsp/"/>
        <!-- jsp后缀 -->
        <propertyname="suffix"value=".jsp"/>
    </bean>
</beans>

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

7 springmvc与struts2不同

1、 springmvc的入口是一个servlet即前端控制器,而struts2入口是一个filter过虑器。
2、 springmvc是基于方法开发(一个url对应一个方法),请求参数传递到方法的形参,可以设计为单例或多例(建议单例),struts2是基于类开发,传递参数是通过类的属性,只能设计为多例。
3、 Struts采用值栈存储请求和响应的数据,通过OGNL存取数据, springmvc通过参数解析器是将request请求内容解析,并给方法形参赋值,将数据和视图封装成ModelAndView对象,最后又将ModelAndView中的模型数据通过reques域传输到页面。Jsp视图解析器默认使用jstl。

总结:

springMvc:是一个表现层框架,
    作用:就是从请求中接收传入的参数,
         将处理后的结果数据返回给页面展示
2. ssm整合:
    1)Dao层
        pojo和映射文件以及接口使用逆向工程生成
        SqlMapConfig.xml   mybatis核心配置文件
        ApplicationContext-dao.xml 整合后spring在dao层的配置
            数据源
            会话工厂
            扫描Mapper
    2)service层
        事务          ApplicationContext-trans.xml
        @Service注解扫描    ApplicationContext-service.xml
    3)controller层
        SpringMvc.xml 
            注解扫描:扫描@Controller注解
            注解驱动:替我们显示的配置了最新版的处理器映射器和处理器适配器
            视图解析器:显示的配置是为了在controller中不用每个方法都写页面的全路径
    4)web.xml
        springMvc前端控制器配置
        spring监听

3.参数绑定(从请求中接收参数)重点
    1)默认类型:
        在controller方法中可以有也可以没有,看自己需求随意添加.
        httpservletRqeust,httpServletResponse,httpSession,Model(ModelMap其实就是Mode的一个子类
        ,一般用的不多)
    2)基本类型:string,double,float,integer,long.boolean
    3)pojo类型:页面上input框的name属性值必须要等于pojo的属性名称
    4)vo类型:页面上input框的name属性值必须要等于vo中的属性.属性.属性....
    5)自定义转换器converter:
        作用:由于springMvc无法将string自动转换成date所以需要自己手动编写类型转换器
        需要编写一个类实现Converter接口
        在springMvc.xml中配置自定义转换器
        在springMvc.xml中将自定义转换器配置到注解驱动上
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值