前情提要请看JavaWeb学习之路——SSM框架之Spring(四)
整合Spring和Mybatis框架
1.在项目的lib下导入如下jar包
导入mybatis所有jar和spring的jar基本包,spring-jdbc,spring-tx,spring-aop,spring整合mybatis等
2.编写spring配置文件applicationContext
在jar包下找到对应的类文件,复制它的类名,将之加入到对应的bean的Class属性中,下图为一个示例:
Spring 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- id表示获取到对象标识
class 创建哪个类的对象
-->
<!-- 数据源封装类,相当于mybatis的environment标签,数据类在spring-jdbc包中 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/likui"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</bean>
<!-- 在mybatis-spring包中 -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 扫描器,相当于mybatis下的mappers package标签 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.likui.mapper"></property>
<!-- 让factory与数据库相关联 -->
<property name="sqlSessionFactory" ref="factory"></property>
</bean>
</beans>
对应类:MapperScannerConfigurer->SqlSessionFactoryBean->DriverManagerDataSource,层层嵌套
3.使用流程
src下代码结构图:
1)在src下创建mapper包,里面是sql语句的使用方法
public interface FlowerMapper {
@Select("select * from flower")
List<Flower> selAll();
}
2)在src下创建pojo包,里面是类的构造方法和setter、getter方法,用来封装对象
public class Flower {
private int id;
private String name;
private double price;
private String production;
public void setList(List<Integer> list) {
this.list = list;
}
public Flower(int id, String name, double price, String production) {
this.id = id;
this.name = name;
this.price = price;
this.production = production;
}
public Flower() {}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getProduction() {
return production;
}
public void setProduction(String production) {
this.production = production;
}
3)创建service包,里面是工程项目的实现类,接口和它的实现类都放这里面
(1)接口
public interface FlowerService {
List<Flower> show() throws IOException ; //显示
}
(2)实现类
public class FlowerServiceImpl implements FlowerService{
private FlowerMapper flowermapper;
public FlowerMapper getFlowermapper() {
return flowermapper;
}
public void setFlowermapper(FlowerMapper flowermapper) {
this.flowermapper = flowermapper;
}
@Override
public List<Flower> show() throws IOException {
// TODO Auto-generated method stub
return flowermapper.selAll();
}
}
4)在Spring的beans.xml中创建类的对象
注意对应的首字母为大写的类或接口在引用时需要将首字母小写,接口不能创建bean,因为不能实例化
<bean id="flowerService" class="com.likui.service.FlowerServiceImpl">
<property name="flowermapper" ref="flowerMapper"></property>
</bean>
5)编写Test主函数来实现,在java文件中利用Spring IoC获取相应类对象
public class Test {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
//获取所有spring管理的bean的名称
//String []names=ac.getBeanDefinitionNames();
//for(String string:names) {
// System.out.println(string);
//}
FlowerServiceImpl flowerServiceImpl=ac.getBean("flowerService",FlowerServiceImpl.class);
List<Flower> list=flowerServiceImpl.show();
System.out.println("id\t\tname\t\tprice\t\tproduction");
for (Flower flower : list) {
System.out.println(flower.getId()+"\t\t"+flower.getName()+"\t\t"+
flower.getPrice()+"\t\t"+flower.getProduction());
}
}
}
6)实验结果展示:
4.发布到Web项目上
因为Spring不能管理serverlet,需要用tomcat来管理它,利用tomcat提供的方法来支持Spring
1)在WEB-INF下新建web.xml配置文件。用于加载Spring的配置文件,获取到相应的contextConfigLocation
代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- 上下文参数 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- spring配置文件 -->
<param-value>classpath:beans.xml</param-value>
</context-param>
<!-- 封装了一个监听器,帮助加载Spring的配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
2)在src下新建serverlet包,里面写相应的serverlet实现方法
利用init初始化方法来实例化service中接口实现类,代码如下:
@WebServlet("/show")
public class ShowServerlet extends HttpServlet{
private FlowerService flowerservice;
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
//对service实例化
//ApplicationContext ac=new ClassPathXmlApplicationContext("beans.xml");
//Spring不能管理serverlet对象,需要用tomacat来管理它,会封装它
ApplicationContex ac=WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
flowerservice=ac.getBean("flowerService",FlowerServiceImpl.class);
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
req.setAttribute("list", flowerservice.show());
req.getRequestDispatcher("/index.jsp").forward(req, resp);
}
}
3)在WebContent下新建index.jsp用于测试。
代码如下所示:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
hello world!
<table>
<tr>
<th>编号</th>
<th>名字</th>
<th>价格</th>
<th>产处</th>
</tr>
<c:forEach items="${list }" var="peo">
<tr>
<td>${peo.id }</td>
<td>${peo.name }</td>
<td>${peo.price }</td>
<td>${peo.production }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
4)实验结果: