SpringMVC-Mybatis整合和注解开发

SpringMVC-Mybatis整合和注解开发

SpringMVC-Mybatis整合

整合的思路

  • 在mybatis和spring整合的基础上 添加springmvc。
  • spring要管理springmvc编写的Handler(controller)、mybatis的SqlSessionFactory、mapper、别名、映射等
  • 步骤:
    1. 整合dao(mapper)层,spring和mybatis整合
    2. 整合service,spring管理service接口,service中可以调用spring容器中dao(mapper)
    3. 整合controller,spring管理controller接口,在controller调用service

jar包

  • mybatis-3.2.7.jar
  • Spring 4.2.4
  • mybatis和spring整合包
  • 数据库驱动包
  • log4j日志

配置文件

  • 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:jdbc.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>
    	
    	<!-- SqlSessionFactory配置 -->
    	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    		<!-- 加载数据源 -->
    		<property name="dataSource" ref="dataSource" />
    		<!-- 加载mybatis核心配置文件 -->
    		<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
    		<!-- 别名包扫描 -->
    		<property name="typeAliasesPackage" value="com.syj.ssm.pojo" />
    	</bean>
    	
    	<!-- 动态代理,第二种方式:包扫描(推荐): -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        	<!-- basePackage多个包用","分隔 -->
        	<property name="basePackage" value="com.syj.ssm.mapper" />
        </bean>
        
    </beans>
    
  • applicationContext-service.xml—配置service接口

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
    	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
    	
    	<!-- @Service包扫描器 -->
    	<context:component-scan base-package="com.syj.ssm.service"/>
    </beans>
    
    
  • applicationContext-transaction.xml–事务管理

    <!-- 事务管理器 -->
    	<bean id="transactionManager"
    		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    		<!-- 数据源 -->
    		<property name="dataSource" ref="dataSource" />
    	</bean>
    
    	<!-- 通知 -->
    	<tx:advice id="txAdvice" transaction-manager="transactionManager">
    		<tx:attributes>
    			<!-- 传播行为 -->
    			<tx:method name="save*" propagation="REQUIRED" />
    			<tx:method name="insert*" propagation="REQUIRED" />
    			<tx:method name="delete*" propagation="REQUIRED" />
    			<tx:method name="update*" propagation="REQUIRED" />
    			<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
    			<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
    			<tx:method name="query*" propagation="SUPPORTS" read-only="true" />
    		</tx:attributes>
    	</tx:advice>
    
    	<!-- 切面 -->
    	<aop:config>
    		<aop:advisor advice-ref="txAdvice"
    			pointcut="execution(* com.syj.ssm.service.*.*(..))" />
    	</aop:config>
    
  • sprintmvc.xml—springmvc的配置,配置处理器映射器、适配器、视图解析器

    <!-- 配置Handler ========================= -->
    	<!-- 包扫描配置  -->
    	<context:component-scan base-package="com.syj.ssm.controller" />
    
    	
    	<!-- ==================================== -->
    	
    	<!-- 配置处理器映射器 -->
    	<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/> -->
    	<!-- 配置处理器适配器-->
    	<!-- <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/> -->
    	
    	<!-- 配置注解驱动,相当于同时使用最新处理器映射跟处理器适配器,对json数据响应提供支持 -->
    	<mvc:annotation-driven />
    	
    	<!-- ==================================== -->
    	
    	<!-- 视图解析器 ============================ -->
    	<!--注解实现 -->
     	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    		<property name="prefix" value="/WEB-INF/jsp/" />
    		<property name="suffix" value=".jsp" />	
    	</bean> 
    
  • SqlMapConfig.xml—mybatis的配置文件,配置别名、settings、mapper(也可以仅配置setting和properties等)

    <?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>
    
    	<!-- 别名 -->
    
    	<!-- mapper映射器 -->
    
    </configuration>
    
  • Spring中的配置文件的加载可以在web.xml中进行加载

    mybatis配置文件的加载可以在applicationContext-dao.xml配置加载

     <!-- 配置spring -->
    	<context-param>
    		<param-name>contextConfigLocation</param-name>
    		<param-value>classpath:spring/applicationContext-*.xml</param-value>
    	</context-param>
    
    	<!-- 使用监听器加载Spring配置文件 -->
    	<listener>
    		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    	</listener>
    	
    	<!-- ================================= -->
    	
    	<!-- SqlSessionFactory配置 -->
    	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    		<!-- 加载数据源 -->
    		<property name="dataSource" ref="dataSource" />
    		<!-- 加载mybatis核心配置文件 -->
    		<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
    		<!-- 别名包扫描 -->
    		<property name="typeAliasesPackage" value="com.syj.ssm.pojo" />
    	</bean>
    

前端控制器

  • 前端控制器配置

     <!-- 前端控制器 -->
      <servlet>
      	<servlet-name>springmvc</servlet-name>
      	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      		<!-- 加载SpringMVC的配置 -->
      		<init-param>
      			<param-name>contextConfigLocation</param-name>
      			<param-value>classpath:spring/springmvc.xml</param-value>
      		</init-param>
      </servlet>
      <servlet-mapping>
      	<servlet-name>springmvc</servlet-name>
      	<url-pattern>*.action</url-pattern>
      </servlet-mapping>
    

工程目录

在这里插入图片描述

商品列表开发

  1. 需求:商品列表开发

  2. 商品列表的mapper开发

    mapper接口

    // 根据一定条件查询商品列表
    	public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
    
  3. mapper.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
    <mapper namespace="com.syj.ssm.mapper.ItemMapperCustomer">
    	<!-- 
    		商品查询的sql片段
    		建议是以单表为单位定义查询条件
    		建议将常用的查询条件都写出来 
    	 -->
    	<sql id= "query_items_where">
    		<if test="itemsCustom!=null">
    			<if test="itemsCustom.name!=null and itemsCustom.name!='' ">
    				and name like '%${itemsCustom.name}%'
    			</if>
    			<if test="itemsCustom.id != null">
    				and id = #{itemsCustom.id}
    			</if>
    		</if>
    	</sql>
    	
    		<!-- 商品查询 -->
    		<select id="findItemsList"  parameterType="com.syj.ssm.pojo.ItemsQueryVo" 
    		 resultType="com.syj.ssm.pojo.ItemsCustom">
    			SELECT * FROM items
    			<where>
    				<include refid="query_items_where" />
    			</where>
    		</select>
    
    </mapper>
    
  4. pojo的扩展类和包装类

        /**
         * 商品信息的扩展类
         * 
         * @author SYJ
         *
         */
        public class ItemsCustom extends Items {
    
        }
    //=====================================
    
    	/**
    	 * 商品信息的包装类
    	 */
    	private static final long serialVersionUID = 1L;
    	private ItemsCustom itemsCustom;
    
    	public ItemsCustom getItemsCustom() {
    		return itemsCustom;
    	}
    
    	public void setItemsCustom(ItemsCustom itemsCustom) {
    		this.itemsCustom = itemsCustom;
    	}
    
  5. service的编写

    @Service
    public class ItemsServiceImpl implements ItemsService {
    
    	// 注入ItemMapperCustomer的mapper
    	@Autowired
    	private ItemMapperCustomer itemsMapperCustomer;
    
    
    	@Override
    	public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception {
    		return itemsMapperCustomer.findItemsList(itemsQueryVo);
    	}
    
  6. 在applicationContext-service.xml中配置service

    	<!-- @Service包扫描器 -->
    	<context:component-scan base-package="com.syj.ssm.service"/>
    
  7. Controller代码的编写

    @Controller
    @RequestMapping(value = "/item")
    public class ItemsController {
    	// 注入service
    	@Autowired
    	private ItemsService itemsService;
    
    	@RequestMapping("/queryItems")
    	/**
    	 * @Title: queryItems
    	 * @Description: 查询商品列表
    	 * @param @return
    	 * @param @throws Exception
    	 * @return ModelAndView
    	 */
    	public ModelAndView queryItems(HttpServletRequest request) throws Exception {
    		List<ItemsCustom> itemsList = itemsService.findItemsList(null);
    		// System.out.println(request.getParameter("id"));
    		ModelAndView modelAndView = new ModelAndView();
    		modelAndView.addObject("itemsList", itemsList);
    		modelAndView.setViewName("itemsList");
    
    		return modelAndView;
    	}
    }
    
  8. 在web.xml配置spring监听器

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

SpringMVC注解开发

商品的修改

  • 需求:

    功能描述:商品信息修改

    操作流程:

    1、在商品列表页面点击修改连接

    2、打开商品修改页面,显示了当前商品的信息

    ​ 根据商品id查询商品信息

    3、修改商品信息,点击提交。

    ​ 更新商品信息

  • 逆向生成Items

  • 编写Service

    @Override
    	/**
    	 * 根据id查询商品信息
    	 */
    	public ItemsCustom findItemsById(int id) throws Exception {
    		Items items = itemsMapper.selectByPrimaryKey(id);
    		// 在这里随着需求的变量,需要查询商品的其它的相关信息,返回到controller
    		ItemsCustom itemsCustom = new ItemsCustom();
    		// 将items的属性拷贝到itemsCustom
    		BeanUtils.copyProperties(items, itemsCustom);
    
    		return itemsCustom;
    	}
    
    	@Override
    	/**
    	 * 更新查询商品信息 定义service接口,遵循单一职责,将业务参数细化(不要使用包装类型,比如map)
    	 */
    	public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception {
    		// 编写业务代码
    
    		// 对关键业务的数据进行非空的校验
    		if (id != null) {
    			// 抛出异常,提示调用接口的用户,id不能为空
    			// 有错误就抛出异常
    			// ...
    		}
    
    		itemsMapper.updateByPrimaryKey(itemsCustom);
    //		itemsMapper.updateByPrimaryKeySelective(itemsCustom);
    	}
    

@RequestMapping

  • 设置方法对应的url(完成url映射)
    在这里插入图片描述

  • 窄化请求映射
    在class上定义根路径

    好处:更新规范系统 的url,避免 url冲突。
    在这里插入图片描述

  • 限制http请求的方法

    通过requestMapping限制url请求的http方法,

    如果限制请求必须是post,如果get请求就抛出异常
    在这里插入图片描述

controller方法返回值

  • 返回ModelAndView
    在这里插入图片描述

  • 返回字符串

    如果controller方法返回jsp页面,可以简单将方法返回值类型定义 为字符串,最终返回逻辑视图名。
    在这里插入图片描述

  • 返回void

    使用此方法,容易输出json、xml格式的数据:

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

    response.setCharacterEncoding(“utf-8”);

    response.setContentType(“application/json;charset=utf-8”);

    response.getWriter().write(“json串”);
    在这里插入图片描述

  • redirect重定向

    如果方法重定向到另一个url,方法返回值为“redirect:url路径”

    使用redirect进行重定向,request数据无法共享,url地址栏会发生变化的。

    return "redirect:queryItems.action";
    
  • forward转发

    使用forward进行请求转发,request数据可以共享,url地址栏不会。

    方法返回值为“forward:url路径”

    return "forward:queryItems.action";
    

参数绑定

  • 参数绑定过程
    在这里插入图片描述

  • 默认支持的参数类型

    HttpServletRequest:通过request对象获取请求信息

    HttpServletResponse:通过response处理响应信息

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

    Model:通过model向页面传递数据,如下:
    在这里插入图片描述

  • @RequestParam

    如果request请求的参数名和controller方法的形参数名称一致,适配器自动进行参数绑定。如果不一致可以通过

    @RequestParam 指定request请求的参数名绑定到哪个方法形参上。

    对于必须要传的参数,通过@RequestParam中属性required设置为true,如果不传此参数则报错。

    对于有些参数如果不传入,还需要设置默认值,使用@RequestParam中属性defaultvalue设置默认值
    在这里插入图片描述

  • 可以绑定简单类型

    可以绑定整型、 字符串、单精/双精度、日期、布尔型。

  • 可以绑定简单pojo类型
    简单pojo类型只包括简单类型的属性。
    绑定过程:
    ​ request请求的参数名称和pojo的属性名一致,就可以绑定成功。
    问题:
    ​ 如果controller方法形参中有多个pojo且pojo中有重复的属性,使用简单pojo绑定无法有针对性的绑定,
    ​ 比如:方法形参有items和User,pojo同时存在name属性,从http请求过程的name无法有针对性的绑
    ​ 定到items或user。这个时候我们可以使用包装的pojo

  • 可以绑定包装的pojo
    包装的pojo里边包括了pojo。

    1. 页面:
      在这里插入图片描述
    2. 包装类型的属性
      在这里插入图片描述

自定义参数绑定使用转化器

  • 第一步编写转化类:

    1. 将字符转化成日期

      /**
       * 自定义日期转换器(字符串转化成日期)
       * 
       * @author SYJ
       *
       */
      public class CustomDateConverer implements Converter<String, Date> {
      
      	@Override
      	public Date convert(String str) {
      		try {
      			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(str);
      		} catch (ParseException e) {
      			e.printStackTrace();
      		}
      		return null;
      	}
      }
      
    2. 去除字符串两边的空格

      import org.springframework.core.convert.converter.Converter;
      
      public class StringTrimConverter implements Converter<String, String> {
      	@Override
      	public String convert(String str) {
      		// 去掉字符串两边空格,如果去除后为空设置为null
      		if (str != null) {
      			str = str.trim();
      			if (str.equals("")) {
      				return null;
      			}
      		}
      		return str;
      	}
      }
      
  • 第二步对自定义参数绑定转化类进行配置

    我们会使用<mvc:annotation-driven/>和conversion-service属性

    	<!-- 配置注解驱动,相当于同时使用最新处理器映射跟处理器适配器,对json数据响应提供支持 -->
    	<mvc:annotation-driven   conversion-service="conversionService"  />
    	
    	<!-- 转换器 -->
        <bean id="conversionService"
    	class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    		<property name="converters">
    			<list>
    				<bean class="com.syj.ssm.controller.converter.CustomDateConverer"/>
    				<bean class="com.syj.ssm.controller.converter.StringTrimConverter"/>
    			</list>
    		</property>
    	</bean> 
    

乱码

  • 解决post请求乱码问题。在web.xml中加入:

    <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请求中文参数出现乱码解决方法有两个:

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

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

    第二种:对参数进行重新编码:

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

    String userName new 
    String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")
    
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值