SpringMvc第一天

  1. SpringMvc介绍

  1. 定义

springMvc:是一个表现层框架,它是Spring框架的一部分.作用是从请求中接收传入的参数,及将处理后的结果数据返回给页面展示.

  1. 框架结构

 

架构流程

  1. 用户发送请求至前端控制器DispatcherServlet
  2. DispatcherServlet收到请求调用HandlerMapping处理器映射器。
  3. 处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。

    (处理器映射器就像一个map集合,key是用户在浏览器url中输入的地址,value是对应的方法对象.这时如果有拦截器则进行判断,符合要求则放行,否则就进行拦截)

  4. DispatcherServlet根据不同的处理器Handler通过HandlerAdapter处理器适配器调用处理器
  5. 执行处理器(Controller,也叫后端控制器)。
  6. Controller执行完成后返回ModelAndView
  7. HandlerAdapter处理器适配器将controller执行结果ModelAndView返回给DispatcherServlet
  8. DispatcherServlet将ModelAndView传给ViewReslover视图解析器
  9. ViewReslover解析后返回具体View
  10. DispatcherServlet对View视图进行渲染(即将模型数据填充至视图中)。
  11. 最后DispatcherServlet响应用户

 

3.组件说明

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

  • DispatcherServlet:前端控制器

用户请求到达前端控制器,它就相当于mvc模式中的cdispatcherServlet是整个流程控制的中心,由它调用其它组件处理用户的请求,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视图类型的支持,包括:jstlViewfreemarkerViewpdfView等。我们最常用的视图就是jsp

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

 

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

需要用户开发的组件有handlerview(controllerjsp)

 

  1. 入门程序

新建工程à导入springMvc独立运行的jar包à在web.xml中配置前端控制器à编写springMvc核心配置文件,pojo,controller,jsp

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>SpringMvc0523</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核心配置文件,那么默认会去找/WEB-INF/+<servlet-name>中的内容 + -servlet.xml配置文件 -->

    <!-- 定核心配置文件位置 -->

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

Tips: org.springframework.web.servlet.DispatcherServlet的位置如下:

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.itcast.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中指定页面路径的时候就不用写页面的完整路径名称了,可以直接写页面去掉扩展名的名称

    -->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <!-- 真正的页面路径 = 前缀 + 去掉后缀名的页面名称 + 后缀 -->

        <!-- 前缀 -->

        <property name="prefix" value="/WEB-INF/jsp/"></property>

        <!-- 后缀 -->

        <property name="suffix" value=".jsp"></property>

    </bean>

    

</beans>

Tips:

1.如果没有显示的配置处理器映射器和处理器适配那么springMvc会去默认的dispatcherServlet.properties中查找

dispatcherServlet.properties:

2. org.springframework.web.servlet.view.InternalResourceViewResolver:

如果没有配置视图解析器,那么在Controller中指定要返回的页面的位置时,都要写全网页的路径名称,如:

modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");

 

Items.java:

public class Items {

      

private Integer id;

private String name;

private Float price;

private String pic;

private Date createtime;

private String detail;

 

get,set方法

}

 

ItemsController:

@Controller

public class ItemsController {

    

    @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);

        

        //模型和视图

        //model模型:模型对象中存放了要返回给页面的数据

        //view视图:视图对象中指定了要返回的页面的位置

        ModelAndView modelAndView = new ModelAndView();

        

        //将要返回给页面的数据放入模型和视图对象中

        modelAndView.addObject("itemList", itemList);

        

        //指定要返回的页面的位置

        modelAndView.setViewName("itemList ");

        

        return modelAndView;

    }

} 

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>

  1. SSM的整合

  1. SpringMvc,Spring,Mybatis的整合

步骤:

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

 

创建工程,导入jar包(主要是Mybatis和Spring整合的jar包,因为SpringMvc和Spring都是Spring公司出的,不需要整合),再按整合步骤慢慢来:

Dao层:

先建立数据库(springmvc)和表:

再利用逆向工程生成pojo,映射文件以及接口:

StarServer:

public class StartServer {

    

    public void generator() throws Exception{

        List<String> warnings = new ArrayList<String>();

        boolean overwrite = true;

        File configFile = new File("generator.xml");

        ConfigurationParser cp = new ConfigurationParser(warnings);

        Configuration config = cp.parseConfiguration(configFile);

        DefaultShellCallback callback = new DefaultShellCallback(overwrite);

        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config,

                callback, warnings);

        myBatisGenerator.generate(null);

    }

    

    public static void main(String[] args) throws Exception {

        try {

            StartServer startServer = new StartServer();

            startServer.generator();

        } catch (Exception e) {

            e.printStackTrace();

        }

}

} 

Generator.xml:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE generatorConfiguration

PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"

"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

 

<generatorConfiguration>

    <context id="testTables" targetRuntime="MyBatis3">

        <commentGenerator>

            <!-- 是否去除自动生成的注释 true:是 false: -->

            <property name="suppressAllComments" value="true" />

        </commentGenerator>

        <!--数据库连接的信息:驱动类、连接地址、用户名、密码 -->

        <jdbcConnection driverClass="com.mysql.jdbc.Driver"

            connectionURL="jdbc:mysql://localhost:3306/springmvc" userId="root"

            password="root">

        </jdbcConnection>

        <!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"

            connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:yycg"

            userId="yycg"

            password="yycg">

        </jdbcConnection> -->

 

        <!-- 默认false,把JDBC DECIMAL NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL

            NUMERIC 类型解析为java.math.BigDecimal -->

        <javaTypeResolver>

            <property name="forceBigDecimals" value="false" />

        </javaTypeResolver>

 

        <!-- targetProject:生成PO类的位置 -->

        <javaModelGenerator targetPackage="cn.itheima.pojo"

            targetProject=".\src">

            <!-- enableSubPackages:是否让schema作为包的后缀 -->

            <property name="enableSubPackages" value="false" />

            <!-- 从数据库返回的值被清理前后的空格 -->

            <property name="trimStrings" value="true" />

        </javaModelGenerator>

<!-- targetProject:mapper映射文件生成的位置 -->

        <sqlMapGenerator targetPackage="cn.itheima.dao"

            targetProject=".\src">

            <!-- enableSubPackages:是否让schema作为包的后缀 -->

            <property name="enableSubPackages" value="false" />

        </sqlMapGenerator>

        <!-- targetPackagemapper接口生成的位置 -->

        <javaClientGenerator type="XMLMAPPER"

            targetPackage="cn.itheima.dao"

            targetProject=".\src">

            <!-- enableSubPackages:是否让schema作为包的后缀 -->

            <property name="enableSubPackages" value="false" />

        </javaClientGenerator>

        <!-- 指定数据库表 -->

<!--         <table tableName="items"></table> -->

        <table tableName="items"></table>

<!--         <table tableName="orderdetail"></table> -->

        <table tableName="user"></table>

        <!-- <table schema="" tableName="sys_user"></table>

        <table schema="" tableName="sys_role"></table>

        <table schema="" tableName="sys_permission"></table>

        <table schema="" tableName="sys_user_role"></table>

        <table schema="" tableName="sys_role_permission"></table> -->

        

        <!-- 有些表的字段需要指定java类型

         <table schema="" tableName="">

            <columnOverride column="" javaType="" />

        </table> -->

    </context>

</generatorConfiguration>

运行StarServer后:

将生成的这些文件复制到项目中.

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:

<?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 使用mybatisspring整合包中的 -->

    <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.itheima.dao"/>

    </bean>

</beans>

Service层:

事务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:attributes>

    </tx:advice>

    

    <!-- 切面 -->

    <aop:config>

        <aop:advisor advice-ref="txAdvice"

            pointcut="execution(* cn.itheima.service.*.*(..))" />

    </aop:config>

    

</beans>

@Service注解扫描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.itheima.service"></context:component-scan>

</beans>

controller层:

SpringMvc.xml:

注解扫描:扫描@Controller注解

注解驱动:替我们显示地配置了最新版的处理器映射器和处理器适配器

视图解析器:显示的配置是为了在controller中不用每个方法都写页面的全路径

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

 

<!-- 注解驱动:

        替我们显示的配置了最新版的注解的处理器映射器和处理器适配器 -->

<mvc:annotation-driven></mvc:annotation-driven>

 

<!-- 配置视图解析器

    作用:controller中指定页面路径的时候就不用写页面的完整路径名称了,可以直接写页面去掉扩展名的名称

    -->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <!-- 真正的页面路径 = 前缀 + 去掉后缀名的页面名称 + 后缀 -->

        <!-- 前缀 -->

        <property name="prefix" value="/WEB-INF/jsp/"></property>

        <!-- 后缀 -->

        <property name="suffix" value=".jsp"></property>

    </bean>

</beans>

web.xml:

springMvc前端控制器配置

spring监听

<?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>ssm0523</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>

 

<!-- SpringMvc前端控制器 -->

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

  1. 整合后的测试

新建controller,service接口及其实现类,将页面复制过来:

itemsController:

@Controller

public class itemsController {

 

    @Autowired

    private ItemsService itemService;

    

    @RequestMapping("/list")

    public ModelAndView itemsList() throws Exception{

        

        List<Items> itemList = itemService.list();

        

        ModelAndView modelAndView = new ModelAndView();

        modelAndView.addObject("itemList", itemList);

        modelAndView.setViewName("itemList");

        

        return modelAndView;

    }

}

Tips: @Autowired@Resource: @Autowired为自动装配,所以如果该接口只有一个实现类,用哪个注解都可以,但如果该接口有多个实现类,那只能用@Resource.

ItemsServiceImpl:

@Service

public class ItemsServiceImpl implements ItemsService{

    

    @Autowired

    private ItemsMapper itemsMapper;

 

    public List<Items> list() {

        //如果不需要任何查询条件,直接将example对象new出来即可

        ItemsExample example = new ItemsExample();

        List<Items> list = itemsMapper.selectByExampleWithBLOBs(example );

        return list;

    }

}

Tips:

不用selectByExample(example)方法,是因为items中的detail是大文本类型,若用了该方法,则查询不出该字段.

  1. 参数绑定

  1. 默认支持的类型

需求:在商品列表页面点击"修改"按钮时,页面跳转到修改页面(将要修改的商品信息展示出来).

itemsController:

@Controller

public class itemsController {

 

    @Autowired

    private ItemsService itemService;

    

    @RequestMapping("/list")

    public ModelAndView itemsList() throws Exception{…}

 

    /**

     *springMvc中默认支持的参数类型:也就是说在controller方法中可以加入这些也可以不加, 加不加看自己需不需要,都行.

     *HttpServletRequest

     *HttpServletResponse

     *HttpSession

     *Model

     */

    @RequestMapping("itemEdit")

    public String itemEdit(HttpServletRequest request, HttpServletResponse response,

            HttpSession session, Model model) throws Exception{

        

        String idStr = request.getParameter("id");

        

        Items items = itemService.findItemsById(Integer.parseInt(idStr));

        

        //Model模型:模型中放入了返回给页面的数据

        //model底层其实就是用的request域来传递数据,但是对request域进行了扩展.

        model.addAttribute("item",items);

        

        //如果springMvc方法返回一个简单的string字符串,那么springMvc就会认为这个字符串就是页面的名称

        return "editItem";

    }

} 

Tips:因为用getParameter方法从页面接收过来的数据都会变成String类型,而id是Integer类型的,所以要进行转换.

ItemsServiceImpl:

@Service

public class ItemsServiceImpl implements ItemsService{

    

    @Autowired

    private ItemsMapper itemsMapper;

 

    @Override

    public List<Items> list() {…}

 

    @Override

    public Items findItemsById(Integer id) {

        Items items = itemsMapper.selectByPrimaryKey(id);

        return items;

    }

} 

  1. 基本类型

需求:修改指定的商品信息.

itemsController:

@Controller

public class itemsController {

 

    @Autowired

    private ItemsService itemService;

    

    @RequestMapping("/list")

    public ModelAndView itemsList() throws Exception{…}

    

    /**

     *springMvc中默认支持的参数类型:也就是说在controller方法中可以加入这些也可以不加, 加不加看自己需不需要,都行.

     *HttpServletRequest

     *HttpServletResponse

     *HttpSession

     *Model

     */

    @RequestMapping("itemEdit")

    public String itemEdit(HttpServletRequest request, HttpServletResponse response,

            HttpSession session, Model model) throws Exception{…}

    

    //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());

        

        itemService.update(items);

        

        return"success";

    }

} 

Tips:参数列表中的参数都是从页面传过来的,虽然修改页面的日期被注释掉了,但仍要给他new个日期,因为该字段在数据库中被设置为非空.

补充(了解即可):

一般controller方法接收的参数的变量名称必须要等于页面上input框的name属性值,但如果加了@RequestParam("input框的name属性值")的话,参数名称就随便写了:

ItemsServiceImpl:

@Service

public class ItemsServiceImpl implements ItemsService{

    

    @Autowired

    private ItemsMapper itemsMapper;

 

    @Override

    public List<Items> list() {…}

 

    @Override

    public Items findItemsById(Integer id) {…}

 

    @Override

    public void update(Items items) {

        itemsMapper.updateByPrimaryKeyWithBLOBs(items);

    }

} 

Tips:用updateByPrimaryKeyWithBLOBs(items)是因为用反向工程生成的ItemsMapper.xml中类似的其他方法不能查询到Items中的detail属性(大文本格式),而该方法可以:

在浏览器url中输入的地址及后面带参数的,都是get请求,表单提交,修改和保存的都是post请求.在此,是post请求,会出现乱码问题,因此要解决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>

 

解决get请求乱码的问题有以下两种方法:

  1. 修改tomcat配置文件添加编码与工程编码一致,如下:

 

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

 

②对参数进行重新编码:

String userName new

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

 

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

  1. Pojo类型

ItemsController:

@Controller

public class itemsController {

 

    @Autowired

    private ItemsService itemService;

 

    //springMvc可以直接接收基本数据类型,包括string.spirngMvc可以帮你自动进行类型转换.

    //controller方法接收的参数的变量名称必须要等于页面上input框的name属性值

    //spirngMvc可以直接接收pojo类型:要求页面上input框的name属性名称必须等于pojo的属性名称

    @RequestMapping("updateitem")

    public String update(Items items) throws Exception{

        

        items.setCreatetime(new Date());

        

        itemService.update(items);

        

        return"success";

    }

}

Tips: spirngMvc可以直接接收pojo类型:要求页面上input框的name属性名称必须等于pojo的属性名称!!!

  1. 接收VO

应用场景:比如需要进行高级查询时,既要通过商品信息进行查询,也还可能要用用户信息和其他信息进行查询,这时用pojo类接收是不够的,应该用vo(封装类)接收.

新建一个vo包:

QueryVo:

package cn.itheima.vo;

 

import cn.itheima.pojo.Items;

 

public class QueryVo {

    

    //商品对象

    private Items items;

    

    //用户对象...

    //订单对象...

 

    public Items getItems() {

        return items;

    }

    public void setItems(Items items) {

        this.items = items;

    }

}

ItemsController:

@Controller

public class itemsController {

 

    @Autowired

    private ItemsService itemService;

    

    @RequestMapping("/list")

    public ModelAndView itemsList() throws Exception{…}

    

    /**

     *springMvc中默认支持的参数类型:也就是说在controller方法中可以加入这些也可以不加, 加不加看自己需不需要,都行.

     *HttpServletRequest

     *HttpServletResponse

     *HttpSession

     *Model

     */

    @RequestMapping("itemEdit")

    public String itemEdit(HttpServletRequest request, HttpServletResponse response,

            HttpSession session, Model model) throws Exception{…}

    

    //springMvc可以直接接收基本数据类型,包括string.spirngMvc可以帮你自动进行类型转换.

    //controller方法接收的参数的变量名称必须要等于页面上input框的name属性值

    //spirngMvc可以直接接收pojo类型:要求页面上input框的name属性名称必须等于pojo的属性名称

    @RequestMapping("updateitem")

    public String update(Items items) throws Exception{…}

    

    //如果Controller中接收的是Vo,那么页面上input框的name属性值要等于vo的属性.属性.属性.....

    @RequestMapping("/search")

    public String search(QueryVo vo) throws Exception{

        

        System.out.println(vo);

        return "";

    }

} 

ItemList页面中:

查询条件:

<table width="100%" border=1>

<tr>

<!-- 如果Controller中接收的是Vo,那么页面上input框的name属性值要等于vo的属性.属性.属性..... -->

<td>商品名称:<input type="text" name="items.name"/></td>

<td>商品价格:<input type="text" name="items.price"/></td>

<td><input type="submit" value="查询"/></td>

</tr>

</table>

打断点测试,是有值的:

  1. 自定义转换器

createTime为Date类型,且此字段在数据库中被设置为非空.若将Controller中update()里对createTime的处理注释掉, 放开修改页面中对createTime修改语句的注释,此时启动服务器,在修改页面对createTime进行修改,则会报错.原因是createTime是Date类型,页面传过来的是String类型,而Controller中没有将String转换为Date,所以会报错:

 

 

这时候我们需要自定义转换器:

新建个转换器包,在包下新建一个自定义的全局的String到Date的转换器类:

CustomGlobalStrToDateConverter:

import org.springframework.core.convert.converter.Converter;

/**

* String:

* Date:目标

* @author Tan

*

*/

public class CustomGlobalStrToDateConverter implements Converter<String, Date> {

 

    @Override

    public Date convert(String source) {

        

        try {

            

            Date date = new SimpleDateFormat("yy-MM-DD hh:mm:ss").parse(source);

            return date;

            

        } catch (ParseException e) {

            e.printStackTrace();

        }    

        return null;

    }

}

Tips:不熟悉SimpleDateFormat()相关方法的话,自行查阅JDK文档.

写完自定义转换器类后,要在SpringMvc.xml中进行配置:

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>

 

<!-- 注解驱动:

        替我们显示的配置了最新版的注解的处理器映射器和处理器适配器 -->

<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

 

<!-- 配置视图解析器

    作用:controller中指定页面路径的时候就不用写页面的完整路径名称了,可以直接写页面去掉扩展名的名称

    -->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

        <!-- 真正的页面路径 = 前缀 + 去掉后缀名的页面名称 + 后缀 -->

        <!-- 前缀 -->

        <property name="prefix" value="/WEB-INF/jsp/"></property>

        <!-- 后缀 -->

        <property name="suffix" value=".jsp"></property>

    </bean>

    <!-- 配置自定义转换器

    注意: 一定要将自定义的转换器配置到注解驱动上

    -->

    <bean id="conversionService"

        class="org.springframework.format.support.FormattingConversionServiceFactoryBean">

        <property name="converters">

            <set>

                <!-- 指定自定义转换器的全路径名称 -->

                <bean class="cn.itheima.controller.converter.CustomGlobalStrToDateConverter"/>

            </set>

        </property>

    </bean>

</beans>

五.SpringMvc和Struts2的区别

从接收数据和向页面传递数据两个方面进行简单说明:

接收数据:

Struts2用模型/属性驱动接收数据,model/属性都是全局变量,全局变量中存放着数据,Action中的任何方法都可以用,因此线程不安全,因此Action才要做成多例的;

而SpringMvc用局部变量接收数据,线程安全,因此Controller是单例的.(没必要开多例,浪费资源).

向页面传递数据:

Struts2通过值栈向页面传递数据;

而SpringMvc通过model向页面传递数据,model底层采用的是request域.

 

较为官方的解释:

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

六.总结

1. 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中将自定义转换器配置到注解驱动上

 

最终目录结构:

转载于:https://www.cnblogs.com/beihai2018/p/8721477.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值