完整工程已上传到GitHub:传送门
新建一个空的maven项目
maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.jam</groupId>
<artifactId>ssm-template</artifactId>
<version>1.0-SNAPSHOT</version>
<!--依赖-->
<dependencies>
<!--Junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!--数据库连接池-->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.5</version>
</dependency>
<!--servlet-jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--MyBatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
<!--Spring-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
<!--FastJson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.76</version>
</dependency>
<!--Lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
</dependencies>
<!--静态资源导出问题-->
<build>
<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>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
MyBatis整合
- 创建用于测试的POJO:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
/**
* id
*/
private long bookId;
/**
* 书名
*/
private String bookName;
/**
* 数量
*/
private int bookCounts;
/**
* 描述
*/
private String detail;
}
- Books的Mapper接口:
public interface BookMapper {
/**
* 通过id查询Book对象
* @param id bookId
* @return Book对象
*/
Books queryBookById(@Param("bookId") long id);
}
- BookMapper的xml文件:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.jam.dao.BookMapper">
<select id="queryBookById" parameterType="long" resultType="Books">
select * from books where bookId = #{bookId};
</select>
</mapper>
- 在resources目录下创建MyBaits的配置文件“MyBaits-config.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>
<!--注意配置的顺序-->
<settings>
<!-- 打印SQL-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
<!-- <!– 开启延迟加载 –>-->
<!-- <setting name="lazyLoadingEnabled" value="true"/>-->
<!-- <!– 开启二级缓存 –>-->
<!-- <setting name="cacheEnabled" value="true"/>-->
</settings>
<typeAliases>
<!--对这个目录下的POJO启用别名-->
<package name="cn.jam.pojo"/>
</typeAliases>
<!--在spring-dao.xml配置了扫描,这里不用每次注册-->
<!-- <mappers>-->
<!-- <mapper class="cn.jam.dao.BookMapper"/>-->
<!-- </mappers>-->
</configuration>
- 添加数据库信息的配置文件“database.properties”:
jdbc.driver=com.mysql.jdbc.Driver
#如果是用的MySQL 8.0+,这里要加时区的配置:&serverTimezone=Asia/Shanghai
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
- MyBatis中的连接池、mapper.xml等不在mybatis-config.xml里配置,都通过Spring来配置
Spring整合
- 首先添加Spring的applicationContext.xml,它包含其他相关的Spring配置文件。
<?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">
</beans>
- 通过spring-dao.xml配置dao的部分,整合Mybatis。
<?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 https://www.springframework.org/schema/context/spring-context.xsd">
<!--1.关联数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>
<!--2.连接池
dbcp:半自动化操作,不能自动连接
c3p0:自动化操作,自动加载配置文件,可以自动设置到对象中
druid
hikari-->
<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}"/>
<!--c3p0私有属性-->
<!--连接池大小-->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!--关闭连接后不自动commit-->
<property name="autoCommitOnClose" value="false"/>
<!--连接超时时间-->
<property name="checkoutTimeout" value="10000"/>
<!--获取连接失败重试次数-->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!--使用spring的数据源代替mybatis的,和c3p0相比,配置会简单点,但也就没那么灵活-->
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">-->
<!-- <property name="driverClassName" value="${jdbc.driver}"/>-->
<!-- <property name="url" value="${jdbc.url}"/>-->
<!-- <property name="username" value="${jdbc.username}"/>-->
<!-- <property name="password" value="${jdbc.password}"/>-->
<!-- </bean>-->
<!--3.SqlSessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<!--mybatis 配置文件-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--配置mapper配置文件-->
<property name="mapperLocations" value="classpath:cn/jam/dao/*.xml"/>
</bean>
<!--配置dao接口扫描包,动态的实现dao接口可以注入到Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--注入SqlSessionFactory-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--要扫描的dao包-->
<property name="basePackage" value="cn.jam.dao"/>
</bean>
</beans>
- 通过spring-service.xml配置service层,通过AOP切入事务
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--1.扫描service下的包-->
<context:component-scan base-package="cn.jam.service"/>
<!--2.将我们所有业务类,注入Spring,可以通过配置,也可以通过注解,这里用注解-->
<!--3.声明式事务-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--注入数据源-->
<property name="dataSource" ref="dataSource"/>
</bean>
<!--4.aop事务支持-->
<!--结合AOP,实现事务的织入-->
<tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
<tx:attributes>
<!--配置那些方法要织入事务,*代表所有方法-->
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--配置AOP切入事务-->
<aop:config>
<aop:pointcut id="txCutPoint" expression="execution(* cn.jam.dao.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="txCutPoint"/>
</aop:config>
</beans>
- 将spring-dao.xml、spring-service.xml加到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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<import resource="classpath:spring-dao.xml"/>
<import resource="classpath:spring-service.xml"/>
</beans>
- 编写service层中的BookService:
public interface BookService {
/**
* 通过id查找Book对象
* @param id id
* @return Book对象
*/
Books queryBookById(long id);
}
@Service
public class BookServiceImpl implements BookService {
private final BookMapper bookMapper;
/** Spring4.x之后,使用构造器就可以不需要@Autowired注解 */
public BookServiceImpl(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
public Books queryBookById(long id) {
return bookMapper.queryBookById(id);
}
}
SpringMVC整合
- 因为以开始是建的普通maven工程,在整合SpringMVC之前需要先配置web框架:
- 加好web框架后,先需要在web.xml中,配上SpringMVC的DispatchServlet、处理乱码的filter等
<?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">
<!--dispatchServlet-->
<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:applicationContext.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>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>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Session-->
<session-config>
<!--session过期时间,15min-->
<session-timeout>15</session-timeout>
</session-config>
</web-app>
- web.xml处理好后,开始写mvc的配置文件spring-mvc.xml,同时,要记得import到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: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/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--1.注解驱动,即handlerMapping、handlerAdapt-->
<mvc:annotation-driven/>
<!--2.静态资源过滤,防止通过请求直接拿到静态资源-->
<mvc:default-servlet-handler/>
<!--3.扫描包:controller-->
<context:component-scan base-package="cn.jam.controller"/>
<!--4.视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
- 编写测试用的BookController
@Controller
public class BookController {
private BookService bookService;
public BookController(BookService bookService) {
this.bookService = bookService;
}
@RequestMapping("query/{bookId}")
public String queryById(@PathVariable("bookId") long id, Model model) {
Books book = bookService.queryBookById(id);
model.addAttribute("book", JSON.toJSONString(book));
return "book";
}
}
- 在WEB-INF下新建一个jsp目录,存放jsp页面,同时新建一个book.jsp页面,来展示BookController返回的Book对象
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${book}
</body>
</html>
- 测试一下(我这里是本地已经有数据了,所以可以查到):
- 最后,这是整个工程的目录结构,以供参考
注意事项
- 如果使用IDEA,需要检查依赖的jar有没有以前打包到war包里,没有的话可以自己建一个lib目录,手动把jar加进来
转载:https://blog.csdn.net/qq_33954947/article/details/115681512
查看评论