SpringMVC和Mybatis整合(前端控制器、处理器映射器、处理器适配器、视图解析器学习)

柔光的暖阳◎ 2022-05-13 14:36 280阅读 0赞

什么是SpringMVC ?

springmvc是spring框架的一个模块,springmvc和spring无需通过中间整合层进行整合。springmvc是一个基于mvc的web框架。下面通过一张图来了解springmvc框架.

70

图源: 《传智播客》

SpringMVC**的工作原理**

· 发起请求到前端控制器(DispatcherServlet)

· 前端控制器请求HandlerMapping查找 Handler。可以根据xml配置、注解进行查找

· 处理器映射器HandlerMapping向前端控制器返回Handler

· 前端控制器调用处理器适配器去执行Handler

· 处理器适配器去执行Handler

· Handler执行完成给适配器返回ModelAndView

· 处理器适配器向前端控制器返回ModelAndView。ModelAndView是springmvc框架的一个底层对象,包括 Model和view

· 前端控制器请求视图解析器去进行视图解析。根据逻辑视图名解析成真正的视图(jsp)

· 视图解析器向前端控制器返回View

· 前端控制器进行视图渲染。视图渲染将模型数据(在ModelAndView对象中)填充到request域

· 前端控制器向用户响应结果


下面通过SpringMVC和Mybatis整合的一个入门程序,了解springmvc框架原理,对前端控制器、处理器映射器、处理器适配器、视图解析器学习。区别非注解的处理器映射器、处理器适配器与注解,的处理器映射器、处理器适配器(要求掌握)。在实际开发中建议使用后者注解开发,简化代码,降低程序维护难度。

Springmvc+Mybatis整合思路

Springmvc+Mybatis系统架构

70 1

图源:《传智播客》

简单解释一下上图:

第一步:整合dao层

  1. ·mybatisspring整合,通过spring管理mapper接口。
  2. ·使用mapper的扫描器自动扫描mapper接口在spring中进行注册。

第二步:整合service层

  1. ·通过spring管理 service接口。
  2. ·使用配置方式将service接口配置在spring配置文件中。
  3. ·实现事务控制。

第三步:整合springmvc

  1. ·由于springmvcspring的模块,不需要整合。

搭建工程结构

1.在src下创建4个空包

·cn.ssm.xhchen.controller 放置业务逻辑控制

·cn.ssm.xhchen.mapper 放置mapper接口和映射文件

·cn.ssm.xhchen.po 放置Java实体类

·cn.ssm.xhchen.service 放置业务逻辑管理

2.创建资源文件夹config与src同级

·【config/mybatis】 创建名为“SqlMapContext.xml”的mybatis全局配置文件

·【config/spring】 创建名为“applicationContext-dao.xml”全局数据源配置文件

·【config/spring】 创建名为“applicationContext-service.xml”全局业务逻辑管理配置文件

·【config/spring】 创建名为“applicationContext-transaction.xml”全局事务管理配置文件

·【config/spring】 创建名为“springmvc.xml”mvc核心配置文件

·【config】创建名为db.properties数据源文件和log4j.properties日志文件

3.创建两个jsp页面

·【WEB-INF/jsp/items】创建名为“itemsList.jsp”的商品列表

·【WEB-INF/jsp/items】创建名为“editItems.jsp”的更新商品列表

70 2 70 3

工程环境搭建

70 470 5

整合dao

mybatis配置文件

  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
  3. <configuration>
  4. <!-- 数据源交给spring配置 -->
  5. <!-- settings -->
  6. <settings>
  7. <!-- 打开延迟加载的开关 -->
  8. <setting name="lazyLoadingEnabled" value="true" />
  9. <!-- 将积极加载改为消极加载 -->
  10. <setting name="aggressiveLazyLoading" value="false" />
  11. <!-- 打开全局缓存开关(二级缓存)默认值就是 true -->
  12. <setting name="cacheEnabled" value="true" />
  13. </settings>
  14. <!-- 配置别名 -->
  15. <typeAliases>
  16. <package name="cn.ssm.xhchen.po"/>
  17. </typeAliases>
  18. <!-- mapper配置交给spring包扫描 -->
  19. </configuration>

配置数据源(applicationContext-dao.xml)

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

  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:context="http://www.springframework.org/schema/context"
  4. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/tx
  8. http://www.springframework.org/schema/tx/spring-tx.xsd
  9. http://www.springframework.org/schema/aop
  10. http://www.springframework.org/schema/aop/spring-aop.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context.xsd">
  13. <!-- 加载db.properties数据原文件 -->
  14. <context:property-placeholder location="classpath:db.properties" />
  15. <!-- 配置数据源 -->
  16. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  17. <property name="driverClassName" value=" ${jdbc.driver}" />
  18. <property name="url" value="${jdbc.url}" />
  19. <property name="username" value="${jdbc.username}" />
  20. <property name="password" value="${jdbc.password}" />
  21. </bean>
  22. <!-- 配置sqlSessionFactory -->
  23. <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  24. <!-- 数据连接池 -->
  25. <property name="dataSource" ref="dataSource"></property>
  26. <!-- 加载 SqlMapConfig 的全局配置文件-->
  27. <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml"></property>
  28. </bean>
  29. <!-- 配置mapper扫描器 -->
  30. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
  31. <!-- 扫描包路径 -->
  32. <property name="basePackage" value="cn.ssm.xhchen.mapper"></property>
  33. <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
  34. </bean>
  35. </beans>

cn.ssm.xhchen.po

创建商品实体类Items.java

创建商品信息po拓展类ItemsCustomer.java

创建商品信息包装类ItemsQueryVo.java

Items.java

  1. package cn.ssm.xhchen.po;
  2. /**
  3. *
  4. * ClassName: Items
  5. *
  6. * @Description: 商品实体类
  7. * @author XHChen
  8. * @date 2018年10月17日 下午5:09:14
  9. */
  10. public class Items {
  11. private Integer id; // 商品主键
  12. private String items_name; // 商品名称
  13. private String items_detail; // 商品明细
  14. private Double items_price; // 商品价格
  15. public Integer getId() {
  16. return id;
  17. }
  18. public void setId(Integer id) {
  19. this.id = id;
  20. }
  21. public String getItems_name() {
  22. return items_name;
  23. }
  24. public void setItems_name(String items_name) {
  25. this.items_name = items_name;
  26. }
  27. public String getItems_detail() {
  28. return items_detail;
  29. }
  30. public void setItems_detail(String items_detail) {
  31. this.items_detail = items_detail;
  32. }
  33. public Double getItems_price() {
  34. return items_price;
  35. }
  36. public void setItems_price(Double items_price) {
  37. this.items_price = items_price;
  38. }
  39. @Override
  40. public String toString() {
  41. return "Items [id=" + id + ", items_name=" + items_name
  42. + ", items_detail=" + items_detail + ", items_price="
  43. + items_price + "]";
  44. }
  45. }

ItemsCustomer.java

  1. package cn.ssm.xhchen.po;
  2. import java.util.Date;
  3. /**
  4. *
  5. * ClassName: Items
  6. *
  7. * @Description: 商品信息po拓展类
  8. * @author XHChen
  9. * @date 2018年10月17日 下午5:09:14
  10. */
  11. public class ItemsCustomer extends Items {
  12. // 添加拓展属性
  13. private Date items_creattime; // 商品生产时间
  14. public Date getItems_creattime() {
  15. return items_creattime;
  16. }
  17. public void setItems_creattime(Date items_creattime) {
  18. this.items_creattime = items_creattime;
  19. }
  20. @Override
  21. public String toString() {
  22. return "ItemsCustomer [toString()=" + super.toString()
  23. + ", items_creattime=" + items_creattime + "]";
  24. }
  25. }

ItemsQueryVo.java

  1. package cn.ssm.xhchen.po;
  2. /**
  3. *
  4. * ClassName: ItemsQueryVo
  5. *
  6. * @Description: 商品信息包装类
  7. * @author XHChen
  8. * @date 2018年10月17日 下午8:03:46
  9. */
  10. public class ItemsQueryVo {
  11. // 商品信息
  12. private Items items;
  13. // 系统拓展性,对原始po进行拓展
  14. private ItemsCustomer itemsCustomer;
  15. public Items getItems() {
  16. return items;
  17. }
  18. public void setItems(Items items) {
  19. this.items = items;
  20. }
  21. public ItemsCustomer getItemsCustomer() {
  22. return itemsCustomer;
  23. }
  24. public void setItemsCustomer(ItemsCustomer itemsCustomer) {
  25. this.itemsCustomer = itemsCustomer;
  26. }
  27. @Override
  28. public String toString() {
  29. return "ItemsQueryVo [items=" + items + ", itemsCustomer="
  30. + itemsCustomer + "]";
  31. }
  32. }

cn.ssm.xhchen.mapper

创建Items的mapper.xml配置文件ItemsMapper.xml

创建ItemsMapper的拓展mapper.xml配置文件ItemsMapperCustomer.xml

创建Items的mapper接口ItemsMapper.java

创建ItemsMapper的拓展mapper接口ItemsMapperCustomer.java

ItemsMapper.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <mapper namespace="cn.ssm.xhchen.mapper.ItemsMapper">
  4. <!-- 添加数据 -->
  5. <insert id="insertItems" parameterType="cn.ssm.xhchen.po.Items">
  6. <!-- id自动增长 -->
  7. <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
  8. SELECT
  9. LAST_INSERT_ID()
  10. </selectKey>
  11. <!-- 插入sql语句 -->
  12. insert into items(items_name,items_detail,items_price) values(#{items_name},#{items_detail},#{items_price})
  13. </insert>
  14. <!-- 修改数据 -->
  15. <update id="updateItems" parameterType="cn.ssm.xhchen.po.Items">
  16. <!-- 插入修改sql语句 -->
  17. update items set items_name=#{items_name}, items_detail=#{items_detail}, items_price=#{items_price} where id=#{id}
  18. </update>
  19. <!-- 删除数据 -->
  20. <delete id="deleteItems" parameterType="cn.ssm.xhchen.po.Items">
  21. <!-- 插入删除语句 -->
  22. delete from items where id=#{id}
  23. </delete>
  24. <!-- 通过id查询 -->
  25. <select id="findItemsById" parameterType="java.lang.Integer" resultType="cn.ssm.xhchen.po.Items">
  26. <!-- 插入查询语句 -->
  27. select * from items where id=#{id}
  28. </select>
  29. </mapper>

ItemsMapperCustomer.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3. <!-- ItemsMapper的拓展mapper -->
  4. <mapper namespace="cn.ssm.xhchen.mapper.ItemsMapperCustomer">
  5. <!-- sql片段 -->
  6. <sql id="where_query_Items">
  7. <!-- 使用动态sql,满足条件进行sql拼接 -->
  8. <!-- 商品信息通过 ItemsQueryVo包装类中的ItemsCustomer传递 -->
  9. <if test="itemsCustomer != null">
  10. <if test="itemsCustomer.items_name != null and itemsCustomer.items_name != ''">
  11. items_name like '%${itemsCustomer.items_name}%';
  12. </if>
  13. </if>
  14. </sql>
  15. <!-- 商品列表查询 parameterType:商品信息包装类 resultType:商品信息po拓展类 -->
  16. <select id="findItemsList" parameterType="cn.ssm.xhchen.po.ItemsQueryVo" resultType="cn.ssm.xhchen.po.ItemsCustomer">
  17. select * from items
  18. <where>
  19. <include refid="where_query_Items"></include>
  20. </where>
  21. </select>
  22. </mapper>

ItemsMapper.java

  1. package cn.ssm.xhchen.mapper;
  2. import cn.ssm.xhchen.po.Items;
  3. /**
  4. *
  5. * ClassName: ItemsMapper
  6. *
  7. * @Description: Items的mapper接口
  8. * @author XHChen
  9. * @date 2018年10月17日 下午5:11:51
  10. */
  11. public interface ItemsMapper {
  12. // 添加
  13. public void insertItems(Items items) throws Exception;
  14. // 修改
  15. public void updateItems(Items items) throws Exception;
  16. // 删除
  17. public void deleteItems(int id) throws Exception;
  18. // 通过id查询
  19. public Items findItemsById(int id) throws Exception;
  20. }

ItemsMapperCustomer.java

  1. package cn.ssm.xhchen.mapper;
  2. import java.util.List;
  3. import cn.ssm.xhchen.po.ItemsCustomer;
  4. import cn.ssm.xhchen.po.ItemsQueryVo;
  5. /**
  6. *
  7. * ClassName: ItemsMapper
  8. *
  9. * @Description: ItemsMapper的拓展mapper接口
  10. * @author XHChen
  11. * @date 2018年10月17日 下午5:11:51
  12. */
  13. public interface ItemsMapperCustomer {
  14. // 商品列表查询
  15. public List<ItemsCustomer> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
  16. }

整合service

cn.ssm.xhchen.service

创建Items管理接口ItemsService.java

创建Items管理实现ItemsServiceImpl.java

ItemsService.java

  1. package cn.ssm.xhchen.service;
  2. import java.util.List;
  3. import cn.ssm.xhchen.po.ItemsCustomer;
  4. import cn.ssm.xhchen.po.ItemsQueryVo;
  5. /**
  6. *
  7. * ClassName: ItemsService
  8. *
  9. * @Description: Items管理接口
  10. * @author XHChen
  11. * @date 2018年10月17日 下午8:49:43
  12. */
  13. public interface ItemsService {
  14. /**
  15. *
  16. * @Description: 商品列表查询
  17. * @param @param itemsQueryVo 封装商品信息的类
  18. * @param @return
  19. * @param @throws Exception
  20. * @return List<ItemsCustomer> 数据库返回的值映射到ItemsCustomer
  21. * @throws
  22. * @author XHChen
  23. * @date 2018年10月20日 下午8:23:28
  24. */
  25. public List<ItemsCustomer> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
  26. /**
  27. *
  28. * @Description: 找到修改商品信息
  29. * @param @param id 查询商品的id
  30. * @param @return
  31. * @param @throws Exception
  32. * @return ItemsCustomer
  33. * @throws
  34. * @author XHChen
  35. * @date 2018年10月20日 下午8:23:06
  36. */
  37. public ItemsCustomer findItemsById(Integer id) throws Exception;
  38. /**
  39. *
  40. * @Description: 修改商品信息
  41. * @param @param id 修改商品的id
  42. * @param @param itemsCustomer 修改商品的信息
  43. * @param @throws Exception
  44. * @return void
  45. * @throws
  46. * @author XHChen
  47. * @date 2018年10月20日 下午8:23:00
  48. */
  49. public void updateItems(Integer id, ItemsCustomer itemsCustomer) throws Exception;
  50. }

ItemsServiceImpl.java

  1. package cn.ssm.xhchen.service.impl;
  2. import java.util.List;
  3. import org.springframework.beans.BeanUtils;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import cn.ssm.xhchen.mapper.ItemsMapper;
  6. import cn.ssm.xhchen.mapper.ItemsMapperCustomer;
  7. import cn.ssm.xhchen.po.Items;
  8. import cn.ssm.xhchen.po.ItemsCustomer;
  9. import cn.ssm.xhchen.po.ItemsQueryVo;
  10. import cn.ssm.xhchen.service.ItemsService;
  11. /**
  12. *
  13. * ClassName: ItemsServiceImpl
  14. *
  15. * @Description: Items管理实现
  16. * @author XHChen
  17. * @date 2018年10月17日 下午8:50:58
  18. */
  19. public class ItemsServiceImpl implements ItemsService {
  20. // applicationContext-dao.xml已通过包扫描配置了ItemsMapperCustomer
  21. @Autowired
  22. private ItemsMapperCustomer itemsMapperCustomer;
  23. // 自动注入ItemsMapper接口
  24. @Autowired
  25. private ItemsMapper itemsMapper;
  26. @Override
  27. /**
  28. * 通过itemsQueryVo查询商品信息
  29. */
  30. public List<ItemsCustomer> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception {
  31. // 通过ItemsMapperCustomer查询数据库
  32. return itemsMapperCustomer.findItemsList(itemsQueryVo);
  33. }
  34. @Override
  35. /**
  36. * 根据id查询商品信息
  37. */
  38. public ItemsCustomer findItemsById(Integer id) throws Exception {
  39. // 根据id查询商品信息
  40. Items items = itemsMapper.findItemsById(id);
  41. // 创建ItemsCustomer对象
  42. ItemsCustomer itemsCustomer = new ItemsCustomer();
  43. // 把商品信息items复制到itemsCustomer
  44. BeanUtils.copyProperties(items, itemsCustomer);
  45. // 返回拓展类ItemsCustomer
  46. return itemsCustomer;
  47. }
  48. @Override
  49. /**
  50. * 修改商品信息
  51. */
  52. public void updateItems(Integer id, ItemsCustomer itemsCustomer) throws Exception {
  53. // 一堆代码逻辑
  54. // ......
  55. // 设置修改商品id
  56. itemsCustomer.setId(id);
  57. // 修改商品信息
  58. itemsMapper.updateItems(itemsCustomer);
  59. }
  60. }

配置service(applicationContext-service.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:context="http://www.springframework.org/schema/context"
  4. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/tx
  8. http://www.springframework.org/schema/tx/spring-tx.xsd
  9. http://www.springframework.org/schema/aop
  10. http://www.springframework.org/schema/aop/spring-aop.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context.xsd">
  13. <!-- 配置商品管理的service -->
  14. <bean id="itemsService" class="cn.ssm.xhchen.service.impl.ItemsServiceImpl"></bean>
  15. </beans>

事务控制(applicationContext-transaction.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:context="http://www.springframework.org/schema/context"
  4. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans
  6. http://www.springframework.org/schema/beans/spring-beans.xsd
  7. http://www.springframework.org/schema/tx
  8. http://www.springframework.org/schema/tx/spring-tx.xsd
  9. http://www.springframework.org/schema/aop
  10. http://www.springframework.org/schema/aop/spring-aop.xsd
  11. http://www.springframework.org/schema/context
  12. http://www.springframework.org/schema/context/spring-context.xsd">
  13. <!-- 配置事务管理器 -->
  14. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  15. <!-- 链接数据源,applicationContext-dao.xml中已经实现 -->
  16. <property name="dataSource" ref="dataSource"></property>
  17. </bean>
  18. <!-- 通知 -->
  19. <tx:advice id="txAdvice" transaction-manager="transactionManager">
  20. <tx:attributes>
  21. <tx:method name="save*" isolation="DEFAULT"/>
  22. <tx:method name="delete*" isolation="DEFAULT"/>
  23. <tx:method name="insert*" isolation="DEFAULT"/>
  24. <tx:method name="update*" isolation="DEFAULT"/>
  25. <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
  26. <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
  27. <tx:method name="select*" propagation="SUPPORTS" read-only="true"/>
  28. </tx:attributes>
  29. </tx:advice>
  30. <!-- aop -->
  31. <aop:config>
  32. <aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.ssm.xhchen.service.impl.*.*(..))"/>
  33. </aop:config>
  34. </beans>

SpringMVC注解开发

配置前端控制器

在web.xml下配置前端控制器

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
  3. <web-app id="WebApp_ID">
  4. <display-name>springmvc_mybatis</display-name>
  5. <!-- 加载spring容器 param-value:在tomcat项目下的路径 -->
  6. <context-param>
  7. <param-name>contextConfigLocation</param-name>
  8. <param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
  9. </context-param>
  10. <!-- 解决post全局乱码 -->
  11. <filter>
  12. <filter-name>CharacterEncodingFilter</filter-name>
  13. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  14. <init-param>
  15. <param-name>encoding</param-name>
  16. <param-value>utf-8</param-value>
  17. </init-param>
  18. </filter>
  19. <filter-mapping>
  20. <filter-name>CharacterEncodingFilter</filter-name>
  21. <url-pattern>/*</url-pattern>
  22. </filter-mapping>
  23. <!-- 配置监听器 -->
  24. <listener>
  25. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  26. </listener>
  27. <!-- 配置前端控制器 -->
  28. <servlet>
  29. <servlet-name>springmvc</servlet-name>
  30. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  31. <!-- contextConfigLocation配置springmvc加载的配置文件 -->
  32. <init-param>
  33. <param-name>contextConfigLocation</param-name>
  34. <param-value>classpath:spring/springmvc.xml</param-value>
  35. </init-param>
  36. </servlet>
  37. <!-- *.action,访问以.action结尾由DispatcherServlet解析 -->
  38. <servlet-mapping>
  39. <servlet-name>springmvc</servlet-name>
  40. <url-pattern>*.action</url-pattern>
  41. </servlet-mapping>
  42. <welcome-file-list>
  43. <welcome-file>index.html</welcome-file>
  44. <welcome-file>index.htm</welcome-file>
  45. <welcome-file>index.jsp</welcome-file>
  46. <welcome-file>default.html</welcome-file>
  47. <welcome-file>default.htm</welcome-file>
  48. <welcome-file>default.jsp</welcome-file>
  49. </welcome-file-list>
  50. </web-app>

配置注解处理器适配器

在classpath下的springmvc.xml中配置处理器适配器(之后不再导入约束)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  8. http://www.springframework.org/schema/mvc
  9. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context-4.0.xsd
  12. http://www.springframework.org/schema/aop
  13. http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  14. http://www.springframework.org/schema/tx
  15. http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  16. http://www.springframework.org/schema/util
  17. http://www.springframework.org/schema/util/spring-util-4.0.xsd">
  18. <!-- 注解配置处理器适配器 -->
  19. <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>
  20. </beans>

开发注解Handler(不做参数绑定演示)

在cn.ssm.xhchen.controller下创建ItemsController.java,需要实现 controller接口,才能由org.springframework.web.servlet.mvc.RequestMappingHandlerAdapter适配器执行

@controller注解必须要加,标识类是一个Handler处理器。

  1. @Controller
  2. public class ItemsController {}

@requestMapping注解必须要加,作用:

· 对url和Handler的方法进行映射(一般url名称与方法名称保持一致)。

  1. @RequestMapping("/queryItems.action")
  2. public ModelAndView queryItems() throws Exception {}

· 可以窄化请求映射,设置Handler的根路径,url就是根路径+子路径请求方式

  1. @Controller
  2. // 窄化请求映射,对url进行分类管理
  3. @RequestMapping("/items")
  4. public class ItemsController {}

· 可以限制http请求的方法

  1. // 限制http请求方法,限定表单POST请求
  2. // @RequestMapping(value="/queryItems.action",method={RequestMethod.POST})
  3. // 限制http请求方法,限定表单POST/GET请求
  4. @RequestMapping(value = "/queryItems.action", method = { RequestMethod.GET,RequestMethod.POST })
  5. public ModelAndView queryItems() throws Exception {}

映射成功后,springmvc框架生成一个Handler对象,对象中只包括 一个映射成功的method。

ItemsController.java

  1. package cn.ssm.xhchen.controller;
  2. import java.util.List;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.web.bind.annotation.RequestMapping;
  6. import org.springframework.web.bind.annotation.RequestMethod;
  7. import org.springframework.web.servlet.ModelAndView;
  8. import cn.ssm.xhchen.po.ItemsCustomer;
  9. import cn.ssm.xhchen.po.ItemsQueryVo;
  10. import cn.ssm.xhchen.service.ItemsService;
  11. /**
  12. *
  13. * ClassName: ItemsController
  14. *
  15. * @Description: 商品管理控制
  16. * @author XHChen
  17. * @date 2018年10月17日 下午9:31:52
  18. */
  19. @Controller
  20. // 窄化请求映射,对url进行分类管理
  21. @RequestMapping("/items")
  22. public class ItemsController {
  23. @Autowired
  24. private ItemsService itemsService;
  25. /**
  26. *
  27. * @Description: 模糊查询商品信息
  28. * @param @return
  29. * @param @throws Exception
  30. * @return ModelAndView
  31. * @throws
  32. * @author XHChen
  33. * @date 2018年10月20日 下午8:34:57
  34. */
  35. // 1.@RequestMapping("/queryItems.action")
  36. // 2.限制http请求方法,限定表单POST请求
  37. // @RequestMapping(value="/queryItems.action",method={RequestMethod.POST})
  38. // 3.限制http请求方法,限定表单POST/GET请求
  39. @RequestMapping(value = "/queryItems.action", method = { RequestMethod.GET, RequestMethod.POST })
  40. public ModelAndView queryItems() throws Exception {
  41. // 此项目不做数据绑定
  42. // 创建ItemsCustomer对象
  43. ItemsCustomer itemsCustomer = new ItemsCustomer();
  44. // 设置查询条件
  45. itemsCustomer.setItems_name("苹果");
  46. // 创建ItemsQueryVo对象
  47. ItemsQueryVo itemsQueryVo = new ItemsQueryVo();
  48. // 把itemsCustomer封装到ItemsQueryVo中
  49. itemsQueryVo.setItemsCustomer(itemsCustomer);
  50. // 调用service方法查询数据库
  51. List<ItemsCustomer> itemsList = itemsService.findItemsList(itemsQueryVo);
  52. // 返回ModelAndView
  53. ModelAndView modelAndView = new ModelAndView();
  54. modelAndView.addObject("itemsList", itemsList);
  55. // 指定视图
  56. // 路径前缀和后缀已由springmvc.xml配置
  57. modelAndView.setViewName("items/itemsList");
  58. return modelAndView;
  59. }
  60. /**
  61. *
  62. * @Description: 商品信息修改页面
  63. * @param @return 返回ModelAndView
  64. * @param @throws Exception
  65. * @return ModelAndView
  66. * @throws
  67. * @author XHChen
  68. * @date 2018年10月20日 下午8:46:10
  69. */
  70. @RequestMapping("/editItems.action")
  71. public ModelAndView editItems() throws Exception {
  72. // 通过itemsService获得修改数据,此项目不介绍数据绑定
  73. ItemsCustomer itemsCustomer = itemsService.findItemsById(1);
  74. System.out.println(itemsCustomer);
  75. // 返回ModelAndView
  76. ModelAndView modelAndView = new ModelAndView();
  77. // 把数据添加到modelAndView
  78. modelAndView.addObject("itemsCustomer", itemsCustomer);
  79. // 指定视图
  80. modelAndView.setViewName("items/editItems");
  81. return modelAndView;
  82. }
  83. /**
  84. *
  85. * @Description: 修改商品信息
  86. * @param @return
  87. * @param @throws Exception
  88. * @return ModelAndView
  89. * @throws
  90. * @author XHChen
  91. * @date 2018年10月20日 下午8:51:59
  92. */
  93. @RequestMapping("/editItemsSubmit.action")
  94. public ModelAndView editItemsSubmit() throws Exception {
  95. // 调用itemsService方法修改商品信息,需要将页面数据提交到此方法
  96. // ......
  97. // 方法没有做参数绑定
  98. // itemsService.updateItems(id, itemsCustomer);
  99. // 返回ModelAndView
  100. ModelAndView modelAndView = new ModelAndView();
  101. // 指定视图
  102. modelAndView.setViewName("items/itemsList");
  103. // 返回指定视图
  104. return modelAndView;
  105. }
  106. }

视图编写

·【WEB-INF/jsp/items】创建名为“itemsList.jsp”的商品列表

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
  2. <%
  3. String path = request.getContextPath();
  4. String basePath = request.getScheme() + "://"
  5. + request.getServerName() + ":" + request.getServerPort()
  6. + path + "/";
  7. %>
  8. <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
  9. <%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
  10. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  11. <html>
  12. <head>
  13. <base href="<%=basePath%>">
  14. <title>My JSP 'itemsList.jsp' starting page</title>
  15. <meta http-equiv="pragma" content="no-cache">
  16. <meta http-equiv="cache-control" content="no-cache">
  17. <meta http-equiv="expires" content="0">
  18. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  19. <meta http-equiv="description" content="This is my page">
  20. <!--
  21. <link rel="stylesheet" type="text/css" href="styles.css">
  22. -->
  23. </head>
  24. <body>
  25. <form action="${PageContext.request.ContextPath }/items/queryItems.action" method="post">
  26. <table border="1">
  27. <tr>
  28. <td><input type="text" name="itemsCustomer.items_name"></td>
  29. <td><input type="submit" value="搜索商品"></td>
  30. </tr>
  31. </table>
  32. <h3>商品列表</h3>
  33. <table border="1" width="100%">
  34. <tr>
  35. <td>商品名称</td>
  36. <td>商品价格</td>
  37. <td>生成时间</td>
  38. <td>商品描述</td>
  39. <td>修改商品</td>
  40. <td>删除商品</td>
  41. </tr>
  42. <c:forEach items="${itemsList}" var="item">
  43. <tr>
  44. <td>${item.items_name }</td>
  45. <td>${item.items_price }</td>
  46. <td><fmt:formatDate value="${item.items_creattime }" pattern="yyyy:MM:dd HH:mm:ss"/></td>
  47. <td>${item.items_detail }</td>
  48. <td><a
  49. href="${PageContext.request.ContextPath }/items/editItems.action?id=${item.id}">修改</a></td>
  50. <td><a
  51. href="${PageContext.request.ContextPath }/items/deleteItems.action?id=${item.id}">删除</a></td>
  52. </tr>
  53. </c:forEach>
  54. </table>
  55. </form>
  56. </body>
  57. </html>

【WEB-INF/jsp/items】创建名为“editItems.jsp”的更新商品列表

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
  2. <%
  3. String path = request.getContextPath();
  4. String basePath = request.getScheme() + "://"
  5. + request.getServerName() + ":" + request.getServerPort()
  6. + path + "/";
  7. %>
  8. <%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  10. <html>
  11. <head>
  12. <base href="<%=basePath%>">
  13. <title>My JSP 'editItems.jsp' starting page</title>
  14. <meta http-equiv="pragma" content="no-cache">
  15. <meta http-equiv="cache-control" content="no-cache">
  16. <meta http-equiv="expires" content="0">
  17. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  18. <meta http-equiv="description" content="This is my page">
  19. <!--
  20. <link rel="stylesheet" type="text/css" href="styles.css">
  21. -->
  22. </head>
  23. <body>
  24. <form action="${PageContext.request.ContextPath }/items/editItemsSubmit.action" method="post">
  25. <input type="hidden" name="id" value="${itemsCustomer.id }">
  26. <h3>修改商品信息</h3>
  27. <table border="1">
  28. <tr>
  29. <td>商品名称</td>
  30. <td><input type="text" name="items_name" value="${itemsCustomer.items_name }"></td>
  31. </tr>
  32. <tr>
  33. <td>商品价格</td>
  34. <td><input type="text" name="items_price" value="${itemsCustomer.items_price }"></td>
  35. </tr>
  36. <tr>
  37. <td>生产时间</td>
  38. <td><input type="text" name="items_creattime" value="<fmt:formatDate value="${itemsCustomer.items_creattime }" pattern="yyyy:MM:dd HH:mm:ss"/>"/></td>
  39. </tr>
  40. <tr>
  41. <td>商品描述</td>
  42. <td><input type="text" name="items_detail" value="${itemsCustomer.items_detail }"></td>
  43. </tr>
  44. </table>
  45. <input type="submit" value="提交">
  46. <input type="reset" value="重置">
  47. </form>
  48. </body>
  49. </html>

配置Handler

将编写Handler在spring容器加载。

  1. <!-- 配置Handler -->
  2. <!-- 扫描解决开发中多个Handler的配置 扫描cotroller,指定cotroller的包 -->
  3. <context:component-scan base-package="cn.ssm.xhchen.controller"></context:component-scan>

配置注解处理器映射器

在classpath下的springmvc.xml中配置处理器映射器

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

在这里有必要解释一下,在实际开发中一般用以下配置代替处理器映射器和适配器的配置

(必须引入以下约束)

  1. xmlns:mvc="http://www.springframework.org/schema/mvc"
  2. http://www.springframework.org/schema/mvc
  3. http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
  4. <!-- 实际开发中,代替上边处理器映射器和适配器配置 -->
  5. <mvc:annotation-driven conversion-service="conversionService"/>

配置视图解析器

在classpath下的springmvc.xml中配置jsp视图解析器

  1. <!-- 配置视图解析器 默认jstl标签 -->
  2. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  3. <!-- 配置访问jsp路径的前缀 -->
  4. <property name="prefix" value="/WEB-INF/jsp/"></property>
  5. <!-- 配置访问jsp路径的后缀 -->
  6. <property name="suffix" value=".jsp"></property>
  7. </bean>

在视图解析器配置访问jsp路径的前缀和后缀,Handler指定视图不需要再写前缀和后缀

70 6

部署调试

访问:http://localhost:8080/

发表评论

表情:
评论列表 (有 0 条评论,280人围观)

还没有评论,来说两句吧...

相关阅读