pringmvc和mybatis整合开发的方法

整合目标:控制层采用springmvc、持久层使用mybatis实现

创建数据库表

4.2.需要的jar包
1.spring(包括springmvc)
2.mybatis
3.mybatis-spring整合包
4.数据库驱动
5.第三方连接池。

整合思路

Dao层:
1、SqlMapConfig.xml,空文件即可,但是需要文件头。
2、applicationContext-dao.xml
a)数据库连接池
b)SqlSessionFactory对象,需要spring和mybatis整合包下的。
c)配置mapper文件扫描器。
Service层:
1、applicationContext-service.xml包扫描器,扫描@service注解的类。
2、applicationContext-trans.xml配置事务。

Controller层:
1、Springmvc.xml
a)包扫描器,扫描@Controller注解的类。
b)配置注解驱动
c)配置视图解析器
Web.xml文件:
1、配置spring
2、配置前端控制器。

创建工程

创建动态web工程springmvc-web
复制jar包到/WEB-INF/lib中
工程自动加载jar包

加入配置文件

4.6.1.sqlMapConfig.xml
使用逆向工程来生成Mapper相关代码,不需要配置别名。
在config/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>

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

    <!-- 配置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">
        <!-- 配置Mapper扫描包 -->
        <property name="basePackage" value="cn.itcast.ssm.mapper" />
    </bean>

</beans>

4.6.3.db.properties
配置数据库相关信息

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

4.6.4.applicationContext-service.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 配置service扫描 -->
    <context:component-scan base-package="cn.itcast.ssm.service" />

</beans>

4.6.5.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:method name="query*" propagation="SUPPORTS" read-only="true" />
        </tx:attributes>
    </tx:advice>

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

</beans>

4.6.6.springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns: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="cn.itcast.ssm.controller" />

    <!-- 注解驱动 -->
    <mvc:annotation-driven />

    <!-- Example: prefix="/WEB-INF/jsp/", suffix=".jsp", viewname="test" -> 
        "/WEB-INF/jsp/test.jsp" -->
    <!-- 配置视图解析器 -->
    <bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 配置逻辑视图的前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 配置逻辑视图的后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

4.6.7.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>springmvc-web</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:spring/applicationContext*.xml</param-value>
    </context-param>

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

    <!-- 配置SrpingMVC的前端控制器 -->
    <servlet>
        <servlet-name>springmvc-web</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-web</servlet-name>
        <!-- 配置所有以action结尾的请求进入SpringMVC -->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

</web-app>

4.7.加入jsp页面这里写图片描述

实现商品列表显示

5.1.需求
实现商品查询列表,从mysql数据库查询商品信息。
5.2.DAO开发
使用逆向工程,生成代码

注意修改逆向工程的配置文件,参考MyBatis第二天
逆向工程生成代码如下图:这里写图片描述

5.3.ItemService接口

public interface ItemService {

    /**
     * 查询商品列表
     * 
     * @return
     */
    List<Item> queryItemList();

}

.ItemServiceImpl实现类

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    private ItemMapper itemMapper;

    @Override
    public List<Item> queryItemList() {
        // 从数据库查询商品数据
        List<Item> list = this.itemMapper.selectByExample(null);

        return list;
    }

}

ItemController

@Controller
public class ItemController {

    @Autowired
    private ItemService itemService;

    /**
     * 显示商品列表
     * 
     * @return
     */
    @RequestMapping("/itemList")
    public ModelAndView queryItemList() {
        // 获取商品数据
        List<Item> list = this.itemService.queryItemList();

        ModelAndView modelAndView = new ModelAndView();
        // 把商品数据放到模型中
        modelAndView.addObject("itemList", list);
        // 设置逻辑视图
        modelAndView.setViewName("itemList");

        return modelAndView;

.测试
访问url:
http://127.0.0.1:8080/springmvc-web/itemList.action

参数绑定

6.1.1.需求
打开商品编辑页面,展示商品信息。
6.1.2.需求分析
编辑商品信息,首先要显示商品详情
需要根据商品id查询商品信息,然后展示到页面。
请求的url:/itemEdit.action
参数:id(商品id)
响应结果:商品编辑页面,展示商品详细信息。
6.1.3.ItemService接口
这里写图片描述
6.1.4.ItemServiceImpl实现类

@Override
public Item queryItemById(int id) {
    Item item = this.itemMapper.selectByPrimaryKey(id);

    return item;
}

6.1.5.ItemController
页面点击修改按钮,发起请求
http://127.0.0.1:8080/springmvc-web/itemEdit.action?id=1
需要从请求的参数中把请求的id取出来。
Id包含在Request对象中。可以从Request对象中取id。

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

/**
 * 根据id查询商品
 * 
 * @param request
 * @return
 */
@RequestMapping("/itemEdit")
public ModelAndView queryItemById(HttpServletRequest request) {
    // 从request中获取请求参数
    String strId = request.getParameter("id");
    Integer id = Integer.valueOf(strId);

    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);

    // 把结果传递给页面
    ModelAndView modelAndView = new ModelAndView();
    // 把商品数据放在模型中
    modelAndView.addObject("item", item);
    // 设置逻辑视图
    modelAndView.setViewName("itemEdit");

    return modelAndView;
}

默认支持的参数类型

处理器形参中添加如下类型的参数处理适配器会默认识别并进行赋值。
6.1.6.1.HttpServletRequest
通过request对象获取请求信息
6.1.6.2.HttpServletResponse
通过response处理响应信息
6.1.6.3.HttpSession
通过session对象得到session中存放的对象
6.1.7.Model/ModelMap
6.1.7.1.Model
除了ModelAndView以外,还可以使用Model来向页面传递数据,
Model是一个接口,在参数里直接声明model即可。

如果使用Model则可以不使用ModelAndView对象,Model对象可以向页面传递数据,View对象则可以使用String返回值替代。
不管是Model还是ModelAndView,其本质都是使用Request对象向jsp传递数据。
代码实现:

/**
 * 根据id查询商品,使用Model
 * 
 * @param request
 * @param model
 * @return
 */
@RequestMapping("/itemEdit")
public String queryItemById(HttpServletRequest request, Model model) {
    // 从request中获取请求参数
    String strId = request.getParameter("id");
    Integer id = Integer.valueOf(strId);

    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);

    // 把结果传递给页面
    // ModelAndView modelAndView = new ModelAndView();
    // 把商品数据放在模型中
    // modelAndView.addObject("item", item);
    // 设置逻辑视图
    // modelAndView.setViewName("itemEdit");

    // 把商品数据放在模型中
    model.addAttribute("item", item);

    return "itemEdit";
}

6.1.7.2.ModelMap
ModelMap是Model接口的实现类,也可以通过ModelMap向页面传递数据

使用Model和ModelMap的效果一样,如果直接使用Model,springmvc会实例化ModelMap。代码实现:

/**
 * 根据id查询商品,使用ModelMap
 * 
 * @param request
 * @param model
 * @return
 */
@RequestMapping("/itemEdit")
public String queryItemById(HttpServletRequest request, ModelMap model) {
    // 从request中获取请求参数
    String strId = request.getParameter("id");
    Integer id = Integer.valueOf(strId);

    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);

    // 把结果传递给页面
    // ModelAndView modelAndView = new ModelAndView();
    // 把商品数据放在模型中
    // modelAndView.addObject("item", item);
    // 设置逻辑视图
    // modelAndView.setViewName("itemEdit");

    // 把商品数据放在模型中
    model.addAttribute("item", item);

    return "itemEdit";
}

6.2.绑定简单类型

当请求的参数名称和处理器形参名称一致时会将请求参数与形参进行绑定。
这样,从Request取参数的方法就可以进一步简化。 `/**
* 根据id查询商品,绑定简单数据类型
*
* @param id
* @param model
* @return
*/
@RequestMapping(“/itemEdit”)
public String queryItemById(int id, ModelMap model) {
// 根据id查询商品数据
Item item = this.itemService.queryItemById(id);

// 把商品数据放在模型中
model.addAttribute("item", item);

return "itemEdit";

}`

支持的数据类型

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

处理器方法:
public String editItem(Model model,Integer id,Boolean status)

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

value:参数名字,即入参的请求参数名字,如value=“itemId”表示请求的参数 区中的名字为itemId的参数的值将传入

required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报错
TTP Status 400 - Required Integer parameter ‘XXXX’ is not present

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

定义如下:

@RequestMapping("/itemEdit")
public String queryItemById(@RequestParam(value = "itemId", required = true, defaultValue = "1") Integer id,
        ModelMap modelMap) {
    // 根据id查询商品数据
    Item item = this.itemService.queryItemById(id);

    // 把商品数据放在模型中
    modelMap.addAttribute("item", item);

    return "itemEdit";
}

绑定pojo类型 ##、

6.3.1.需求
将页面修改后的商品信息保存到数据库中。
6.3.2.需求分析
请求的url:/updateItem.action
参数:表单中的数据。
响应内容:更新成功页面
6.3.3.使用pojo接收表单数据
如果提交的参数很多,或者提交的表单中的内容很多的时候,可以使用简单类型接受数据,也可以使用pojo接收数据。
要求:pojo对象中的属性名和表单中input的name属性一致。

页面定义如下图:这里写图片描述这里写图片描述
请求的参数名称和pojo的属性名称一致,会自动将请求参数赋值给pojo的属性。
6.3.4.ItemService接口
ItemService里编写接口方法
/**
* 根据id更新商品
*
* @param item
*/
void updateItemById(Item item);
6.3.5.ItemServiceImpl实现类
ItemServiceImpl里实现接口方法
使用updateByPrimaryKeySelective(item)方法,忽略空参数

@Override
public void updateItemById(Item item) {
    this.itemMapper.updateByPrimaryKeySelective(item);
}

ItemController

/**
 * 更新商品,绑定pojo类型
 * 
 * @param item
 * @param model
 * @return
 */
@RequestMapping("/updateItem")
public String updateItem(Item item) {
    // 调用服务更新商品
    this.itemService.updateItemById(item);

    // 返回逻辑视图
    return "success";
}

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

解决post乱码问题

提交发现,保存成功,但是保存的是乱码
在web.xml中加入:

    <!-- 解决post乱码问题 -->
    <filter>
        <filter-name>encoding</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!-- 设置编码参是UTF8 -->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

以上可以解决post请求乱码问题。

对于get请求中文参数出现乱码解决方法有两个:
修改tomcat配置文件添加编码与工程编码一致,如下:

另外一种方法对参数进行重新编码:
String userName new
String(request.getParamter(“userName”).getBytes(“ISO8859-1”),”utf-8”)
ISO8859-1是tomcat

绑定包装pojo

6.4.1.需求
使用包装的pojo接收商品信息的查询条件。
6.4.2.需求分析
包装对象定义如下:
public class QueryVo {
private Item item;
set/get。。。
}这里写图片描述

6.4.3.接收查询条件

// 绑定包装数据类型
    @RequestMapping("/queryItem")
    public String queryItem(QueryVo queryVo) {
        System.out.println(queryVo.getItem().getId());
        System.out.println(queryVo.getItem().getName());

        return "success";
    }

自定义参数绑定

6.5.1.需求
在商品修改页面可以修改商品的生产日期,并且根据业务需求自定义日期格式。
6.5.2.需求分析
由于日期数据有很多种格式,springmvc没办法把字符串转换成日期类型。所以需要自定义参数绑定。

前端控制器接收到请求后,找到注解形式的处理器适配器,对RequestMapping标记的方法进行适配,并对方法中的形参进行参数绑定。可以在springmvc处理器适配器上自定义转换器Converter进行参数绑定。

一般使用注解驱动加载处理器适配器,可以在此标签上进行配置。

6.5.3.修改jsp页面这里写图片描述

自定义Converter

//Converter<S, T>
//S:source,需要转换的源的类型
//T:target,需要转换的目标类型
public class DateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String source) {
        try {
            // 把字符串转换为日期类型
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
            Date date = simpleDateFormat.parse(source);

            return date;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 如果转换异常则返回空
        return null;
    }
}

6.5.5.配置Converter
我们同时可以配置多个的转换器。
类似下图的usb设备,可以接入多个usb设备

<!-- 配置注解驱动 -->
<!-- 如果配置此标签,可以不用配置... -->
<mvc:annotation-driven conversion-service="conversionService" />

<!-- 转换器配置 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="cn.itcast.springmvc.converter.DateConverter" />
        </set>
    </property>
</bean>

6.5.6.配置方式2(了解即可)

<!--注解适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <property name="webBindingInitializer" ref="customBinder"></property>
</bean>

<!-- 自定义webBinder -->
<bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
    <property name="conversionService" ref="conversionService" />
</bean>

<!-- 转换器配置 -->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <set>
            <bean class="cn.itcast.springmvc.convert.DateConverter" />
        </set>
    </property>
</bean>

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

springmvc与struts2不同

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

uniquewdl

匆忙的人生,总有你喜欢的文章

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值