SpringMVC基础知识(2)

1、springmvc和mybatis整合

      1.1、需求:使用springmvc和mybatis完成商品列表查询。

      1.2、整合思路

      springmvc+mybatis的系统架构:

      

      1.2.1、第一步:整合dao层

      mybatis和spring整合,通过spring管理mapper接口。

      使用mapper的扫描器自动扫描mapper接口在spring中进行注册。

      1.2.2、第二步:整合service

      通过spring管理service接口。

      使用配置方式将service接口配置在spring配置文件中。

      实现事务控制。

      1.2.3、第三步:整合springmvc

      由于springmvc是spring的模块,不需要整合。


      1.3、整合dao

      1.3.1、sqlMapConfig.xml

      配置mybatis自己的配置文件

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

	<!-- 全局setting配置,根据需要添加 -->

	<!-- 配置别名 -->
	<typeAliases>
		<!-- 批量扫描 -->
		<package name="lsq.study.ssm.po" />
	</typeAliases>

	<!-- 
		配置mapper 
			由于这里使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。 
			必须遵循:mapper.xml和mapper.java文件同名且在同一个目录
	-->

</configuration>

      1.3.2、applicationContext-dao.xml

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

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
	
	<!-- 加载db.properties文件 -->
	<context:property-placeholder location="classpath:db.properties"/>
	
	<!-- 配置数据源:dbcp -->
	<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="30" />
		<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"/>
	</bean>
	
	<!-- mapper扫描器 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
		<property name="basePackage" value="lsq.study.ssm.mapper"/>
		<!-- 
			☆注意:下边不能写成<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
			这样会导致db.properties加载不上而连不上数据库
		 -->
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
	</bean>
		
</beans>

      1.3.3、手动定义商品查询mapper

      针对综合查询mapper,一般情况会有关联查询,建议自定义mapper。

      1.3.3.1、ItemsMapperCustom.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="cn.itcast.ssm.mapper.ItemsMapperCustom" >
  
  <!-- 定义商品查询的sql片段,就是商品查询条件 -->
  <sql id="query_items_where">
  	<!-- 商品查询条件通过ItemsQueryVo包装对象中itemsCustom属性传递 -->
  	<if test="itemsCustom!=null">
  		<if test="itemsCustom.name!=null and itemsCustom.name!=''">
  			items.NAME LIKE '%${itemsCustom.name}%'
  		</if>
  	</if>
  </sql>
  
  <!-- 商品查询列表 -->
  <!-- 
  	parameterType:建议传入包装对象(包装了查询条件);
  	resultType:建议使用扩展对象,如果有子查询,扩展对象可以接收子查询的查询结果。
   -->
  <select id="findItemsList" parameterType="lsq.study.ssm.po.ItemsQueryVo" 
  		resultType="lsq.study.ssm.po.ItemsCustom">
  	SELECT * FROM items 
  </select>
  
</mapper>
      对应的扩展类ItemsQueryVo、ItemsCustom

package lsq.study.ssm.po;

public class ItemsQueryVo {

    //商品信息
    private Items items;

    private ItemsCustom itemsCustom;

    public Items getItems() {
        return items;
    }

    public void setItems(Items items) {
        this.items = items;
    }

    public ItemsCustom getItemsCustom() {
        return itemsCustom;
    }

    public void setItemsCustom(ItemsCustom itemsCustom) {
        this.itemsCustom = itemsCustom;
    }

}
package lsq.study.ssm.po;

public class ItemsCustom extends Items{

    //在此处添加商品的扩展信息,或者接收子查询的返回值
    
}
      1.3.3.2、对应接口方法

package lsq.study.ssm.mapper;

import java.util.List;

import lsq.study.ssm.po.ItemsCustom;
import lsq.study.ssm.po.ItemsQueryVo;


public interface ItemsMapperCustom {
    //商品查询列表
    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
}


      1.4、整合service

      1.4.1、定义service接口

package lsq.study.ssm.service;

import java.util.List;

import lsq.study.ssm.po.ItemsCustom;
import lsq.study.ssm.po.ItemsQueryVo;

public interface ItemsService {
    
    //商品查询列表
    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
    
}

      1.4.2、定义service接口实现类

package lsq.study.ssm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import lsq.study.ssm.mapper.ItemsMapperCustom;
import lsq.study.ssm.po.ItemsCustom;
import lsq.study.ssm.po.ItemsQueryVo;
import lsq.study.ssm.service.ItemsService;

public class ItemsServiceImpl implements ItemsService {

    @Autowired
    private ItemsMapperCustom itemsMapperCustom;
    
    public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception {
        //通过ItemsMapperCustom查询数据库
        return itemsMapperCustom.findItemsList(itemsQueryVo);
    }

}

      1.4.3、在spring容器中配置service

      创建applicationContext-service.xml文件,配置service

<?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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
	
	<!-- 商品管理的service -->
	<bean id="itemsService" class="lsq.study.ssm.service.impl.ItemsServiceImpl"/>
	
</beans>

      1.4.4、在spring容器中配置事务

      创建applicationContext-transaction.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-3.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">
	
	<!-- 
		事务管理器:
		对mybatis操作数据库进行事务控制,spring使用jdbc的事务控制类
	 -->
	 <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="delete*" propagation="REQUIRED"/>
	 		<tx:method name="insert*" 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="select*" propagation="SUPPORTS" read-only="true"/>
	 	</tx:attributes>
	 </tx:advice>
	
	<!-- aop -->
	<aop:config>
		<aop:advisor advice-ref="txAdvice" pointcut="execution(* lsq.study.ssm.service.impl.*.*(..))"/>
	</aop:config>
</beans>
      

      1.5、整合springmvc

      1.5.1、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:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	
	<!-- 扫描controller -->
	<context:component-scan base-package="lsq.study.ssm.controller"></context:component-scan>
	
	<mvc:annotation-driven></mvc:annotation-driven>
	
	<!-- 配置视图解析器 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 配置jsp路径的前缀 -->
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<!-- 配置jsp路径的后缀 -->
		<property name="suffix" value=".jsp"/>
	</bean>
	
</beans>

      1.5.2、配置springmvc前端控制器

      在web.xml中进行配置:

  <!-- 配置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:spring/springmvc.xml</param-value>
  	</init-param>
  </servlet>
  
  <servlet-mapping>
  	<servlet-name>springmvc</servlet-name>
  	<url-pattern>*.action</url-pattern>
  </servlet-mapping>
  
  <!-- post乱码过滤器 -->
  <filter>
  	<filter-name>CharacterEncodingFilter</filter-name>
  	<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  </filter>
  
  <filter-mapping>
  	<filter-name>CharacterEncodingFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

      1.5.3、编写Controller

package lsq.study.ssm.controller;

import java.util.List;

import lsq.study.ssm.po.ItemsCustom;
import lsq.study.ssm.service.ItemsService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ItemsController {
    
    @Autowired
    private ItemsService itemsService;
    
    @RequestMapping("/queryItems")
    public ModelAndView queryItems() throws Exception{
        //调用service,查询商品列表
        List<ItemsCustom> list = this.itemsService.findItemsList(null);
        
        ModelAndView mv = new ModelAndView();
        mv.addObject("itemsList", list);
        mv.setViewName("items/itemsList");
        
        return mv;
    }
}
      1.5.4、编写jsp

      1.5.5、加载spring容器

      在web.xml中,添加spring容器监听器,加载spring容器。

  <!-- 加载spring容器 -->
  <context-param>
  	<param-name>contextConfigLocation</param-name>
  	<param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
  </context-param>
  <listener>
  	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
      运行结果:

      

2、商品修改功能开发

      2.1、需求:

      操作流程:

      1)进入商品查询列表页面;

      2)点击修改,进入商品修改页面,页面中显示了要修改的商品信息(根据商品id从数据库中查询);
      3)在商品修改页面,修改商品信息,修改后,点击提交。

      2.2、开发mapper

      1)根据id查询商品信息

      2)根据id更新items表的数据

      使用逆向工程生成的代码

      2.3、开发service

      接口功能:

      1)根据id查询商品信息

      2)修改商品信息

      service接口方法:

    //根据id查询商品信息
    public ItemsCustom findItemsById(Integer id) throws Exception;
    
    //修改商品信息
    public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception;
      service接口方法实现:
    public ItemsCustom findItemsById(Integer id) throws Exception {
        Items items = this.itemsMapper.selectByPrimaryKey(id);
        //中间对商品信息进行业务处理
        //...
        //返回ItemsCustom
        ItemsCustom itemsCustom = new ItemsCustom();
        //将items的属性值拷贝到ItemsCustom中
        BeanUtils.copyProperties(items, itemsCustom);
        
        return itemsCustom;
    }

    public void updateItems(Integer id, ItemsCustom itemsCustom) throws Exception {
        //添加业务校验,通常在service接口对关键参数进行校验
        //校验id是否为空,如果为空,抛出异常
        
        //更新商品信息,使用updateByPrimaryKeyWithBLOBs,更新表中所有字段,包括大文本类型字段
        //updateByPrimaryKeyWithBLOBs要求必须传入id
        itemsCustom.setId(id);
        this.itemsMapper.updateByPrimaryKeyWithBLOBs(itemsCustom);
    }

      2.4、开发controller

      方法:

      1)商品信息修改页面显示

      2)商品信息修改提交

    //商品信息修改页面提示
    @RequestMapping("/editItems")
    public ModelAndView editItems() throws Exception{
        //调用service接口,根据商品id查询商品信息
        ItemsCustom itemsCustom = this.itemsService.findItemsById(1);
        
        //返回ModelAndView
        ModelAndView mv = new ModelAndView();
        
        //将商品信息放到model
        mv.addObject("itemsCustom", itemsCustom);
        
        //商品修改页面
        mv.setViewName("items/editItems");
        
        return mv;
    }
    
    //商品信息修改提交
    @RequestMapping("/editItemsSubmit")
    public ModelAndView editItemsSubmit() throws Exception{
        //调用service更新商品信息,页面需要将商品信息传到此方法
        //。。。
        
        //返回ModelAndView
        ModelAndView mv = new ModelAndView();
        
        //返回一个成功页面
        mv.setViewName("success");
        
        return mv;
    }
      测试结果:(至此三层架构可以行得通)

      

3、@RequestMapping

      该注解的作用

      3.1、url映射

      定义controller方法对应的url,进行处理器映射使用。

      3.2、窄化请求映射

      

      3.3、限制http请求方法

      出于安全性考虑,对http的链接进行方法限制。
      如果限制请求方法为post,进行get请求,会报如下错误。
      
      该注解中的method为数组,可以设置多个值
      
      

4、controller方法的返回值

      4.1、返回ModelAndView

      需要在方法结束时,定义ModelAndView,将model和view分别进行设置。

      4.2、返回string

      如果controller返回string,有如下几种情况:

      4.2.1、表示返回逻辑视图名

      真正视图(jsp路径)= 前缀 + 逻辑视图名 + 后缀
      

      4.2.2、redirect重定向

      商品修改提交后,重定向到商品查询列表。
      redirect重定向特点:浏览器地址栏中的url会变化。修改提交的request数据无法传到重定向的地址。因为重定向后重新进行request(request无法共享)
      

      4.2.3、forward页面转发

      通过forward进行页面转发,浏览器地址栏url不变,request可以共享。
      

      4.3、返回void

      在controller方法形参上可以定义request和response,使用request或response指定响应结果:

      4.3.1、使用request转向页面,如下:

      request.getRequestDispatcher("页面路径").forward(request,response);

      4.3.2、页可以通过response页面重定向:

      response.sendRedirect("url")

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

      response.setCharacterEncoding("utf-8");
      response.setContentType("application/json;charset='utf-8");
      response.getWriter().write("json串");

5、参数绑定

      5.1、springmvc参数绑定过程

      从客户端请求key/value数据,经过参数绑定,将key/value数据绑定到controller方法的形参上。

      springmvc中,接收页面提交的数据是通过方法形参来接收。而不是在controller类定义成员变量接收。

      

      5.2、默认支持的类型

      直接在controller方法形参上定义下边类型的对象,就可以使用这些对象。在参数绑定过程中,如果遇到下边类型直接进行绑定。

      5.2.1、HttpServletRequest

      通过request对象获取请求信息。

      5.2.2、HttpServletResponse

      通过response处理响应信息。

      5.2.3、HttpSession

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

      5.2.4、Model/ModelMap

      model是一个接口,modelMap是一个接口实现。

      作用:将model数据填充到request域。

      5.3、简单类型

      通过@RequestParam对简单类型的参数进行绑定。
      如果不使用@RequestParam,要求request传入参数名和controller方法的形参名称一致,方可绑定成功。
      如果使用@RequestParam,不用限制request传入参数名称和controller方法的形参名称一致。
      通过required属性指定参数是否必须要传入,如果设置为true,没有传入参数,报下边错误:
      

      

      5.4、pojo绑定

      页面中input的name和controller的pojo形参中的属性名称一致,将页面中数据绑定到pojo。
      页面定义:
      
      controller的pojo形参的定义:
      

      5.5、自定义参数绑定实现日期类型绑定

      对于controller形参中pojo对象,如果属性中有日期类型,需要自定义参数绑定。
      将请求日期数据串转换成日期类型,要转换的日期类型和pojo中日期属性的类型保持一致。
      
      所以自定义参数绑定将日期字符串转换成java.util.Date类型。
      需要向处理器适配器中注入自定义的参数绑定组件。

      自定义日期类型绑定方法:

package lsq.study.ssm.controller.converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

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

public class CustomDateConverter implements Converter<String, Date>{

    public Date convert(String source) {
        //实现将日期字符串转换成日期类型
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        try {
            //转换成功直接返回
            return format.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //如果参数绑定失败返回null
        return null;
    }

}
      在springmvc.xml中进行配置:

	<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
	
	<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
		<!-- 转换器 -->
		<property name="converters">
			<list>
				<!-- 日期转换器 -->
				<bean class="lsq.study.ssm.controller.converter.CustomDateConverter"/>
			</list>
		</property>
	</bean>
      

6、springmvc和struts2的区别

      6.1、springmvc基于方法开发的,struts2基于类开发的。

      springmvc将url和controller方法映射。映射成功后springmvc生成一个Handler对象,对象中只包括了一个method。方法执行结束,形参数据销毁。

      springmvc的controller开发类似service开发。

      6.2、springmvc可以进行单例开发,并且建议使用单例开发,struts2通过类的成员变量接收参数,无法使用单例,只能使用多例。

      6.3、经过实际测试,struts2速度慢,在于使用struts标签,如果使用struts建议使用jstl。

7、乱码问题

      7.1、POST乱码

      在web.xml中配置post乱码filter:
  <!-- 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>

      7.2、GET请求乱码

      对于get请求中文参数出现乱码解决方法有两个:
      1)修改tomcat配置文件添加编码与工程编码一致,如下:
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
      2)另外一种方法对参数进行重新编码:
      String userName = new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")
      ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码。



      

      












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值