记录下SSM框架整合的步骤,以及框架中每个配置的作用。作为自己学习框架的学习总结。
一、配置Mybatis
1.数据库建表
使用的是Mysql数据库,建表语句如下:
CREATE TABLE `flower` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT '编号',
`name` varchar(30) NOT NULL COMMENT '名称',
`price` float NOT NULL COMMENT '价格',
`production` varchar(30) NOT NULL COMMENT '原产地',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
添加测试数据
2.新建web动态项目,导入mybatis所需要的jar包(jar包资源可在文章末尾获取)
项目结构图,后续新建文件结构
3.新建Flower实体类(存放路径:src下 com.xm.pojo.Flower)
package com.xm.pojo;
public class Flower {
private int id;
private String name;
private float price;
private String production;
public Flower() {
super();
}
public Flower(int id, String name, float price, String production) {
super();
this.id = id;
this.name = name;
this.price = price;
this.production = production;
}
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 float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String getProduction() {
return production;
}
public void setProduction(String production) {
this.production = production;
}
@Override
public String toString() {
return "Flower [id=" + id + ", name=" + name + ", price=" + price + ", production=" + production + "]";
}
}
4.src下新建com.xm.mapper包,存放mapper接口文件和mapper.xml文件
4.1FlowerMapper.java文件代码如下:
package com.xm.mapper;
import java.util.List;
import com.xm.pojo.Flower;
public interface FlowerMapper {
List<Flower> selAll();
}
4.2 FlowerMapper.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.xm.mapper.FlowerMapper">
<select id="selAll" resultType="flower">
select * from flower;
</select>
</mapper>
注意:采用接口绑定的方式时,xml文件中<mapper>标签的namespace属性的值是所对应的接口,<mapper>标签下的子标签的id值和接口中的方法名一致。例如:上面xml中代码<mapper namespace="com.xm.mapper.FlowerMapper">对应的是FlowerMapper接口的全路径,<select id="selAll" resultType="flower">中id="selAll"对应的是接口中的抽象方法:List<Flower> selAll();
FlowerMapper.xml相当于FlowerMapper接口的实现类,采用注解方式的话可以不用mapper.xml文件配置,两种方式可以共同使用。但涉及到动态SQI时,注解方式不如mapper.xml文件配置方式方便。
5.编写mybatis的配置文件,在src下新建mybatis.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>
<!-- 对实体类起别名 -->
<typeAliases>
<package name="com.xm.pojo"/>
</typeAliases>
<!-- 配置数据源 -->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 接口绑定 -->
<mappers>
<package name="com.xm.mapper"/>
</mappers>
</configuration>
注意:上述三个功能:对实体类起别名、配置数据源、扫描mapper接口等功能,在spring整合mybatis时,都整合到spring配置文件中,交给spring容器进行管理。现在写到mybatis.xml中只是为了测试mybatis框架搭建。
6.编写测试类
package com.xm.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.xm.mapper.FlowerMapper;
import com.xm.pojo.Flower;
public class MybatisTest {
public static void main(String[] args) throws Exception {
InputStream is = Resources.getResourceAsStream("mybatis.xml");
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = factory.openSession();
FlowerMapper mapper = session.getMapper(FlowerMapper.class);
List<Flower> list = mapper.selAll();
for (Flower flower : list) {
System.out.println(flower);
}
}
}
上述测试代码展示了mybatis的运行原理,有兴趣的同学可以学习下,如不感兴趣可自动略过,因为上述代码在spring整合以后由spring框架生成SqlSessionFactory,扫描mapper所在的包,产生mapper接口的对象存放在spring容器中进行管理。该代码只是现在测试使用,后续由spring框架完成上述代码功能。
7.测试结果
获取到mysql中的数据,至此mybatis框架配置完成,下一步配置spring整合mybatis。
二、Spring整合Mybatis
1.导入Spring所需的jar包
2.在src下新建Spring的配置文件:applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd"
default-autowire="byName"
>
<!-- 组件扫描 spring扫描注解用的
注意:在Spring的配置文件中不能扫描@controller,因为controller实例化对象要放在SpringMVC容器中管理
-->
<context:component-scan base-package="com.xm.service"></context:component-scan>
<!-- 引入外部文件配置 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 由于创建sqlsession时候需要连接数据库,此时需要ref连接数据库的类对象 -->
<bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 起别名配置 -->
<property name="typeAliasesPackage" value="com.xm.pojo"/>
<!-- 此时有dataSource属性,由于已经自动注入,所以不需要配置 -->
</bean>
<!-- 扫描器 扫描mapper文件夹下xml文件和接口,将mapper接口存储到spring容器中 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.xm.mapper"></property>
<!-- 扫描后的信息全部存储到SqlSessionFactory中 -->
<property name="sqlSessionFactoryBeanName" value="factory" ></property>
</bean>
</beans>
说明:default-autowire="byName"。当<property>标签中name属性里的值和其余<bean>标签中的id相同时,spring会自动把id代表的对象注入到该property属性中,叫做自动注入。
上述配置已经将第一步mybatis的配置全部整合到一起。mybatis.xml文件中现在配置部分可以去掉。
3.spring配置的测试代码类
package com.xm.test;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.xm.mapper.FlowerMapper;
import com.xm.pojo.Flower;
public class SpringTest {
public static void main(String[] args) {
//注意:配置文件被加载时就已经创建对象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
String[] names = ac.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}
/*FlowerMapper flowerMapper = ac.getBean("flowerMapper",FlowerMapper.class);
List<Flower> selAll = flowerMapper.selAll();
for (Flower flower : selAll) {
System.out.println(flower);
}*/
}
}
测试结果:
上面这些是现在Spring容器所管理的对象,可以看到datasource,factory我们自定义名称的对象,MapperScannerConfigurer扫描接口所在的包生成的flowerMapper对象,我们修改下测试代码:
package com.xm.test;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.xm.mapper.FlowerMapper;
import com.xm.pojo.Flower;
public class SpringTest {
public static void main(String[] args) {
//注意:配置文件被加载时就已经创建对象
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
/*String[] names = ac.getBeanDefinitionNames();
for (String name : names) {
System.out.println(name);
}*/
FlowerMapper flowerMapper = ac.getBean("flowerMapper",FlowerMapper.class);
List<Flower> selAll = flowerMapper.selAll();
for (Flower flower : selAll) {
System.out.println(flower);
}
}
}
运行结果:
说明我们可以直接从Spring中获取flowerMapper进行crud操作。
上面我们是用
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
这种方式读取Spring的配置文件创建ApplicationContext容器,如何变成启动tomcat容器就加载该配置文件呢?
3.配置web.xml文件,启动tomcat容器时直接加载applicationContext.xml配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
<!-- 上下文参数 -->
<context-param >
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 封装一个监听器,程序运行加载spring配置文件,根据上下文参数进行加载 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>
为了测试,新建一个FlowerServlet.java文件(此文件只是测试用,因为还没有涉及到SpringMVC整合,等整合后不用此方式),代码如下:
package com.xm.servlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import com.xm.pojo.Flower;
import com.xm.service.FlowerService;
import com.xm.service.impl.FlowerServiceImpl;
@WebServlet("/selAll")
public class FlowerServlet extends HttpServlet{
private FlowerService flowerService;
@Override
public void init() throws ServletException {
//对service实例化
//spring和web整合后所有信息都存放在webApplicationContext
ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
flowerService=ac.getBean("flowerServiceImpl",FlowerServiceImpl.class);
/*String[] beanDefinitionNames = ac.getBeanDefinitionNames();
for (String string : beanDefinitionNames) {
System.out.println(string);
}*/
}
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
List<Flower> list = flowerService.selAll();
System.out.println(list);
}
}
此时启动tomcat服务器,输入路径,可看到数据信息,至此Spring整合Matis完毕。
三、SpringMVC的整合
SpringMVC框架主要核心组件DispatcherServlet、HandlerMapping、HandlerAdapter、ViewResolve这四个组件。在web.xml文件中配置DispatcherServlet,作用是拦截所有请求,在SpringMVC配置文件中配置另外三个组件。
注意:为防止前端jsp页面和控制器编码格式不一致导致出现乱码,此时在web.xml配置文件中还需配置字符编码过滤器。
1.配置DispatcherServlet,web.xml文件配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd">
<!-- 上下文参数 -->
<context-param >
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 封装一个监听器,程序运行加载spring配置文件,根据上下文参数进行加载 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置DispatcherServlet前端控制器,接收所有请求 -->
<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:springmvc.xml</param-value>
</init-param>
<!-- 自启动 tomcat启动时这个类就加载-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 字符编码过滤器 -->
<filter>
<filter-name>encodingFilter</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>
<!--是否强制设置request的编码为encoding,默认false,不建议更改-->
<init-param>
<param-name>forceEncoding</param-name>
<param-value>false</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
2.在src下新建springmvc.xml配置文件。(新建的文件名和classpath后的文件名要一直)
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: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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 扫描注解 -->
<context:component-scan base-package="com.xm.controller"></context:component-scan>
<!-- 注解驱动
此步骤相当于配置了HandlerMapping和HadlerAdapter
-->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 放行静态资源,SpringMVC不进行拦截 -->
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
<!-- 视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
上面配置的一些说明:
- 注解扫描:SpringMVC是Spring的子容器,控制器应由SpringMVC进行管理,有的时候启动项目我们发现SpringMVC无法进行跳转,SpringMVC容器中的请求没有映射到具体controller中:Spring把所有带有@Controller注解的Bean都注册在Spring这个父容器中了,所以springMVC找不到处理器,不能进行跳转。所以注解扫描时,Spring的配置文件不能扫描控制器,SpringMVC只扫描控制器。
放行静态资源:因为在web.xml文件中配置的拦截请求是“/”,所以除*.jsp以外会全部拦截,这样导致导入的图片或者css、js等外部包无法使用,因此要对这些静态资源放行。至此SSM框架整合完毕。
四、整合后代码测试
整理后一个简单的测试,代码如下:
1.控制器代码:
package com.xm.controller;
import java.util.List;
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;
import com.xm.pojo.Flower;
import com.xm.service.FlowerService;
@Controller
public class FlowerController {
@Autowired
private FlowerService flowerService;
@RequestMapping("insFlower")
public String insFlower(Flower flower) {
int n = flowerService.insFlower(flower);
return "redirect:showMenu";
}
@RequestMapping("showMenu")
public ModelAndView showMenu() {
ModelAndView mv = new ModelAndView("main");
mv.addObject("list", flowerService.selAll());
return mv;
}
}
2.service层代码
package com.xm.service;
import java.util.List;
import com.xm.pojo.Flower;
public interface FlowerService {
List<Flower> selAll();
//新增花卉
int insFlower(Flower flower);
}
3.service实现层代码
package com.xm.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xm.mapper.FlowerMapper;
import com.xm.pojo.Flower;
import com.xm.service.FlowerService;
@Service
public class FlowerServiceImpl implements FlowerService{
@Autowired
private FlowerMapper flowerMapper;
@Override
public List<Flower> selAll() {
return flowerMapper.selAll();
}
@Override
public int insFlower(Flower flower) {
return flowerMapper.insFlower(flower);
}
}
4.mapper接口代码
package com.xm.mapper;
import java.util.List;
import com.xm.pojo.Flower;
public interface FlowerMapper {
List<Flower> selAll();
int insFlower(Flower flower);
}
5.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.xm.mapper.FlowerMapper">
<select id="selAll" resultType="flower">
select * from flower;
</select>
<insert id="insFlower" parameterType="flower">
insert into flower values(default,#{name},#{price},#{production});
</insert>
</mapper>
6.前端jsp页面代码:
index.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="insFlower" method="post">
<table>
<tr>
<td>花名:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>价格:</td>
<td><input type="text" name="price"></td>
</tr>
<tr>
<td>产地:</td>
<td><input type="text" name="production"></td>
</tr>
<tr>
<td colspan="1">
<input type="submit" value="提交">
</td>
</tr>
</table>
</form>
</body>
</html>
main.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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table>
<c:forEach items="${list }" var="flower">
<tr>
<td>花卉名:</td>
<td>${flower.name }</td>
<td>价格:</td>
<td>${flower.price }</td>
<td>产地:</td>
<td>${flower.production }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
测试结果:
至此,SSM框架整合完毕,后续如有需求再继续添加配置。