SSM框架整合梳理
近期学到了后台框架SSM,本篇博客用于记录SSM框架即Spring,SpringMVC,Mybatis如何进行整合的 我们以一个基本业务逻辑来当作例子进行整合,这里我也是学习的狂神说的SSM框架,引用一个书库的例子来进行SSM框架整合 这篇文章是整合类型的文章,适合有SSM基础的人观看,没有学过还是建议先学
1. 需求分析
这里需求就是我们需要对一个web页面加入可以操作一个书库的业务逻辑
2.设计数据库
CREATE DATABASE `ssmbuild`
USE `ssmbuild`;
DROP TABLE IF EXISTS `books`;
CREATE TABLE `books`(
`bookID` INT(10) NOT NULL AUTO_INCREMENT COMMENT '书ID',
`bookName` VARCHAR(100) NOT NULL COMMENT '书名',
`bookCounts` INT(11) NOT NULL COMMENT '数量',
`detail` VARCHAR(200) NOT NULL COMMENT '描述',
KEY `bookID123` (`bookID`)
)ENGINE=INNODB DEFAULT CHARSET=utf8
INSERT INTO `books`(`bookID`,`bookName`,`bookCounts`,`detail`)VALUES
(1,'java',1,'从入门到放弃'),
(2,'MySQL',10,'从删库到跑路'),
(3,'Linux',5,'从进门到进牢');
打造一个基本的书库,其中包括四个基本信息还有默认引擎以及编码格式还有一个key字段方便建立索引加快查找速度,然后简单加入三本书(别在意书名 狗头保命)
3.设计Maven配置
3.1导入依赖
导入的依赖主要是junit 数据库驱动 连接池 servlet jsp mybatis mybatis-spring
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.singledog</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
</dependencies>
3.2Maven资源过滤配置
由于静态资源可能不会被自动加载进入打包的项目中 所以我们需要对maven进行配置同样是在pom.xml文件下
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.4.2</version>
<configuration>
<skipTests>true</skipTests>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
</includes>
</resource>
</resources>
</build>
要注意一个事情我们需要将我们所有的依赖文件导入到项目的lib文件夹下,这里我们需要在idea中找到对应项目结构 然后点击构件 然后再加入一个lib文件夹 加入所有的库文件 来避免一些不必要的报错
4.创建基本结构
然后我们需要在resources文件夹下再放入一个连接池基础配置文件dataSource
5.Mybatis层配置
配置mybatis-spring.xml 即mybatis和spring整合时需要的mybatis的核心文件 这里需要写的东西并不多 因为大部分会通过bean标签实现
<?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>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<mappers>
<mapper class="com.rui.dao.BookMapper"/>
</mappers>
</configuration>
这里setting中的是log4j的配置 我把注册mapper的任务也留在了核心文件里 然后我们需要对应数据库数据的实现类,实现sql语句方法的接口,还有接口对应的xml文件,以及其对应的service层的内容
5.1对应的pojo类
package com.rui.pojo;
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
public Books() {
}
public Books(int bookID, String bookName, int bookCounts, String detail) {
this.bookID = bookID;
this.bookName = bookName;
this.bookCounts = bookCounts;
this.detail = detail;
}
@Override
public String toString() {
return "Books{" +
"bookID=" + bookID +
", bookName='" + bookName + '\'' +
", bookCounts=" + bookCounts +
", detail='" + detail + '\'' +
'}';
}
public int getBookID() {
return bookID;
}
public void setBookID(int bookID) {
this.bookID = bookID;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public int getBookCounts() {
return bookCounts;
}
public void setBookCounts(int bookCounts) {
this.bookCounts = bookCounts;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
}
5.2实现sql方法的接口
package com.rui.dao;
import com.rui.pojo.Books;
import java.util.List;
public interface BookMapper {
int addBook(Books books);
int deleteBookById(int id);
int updateBook(Books books);
Books queryBookById(int id);
List<Books> queryAllBook();
}
5.3接口对应的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.rui.dao.BookMapper">
<insert id="addBook" parameterType="com.rui.pojo.Books">
insert into ssmbuild.books(bookName,bookCounts,detail)
values (#{bookName},#{bookCounts},#{detail});
</insert>
<delete id="deleteBookByID" parameterType="int">
delete from ssmbuild.books where bookID=#{id};
</delete>
<update id="updateBook" parameterType="com.rui.pojo.Books">
update ssmbuild.books set bookName=#{bookName},
bookCounts=#{bookCounts},detail=#{detail}
where bookID=#{bookID};
</update>
<select id="queryBookById" resultType="com.rui.pojo.Books">
select * from ssmbuild.books where bookID =#{id};
</select>
<select id="queryAllBook" resultType="com.rui.pojo.Books">
select * from ssmbuild.books;
</select>
</mapper>
5.4对应的service层数据
这里service层对应接口的方法其实也很好实现 就不再展示了
package com.rui.service;
import com.rui.dao.BookMapper;
import com.rui.pojo.Books;
import java.util.List;
public class BookServiceImpl implements BookService {
private BookMapper bookMapper;
public void setBookMapper(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public int addBook(Books books) {
return bookMapper.addBook(books);
}
public int deleteBook(int id) {
return bookMapper.deleteBookById(id);
}
public int updateBook(Books books) {
return bookMapper.updateBook(books);
}
public Books queryBookById(int id) {
return bookMapper.queryBookById(id);
}
public List<Books> queryAllBook() {
return bookMapper.queryAllBook();
}
}
6.Spring层配置
我们将Spring层分为对Dao和Service的配置会让结构更清晰一些
6.1Dao层配置
首先是数据源即dataSource的配置
<context:property-placeholder location="classpath:database.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
然后是sqlSessionFactory的配置
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="datasource"/>
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<property name="mapperLocations" value="classpath:Dao/UserMapper.xml"/>
</bean>
然后我们还需要配置一个sqlSession的模板对象
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
本身我们还需要让我们mybatis的mapper的接口有实现类可以实现对应的方法要达到的目的,但是spring给了我们一个可以直接封装这种类的类,这里给大家引入一下,具体什么作用小编还没有研究透彻
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.rui.dao"/>
</bean>
6.2Service层配置
这里大家要注意一个点就是我们的改查操作的事务不会进行自动提交,所以我们需要人为的对它进行设置,spring这里也帮我们封装好了对应的类,但是我们也还是可以通过Spring的AOP特性给对应的方法添加一个事务自动提交环绕 这里介绍一下spring自己带来的类,有关于这个类是否会自动生效这里小编也还没有测试过,大家如果想要知道可以自行测试或者查阅资料 那么我们的service层就是对应的service对象以及我们的自动提交事务配置
<context:component-scan base-package="com.rui.service"/>
<bean id="BookServiceImpl" class="com.rui.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
7.SpringMVC层的配置
注解驱动和资源过滤应用注解的时候会自动添加 这里我们用MVC中的注解配置 只需要多配置一个视图解析器,但这里还是配置了注解驱动和资源过滤,供大家看一下写法 首先我们要配置web.xml,这里我们需要配置MVC中的servlet以及过滤器
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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"
version="4.0">
<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:spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
然后是对于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"
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.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.rui.controller"/>
<mvc:annotation-driven/>
<mvc:default-servlet-handler/>
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
然后我们把这些配置文件全部引入到一个applicationContext.xml下就可以了 引入使用import 另外要提醒大家的是我们使用注解开发需要对应的包扫描我们使用properties文件的时候需要对应的propeities文件扫描也都体现在上文的代码块中了 注意这里配置的DispatcherServlet的核心文件用的是spring-mvc.xml 其实这会带来一些问题例如我们如果要使用自动装配可能就会导致它找不到对应的bean 为了保险起见还是使用applicationContext.xml会好一些
8.Test
我们写好配置文件以后需要证实其可行性
8.1MyBatis测试
因为不确定事务的自提交有没有配置好,于是我们选择使用查询语句来进行测试 测试代码:
package dao;
import com.rui.dao.BookMapper;
import com.rui.pojo.Books;
import org.junit.Test;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class mybatisTest {
@Test
public void test1_mybatis(){
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
SqlSessionTemplate sqlSession = (SqlSessionTemplate) context.getBean("sqlSession");
BookMapper mapper = sqlSession.getMapper(BookMapper.class);
List<Books> books = mapper.queryAllBook();
for(Books i:books){
System.out.println(i);
}
}
}
运行结果如下: 然后我们再来测试SpringMVC 使用注解开发进行测试 代码如下:
package com.rui.controller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.rui.pojo.User;
@Controller
public class ServletTest {
@RequestMapping(value="/test1")
@ResponseBody
public String test1() throws JsonProcessingException {
User user=new User();
user.setName("XiAoRayL");
ObjectMapper om=new ObjectMapper();
String writer = om.writeValueAsString(user);
System.out.println(writer);
return writer;
}
}
我们还需要配置一个tomcat运行环境,记得部署工件和设计一下上下文嗷 结果也是顺利的返回了一个json字符串 这就说明我们搭建的基本的SSM框架是可以运行的 ,那么这篇文章到这里也就结束了,谢谢大家观看,求一波关注~
|