spring+springMVC+Mybatis整合_XML配置示例
1.概述
spring+springMVC+Mybatis整合 XML配置方式
1.1 测试环境说明
名称 | 版本 | 备注 |
操作系统 | windows 10 专业版 1809_X64 | |
JDK | jdk1.8.0_121 WIN_X64 | |
数据库 | mysql5.7 WIN_X64 | |
web服务器 | Tomcat8.5 WIN_X64 |
2.入门示例
2.1示例流程简述
第一步:导入包
第二步:创建一个访问页面
第三步:修改WEB.XML配置文件,添加spring处理器
第四步:创建spring核心 xml配置文件
第五步:添加springMVC xml配置
第六步:创建访问处理接口。
第七步:创建 实体类
第七步:添加mybatis xml配置
第八步:创建mapper 数据访问接口
第九步:创建相应的mapper 数据库操作xml
第十步:创建服务接口与实现类
第十一步:创建响应页面
第十二步:测试
2.2 目录架构
2.3 操作示例
2.3.1 导入包
2.3.2 创建一个访问页面/SSM_Demo/WebApp/index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/depart/addDepart" method="post">
<label>部门名称</label><input type="text" name="departName"/><br/>
<label>上级部门</label><input type="text" name="departSupperId"/><br/>
<label>简 介</label><input type="text" name="departDescribe"/><br/>
<input type="submit" value="保存"/>
</form>
</body>
</html>
2.3.3 修改WEB.XML配置文件,添加spring处理器
<?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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>SSM_Demo</display-name> <!-- 编码处理 -->
<filter>
<filter-name>encodingFilter</filter-name>
<!-- 编码处理类 包依赖:spring-web-4.3.16.RELEASE.jar -->
<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>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- 加载spring配置 -->
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<!-- 依赖包 spring-webmvc-4.3.16.RELEASE.jar -->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- 首页设置 -->
<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>
</web-app>
2.3.4 创建spring核心 xml配置文件 /SSM_Demo/resourse/spring-context.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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 包扫描 对cn.slm包中所有声明关系的类进行实例化,并注入相应属性-->
<context:component-scan base-package="cn.slm" /> </beans>
2.3.5 添加springMVC xml配置 /SSM_Demo/resourse/spring-mvc.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"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- springMVC注解扫描 自动注册带mvc注解的类 -->
<mvc:annotation-driven /> <!-- 静态资源过滤 1 REST风格的写法 将静态资源的访问管理权交还给默认的servlet容器本身处理 另一种方式是SpringMVC自己处理:静态资源过滤
2 -->
<mvc:default-servlet-handler /> <!-- 静态资源过滤 2 SpringMVC处理静态资源 location:源路径 (实际路径)多路径以“,”逗号分割 ; mapping:映射路径(虚拟路径).
两种方式二选一 -->
<!-- 以下配置将Web根路径"/"及类路径下 /META-INF/publicResources/ 的目录映射为/resources路径。
假设Web根路径下拥有images、js这两个资源目录,在images下面有bg.gif图片,在js下面有test.js文件, 则可以通过 /resources/images/bg.gif
和 /resources/js/test.js 访问这二个静态资源。 假设WebRoot还拥有images/bg1.gif 及 js/test1.js,
则也可以在网页中通过 /resources/images/bg1.gif 及 /resources/js/test1.js 进行引用。 -->
<!-- <mvc:resources location="/,classpath:/META-INF/publicResources/" mapping="/resources/**"/> --> <!-- 视图解析器的统一前后缀配置 这个配置会在返回视图的前后自动加上配置的前(/WEB-INF/view/)后(.jsp)缀 假设希望在跳转视图的时候不被该设置限制,则在控制器中的视图地址中加 (forward:)
示例:
希望自动加前后缀:return "/addDepart.jsp"; 页面在/WEB-INF/view/目录下
不希望加前后缀:return "forward:/login.jsp"; 页面在根目录下 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 配置页面视图前缀 -->
<property name="prefix" value="/WEB-INF/view/"></property>
<!-- 配置页面视图后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
2.3.6 创建访问处理接口。/SSM_Demo/src/cn/slm/action/TDepartmentAction.java
package cn.slm.action; import java.util.Date;
import java.util.HashMap; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.annotation.SessionScope; import cn.slm.pojo.TDepartment;
import cn.slm.service.DepartmentService; @Controller // 访问控制器声明
@SessionScope // 同用户共享声明 单一session只创建一次对象,减少缓存数据
@RequestMapping("/depart")
public class TDepartmentAction{ @Autowired
private DepartmentService dps; @RequestMapping(value="/addDepart")
public String addDepart(TDepartment depart) {
System.out.println("测试添加!"+depart.getDepartName());
depart.setDepartCreateTime(new Date());
int num = dps.addDepartment(depart);
System.out.println("受影响的行数:"+num);
/*if(num>0) {
request.setAttribute("page_depart_findDepart_msg","添加部门成功!");
}else {
request.setAttribute("page_depart_findDepart_msg","添加部门失败!");
}*/
return "forward:/test.jsp";
}
}
2.3.7 创建 实体类 /SSM_Demo/src/cn/slm/pojo/TDepartment.java
package cn.slm.pojo; import java.util.Date; public class TDepartment { private int departId;;// dp_id int 11 0 0 -1 0 0 0 0 部门编号 -1 0
private String departName;// dp_name varchar 50 0 0 0 0 0 0 0 部门名称 utf8 utf8_bin 0 0
private String departSupperId;//dp_supperId int 11 0 0 0 0 0 0 0 上级部门 0 0
private Date departCreateTime;// dp_createTime timestamp 0 0 0 0 0 0 0 CURRENT_TIMESTAMP -1 创建时间 0 0
private String departDescribe;// dp_describe varchar 255 0 -1 0 0 0 0 这是一个有活力的部门 0 部门描述 utf8 utf8_bin 0 0 public int getDepartId() {
return departId;
}
public void setDepartId(int departId) {
this.departId = departId;
}
public String getDepartName() {
return departName;
}
public void setDepartName(String departName) {
this.departName = departName;
}
public String getDepartSupperId() {
return departSupperId;
}
public void setDepartSupperId(String departSupperId) {
this.departSupperId = departSupperId;
}
public Date getDepartCreateTime() {
return departCreateTime;
}
public void setDepartCreateTime(Date departCreateTime) {
this.departCreateTime = departCreateTime;
}
public String getDepartDescribe() {
return departDescribe;
}
public void setDepartDescribe(String departDescribe) {
this.departDescribe = departDescribe;
} }
2.3.8 添加mybatis xml配置 /SSM_Demo/resourse/spring-data.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:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd"> <!--
A 代表 xml与注解(声明)式两种配置方式通用的
B 代表仅xml配置方式需要
C 代表仅注解(声明)配置方式需要
-->
<!-- 数据源信息peopertise文件化 --> <!-- A 1.数据库连接池信息 依赖包:commons-dbcp2-2.1.1.jar 连接池依赖包:commons-pool2-2.4.2.jar-->
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<!-- JDBC驱动类 依赖包:mysql-connector-java-5.1.47.jar-->
<property name="driverClassName" value="org.gjt.mm.mysql.Driver"></property>
<!-- 数据库地址 -->
<property name="url" value="jdbc:mysql://localhost:3306/ssm_demo"></property>
<!-- 数据库用户名 -->
<property name="username" value="root"></property>
<!-- 数据库密码 -->
<property name="password" value="123456"></property>
</bean> <!-- A 2.会话工厂 指定需要进行会话管理的数据库数据源 依赖包:mybatis-spring-1.3.1.jar -->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- A 会话工厂数据源映射 name="dataSource" 属性 ref 处理对象 -->
<property name="dataSource" ref="dataSource"></property>
<!-- B 别名包路径 关联数据库表对象与javaBean对象-->
<property name="typeAliasesPackage" value="cn.slm.pojo"></property>
<!-- B mapper映射文件路径 *_mapper.xml 代表所有以_mapper结尾的xml 注解(声明)式配置不需要此选项-->
<property name="mapperLocations" value="classpath:cn/slm/mapper/xml/*_mapper.xml"></property>
<!-- A 其他配置 -->
<property name="configuration">
<!-- 使用setting标签 依赖包:mybatis-3.4.1.jar -->
<bean class="org.apache.ibatis.session.Configuration">
<!-- 驼峰命名法的支持 -->
<property name="mapUnderscoreToCamelCase" value="true"></property>
</bean>
</property> </bean> <!-- A 3.事务代理 指定需要事务管理的数据库数据源 依赖包:spring-jdbc-4.3.16.RELEASE.jar-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- A 事务代理数据源映射 name="dataSource" 属性 ref 处理对象 -->
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- A 4.mybatis-mapper管理 指定mapper接口类的管理方式 依赖包:mybatis-spring-1.3.1.jar -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- A 会话工厂映射 -->
<property name="sqlSessionFactoryBeanName" value="sessionFactory"></property>
<!-- A mapper 接口路径 -->
<property name="basePackage" value="cn.slm.mapper"></property>
<!-- A 指定带注解 的接口,才创建对象 依赖包:mybatis-3.4.1.jar-->
<property name="annotationClass" value="org.apache.ibatis.annotations.Mapper"></property>
</bean> <!-- A 5.启动事务代理 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
2.3.9 创建mapper 数据访问接口 /SSM_Demo/src/cn/slm/mapper/TDepartmentMapper.java
package cn.slm.mapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import cn.slm.pojo.TDepartment; @Mapper
public interface TDepartmentMapper { //@Insert("insert into t_department(dp_name,dp_supperId,dp_createTime,dp_describe) values(#{departName},#{departSupperId},#{departCreateTime},#{departDescribe})")
int insert(TDepartment depart); int update(TDepartment depart); int logicDel(TDepartment depart); int delete(TDepartment depart); TDepartment select(int id); TDepartment selectByName(String name); List<TDepartment> selectAll(); /*List<TDepartment> selectByPage(@Param int startnum,@Param int endnum)*/ }
2.3.10 创建相应的mapper 数据库操作xml /SSM_Demo/src/cn/slm/mapper/xml/tdepartment_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="cn.slm.mapper.TDepartmentMapper"> <insert id="insert" useGeneratedKeys="true" keyProperty="studentId">
insert into t_department(dp_name,dp_supperId,dp_createTime,dp_describe) values(#{departName},#{departSupperId},#{departCreateTime},#{departDescribe})
</insert> </mapper>
2.3.11 创建服务接口/SSM_Demo/src/cn/slm/service/DepartmentService.java
package cn.slm.service; import java.util.List; import cn.slm.pojo.TDepartment; public interface DepartmentService { public int addDepartment(TDepartment depart);
public int updateDepartment(TDepartment depart);
public int LogicDelDepartment(TDepartment depart);
public int delDepartment(TDepartment depart);
public TDepartment findDepartmentByID(TDepartment depart);
public TDepartment findDepartmentByName(TDepartment depart);
public List<TDepartment> findDepartmentByPage(int start ,int end);
public List<TDepartment> findAllDepartment(); }
2.3.12 创建服务接口实现类 /SSM_Demo/src/cn/slm/service/impl/DepartmentServiceImpl.java
package cn.slm.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import cn.slm.mapper.TDepartmentMapper;
import cn.slm.pojo.TDepartment;
import cn.slm.service.DepartmentService; @Service //声明服务层
public class DepartmentServiceImpl implements DepartmentService { @Autowired //自动注入TDepartmentMapper
private TDepartmentMapper dpartMapper; @Override
public int addDepartment(TDepartment depart) {
return dpartMapper.insert(depart);
} @Override
public int updateDepartment(TDepartment depart) {
// TODO Auto-generated method stub
return dpartMapper.update(depart);
} @Override
public int LogicDelDepartment(TDepartment depart) {
return dpartMapper.logicDel(depart);
} @Override
public int delDepartment(TDepartment depart) {
return dpartMapper.delete(depart);
} @Override
public TDepartment findDepartmentByID(TDepartment depart) {
return dpartMapper.select(depart.getDepartId());
} @Override
public TDepartment findDepartmentByName(TDepartment depart) {
return dpartMapper.selectByName(depart.getDepartName());
} @Override
public List<TDepartment> findDepartmentByPage(int start, int end) {
// TODO Auto-generated method stub
return null;
} @Override
public List<TDepartment> findAllDepartment() {
return dpartMapper.selectAll();
} }
2.3.13 创建响应页面 /SSM_Demo/WebApp/test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
这是一个测试页面,用于测试跳转。 当你看到这行字的时候,说明跳转正常!
</body>
</html>
2.3.14 测试
2.3.14.1 请求页面
2.3.14.2 响应页面
2.3.14.3 数据库
2.3.14.4 控制台