SpringMVC-Mybatis整合和注解开发
SpringMVC-Mybatis整合和注解开发
SpringMVC-Mybatis整合
整合的思路
在mybatis和spring整合的基础上 添加springmvc。
spring要管理springmvc编写的Handler(controller)、mybatis的SqlSessionFactory、mapper、别名、映射等
步骤:
整合dao(mapper)层,spring和mybatis整合
整合service,spring管理service接口,service中可以调用spring容器中dao(mapper)
整合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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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>
1
2
3
4
5
6
7
8
9
10
11
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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
前端控制器
前端控制器配置
<!-- 前端控制器 -->
<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
3
4
5
6
7
8
9
10
11
12
13
14
工程目录
商品列表开发
需求:商品列表开发
商品列表的mapper开发
mapper接口
// 根据一定条件查询商品列表
public List<ItemsCustom> findItemsList(ItemsQueryVo itemsQueryVo) throws Exception;
1
2
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>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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);
}
1
2
3
4
5
6
7
8
9
10
11
12
在applicationContext-service.xml中配置service
<!-- @Service包扫描器 -->
<context:component-scan base-package="com.syj.ssm.service"/>
1
2
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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
在web.xml配置spring监听器
<!-- 使用监听器加载Spring配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
1
2
3
4
SpringMVC注解开发
首先逆向生成Items
参考:https://blog.csdn.net/SYJ_1835_NGE/article/details/91464365
商品的修改
需求:
功能描述:商品信息修改
操作流程:
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);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
@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";
1
forward转发
使用forward进行请求转发,request数据可以共享,url地址栏不会。
方法返回值为“forward:url路径”
return "forward:queryItems.action";
1
参数绑定
参数绑定过程
默认支持的参数类型
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。
页面:
包装类型的属性
自定义参数绑定使用转化器
第一步编写转化类:
将字符转化成日期
/**
* 自定义日期转换器(字符串转化成日期)
*
* @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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
去除字符串两边的空格
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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
第二步对自定义参数绑定转化类进行配置
我们会使用<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>
1
2
3
4
5
6
7
8
9
10
11
12
13
乱码
解决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>
1
2
3
4
5
6
7
8
9
10
11
12
对于get请求中文参数出现乱码解决方法有两个:
第一种:修改tomcat配置文件添加编码与工程编码一致,如下:
<Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
1
第二种:对参数进行重新编码:
ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码
String userName new
String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")
---------------------
SpringMVC-Mybatis整合和注解开发的更多相关文章
- Spring+SpringMVC+mybatis整合以及注解的使用(三)
1.包结构:
- 框架篇:Spring+SpringMVC+Mybatis整合开发
前言: 前面我已搭建过ssh框架(http://www.cnblogs.com/xrog/p/6359706.html),然而mybatis表示不服啊. Mybatis:"我抗议!" ...
- Spring+springmvc+Mybatis整合案例 annotation版(myeclipse)详细版
Spring+springmvc+Mybatis整合案例 Version:annotation版 文档结构图: 从底层开始做起: 01.配置web.xml文件 <?xml version=&qu ...
- Spring+springmvc+Mybatis整合案例 xml配置版(myeclipse)详细版
Spring+springmvc+Mybatis整合案例 Version:xml版(myeclipse) 文档结构图: 从底层开始做起: 01.配置web.xml文件 <?xml version ...
- IDEA下使用maven构建web项目(SpringMVC+Mybatis整合)
需求背景:由于最近总是接到一些需求,需要配合前端团队快速建设移动端UI应用或web应用及后台业务逻辑支撑的需求,若每次都复用之前复杂业务应用的项目代码,总会携带很多暂时不会用到的功能或组件,这样的初始 ...
- [手把手教程][JavaWeb]优雅的SpringMvc+Mybatis整合之路
来源于:http://www.jianshu.com/p/5124eef40bf0 [手把手教程][JavaWeb]优雅的SpringMvc+Mybatis整合之路 手把手教你整合最优雅SSM框架:S ...
- springboot整合mybaits注解开发
springboot整合mybaits注解开发时,返回json或者map对象时,如果一个字段的value为空,需要更改springboot的配置文件 mybatis: configuration: c ...
- 学习笔记_J2EE_SSM_01_spring+springMVC+Mybatis整合_XML配置示例
spring+springMVC+Mybatis整合_XML配置示例 1.概述 spring+springMVC+Mybatis整合 XML配置方式 1.1 测试环境说明 名称 版本 备注 操作系统 ...
- ssm之spring+springmvc+mybatis整合初探
1.基本目录如下 2.首先是向lib中加入相应的jar包 3.然后在web.xml中加入配置,使spring和springmvc配置文件起作用. <?xml version="1. ...
随机推荐
- Android多媒体-MediaPlayer唤醒锁及音频焦点
MediaPlayer的唤醒锁 一般使用MediaPlayer播放音频流,推荐使用一个Service来承载MediaPlayer,而不是直接在Activity里使用.可是Android系统的功耗设计里 ...
- Bootstrap4 网格系统
学习注意事项 col-*-* 第一个*是设备类型,第二个*是控件宽度的占比 屏幕被等分为12,col-1宽度是1/12,col-6宽度是50%,col-12宽度是100% 给应用了class的elem ...
- flash、flex builder、flash builder、 air的关系
flash VS flex builder flash被adobe收购的时候是flash8,已经可以AS2面向对象了. 而被adobe收购后,adobe准备把flash打造成一个开发工具.就比如JBU ...
- 玲珑学院OJ 1023 - Magic boy Bi Luo with his excited math problem 树状数组暴力
分析:a^b+2(a&b)=a+b so->a^(-b)+2(a&(-b))=a-b 然后树状数组分类讨论即可 链接:http://www.ifrog.cc/acm/probl ...
- Handle/Body pattern(Wrapper pattern)
Handle Body Pattern 一些设计模式,通过一系列非直接的间接的方式(这种间接的方式,可称其为 handle(把手)),完成接口与实现(实现可称为 body(主体))的分离 Handle ...
- Ural 1517. Freedom of Choice 后缀数组
Ural1517 所谓后缀数组, 实际上准确的说,应该是排序后缀数组. 一个长度为N的字符串,显然有N个后缀,将他们放入一个数组中并按字典序排序就是后缀数组的任务. 这个数组有很好的性质,使得我们运行 ...
- python3 批量管理Linux服务器 下发命令与传输文件
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import paramiko import os, stat import sys import ope ...
- bzoj 1718: [Usaco2006 Jan] Redundant Paths 分离的路径【tarjan】
首先来分析一下,这是一张无向图,要求没有两条路联通的点对个数 有两条路连通,无向图,也就是说,问题转化为不在一个点双连通分量里的点对个数 tarjan即可,和求scc还不太一样-- #include& ...
- [App Store Connect帮助]六、测试 Beta 版本(3.2)管理测试员:邀请外部测试员
在您上传至少一个构建版本之后,您可以邀请外部测试员(您组织之外的人员)使用“TestFlight Beta 版测试”来测试您的 App.为了使您的构建版本可用于外部测试,请创建一个群组.添加构建版本, ...
- FPGA基础入门篇(四) 边沿检测电路
FPGA基础入门篇(四)--边沿检测电路 一.边沿检测 边沿检测,就是检测输入信号,或者FPGA内部逻辑信号的跳变,即上升沿或者下降沿的检测.在检测到所需要的边沿后产生一个高电平的脉冲.这在FPGA电 ...