-
pom.xml 文件中新增依赖
<?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>com</groupId>
<artifactId>MySSM</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<!-- 统一管理spring相关产品的版本 -->
<spring-version>4.3.9.RELEASE</spring-version>
</properties>
<dependencies>
<!-- spring mvc的依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- rest 风格 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.10</version>
</dependency>
<!-- mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- mybatis spring的插件,将mybatis交给spring来管理 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!-- spring的单元测试 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- spring的事务 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<!-- spring aop的面向切面的配置 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>com.springsource.org.aspectj.weaver</artifactId>
<version>1.6.8.RELEASE</version>
</dependency>
<!-- druid 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.28</version>
</dependency>
<!-- 日志信息 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- junit单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- lombok,特别注意,与maven的tomcat插件冲突时,将scope设置为provided -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<!-- jsp -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- jstl -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<!-- 不过滤java下的.xml文件和.properties配置文件 -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<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>
<plugins>
<!-- define the project compile level -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- 添加tomcat插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8081</port>
</configuration>
</plugin>
</plugins>
</build>
</project>
-
web.xml 的配置
<?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_3_1.xsd"
version="3.1">
<!--配置Spring mvc-->
<servlet>
<servlet-name>dispatcherServlet</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>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--spring写好的中文过滤器-->
<filter>
<filter-name>encode</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>encode</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
-
resources下的 db.properties
driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://localhost:3307/mysqls?serverTimezone=UTC
user = root
pass = 123456
maxActive = 50
minIdle = 1
-
resources下的 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: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">
<!--设置ssm的整合注解配置-->
<context:annotation-config />
<!--设置包扫描,分别扫描controller和service包-->
<context:component-scan base-package="com.controller" />
<context:component-scan base-package="com.service" />
<!--注解驱动-->
<mvc:annotation-driven />
<!--配置默认资源可以被访问-->
<mvc:default-servlet-handler />
<!--引入spring和mybatis的整合文件-->
<import resource="classpath:spring-mybatis.xml" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
-
resource下的 spring-mybatis.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: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 http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 引入数据库配置信息文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 配置druid数据源 -->
<bean id="ds" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${url}"></property>
<property name="driverClassName" value="${driver}" />
<property name="username" value="${user}" />
<property name="password" value="${pass}" />
</bean>
<!-- 配置SqlSessionFactoryBean对象,用来获取SqlSession -->
<bean id="sf" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="typeAliasesPackage" value="com.pojo" />
<property name="mapperLocations" value="classpath:com/dao/mapper/*Mapper.xml" />
<property name="dataSource" ref="ds"></property>
<property name="configLocation" value="classpath:mybatis-config.xml" />
</bean>
<!-- 配置映射扫描器,分别设置dao包的扫描和SqlSessionFactory的指定 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.dao" />
<property name="sqlSessionFactoryBeanName" value="sf" />
</bean>
<!-- 配置事务管理器 -->
<bean id="dtx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="ds"></property>
</bean>
<tx:advice id="tx" transaction-manager="dtx">
<!-- 声明属性,声明事务的规则 -->
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="insert*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
<tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="Exception" />
</tx:attributes>
</tx:advice>
<!-- 定义切面 -->
<aop:config>
<aop:pointcut id="mpt" expression="execution(* com.service.*.*(..))" />
<aop:advisor advice-ref="tx" pointcut-ref="mpt" />
</aop:config>
</beans>
-
SqlSessionFactoryBean
- 在Mybatis的所有操作都是基于一个SqlSession的,而SqlSession是由SqlSessionFactory来产生的,SqlSessionFactory又是由SqlSessionFactoryBuilder来生成的。
- 但是Mybatis-Spring是基于SqlSessionFactoryBean的。在使用Mybatis-Spring的时候,我们也需要SqlSession,而且这个SqlSession是内嵌在程序中的,一般不需要直接访问。
- SqlSession也是由SqlSessionFactory来产生的,但是Mybatis-Spring给我们封装了一个SqlSessionFactoryBean,在这个bean里面还是通过SqlSessionFactoryBuilder来建立对应的SqlSessionFactory,进而获取到对应的SqlSession。通过SqlSessionFactoryBean我们可以通过对其指定一些属性来提供Mybatis的一些配置信息。
-
MapperScannerConfigure
- Mybatis-Spring 为我们提供了一个叫做 MapperScannerConfigurer 的类,通过这个类 Mybatis-Spring 会自动为我们注册 Mapper 对应的 MapperFactoryBean 对象。
- 我们需要在 Spring 的 applicationContext 配置文件中定义一个 MapperScannerConfigurer 对应的 bean 。对于 MapperScannerConfigurer 而言有一个属性是我们必须指定的,那就是 basePackage 。
- basePackage 是用来指定 Mapper 接口文件所在的基包的,在这个基包或其所有子包下面的 Mapper 接口都将被搜索到。多个基包之间可以使用逗号或者分号进行分隔。最简单的 MapperScannerConfigurer 定义就是只指定一个 basePackage 属性。
-
resources下的 mybatis-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>
<setting name="logImpl" value="LOG4J" />
</settings>
</configuration>
-
resource下的 log4j.properties
# Global logging configuration
log4j.rootLogger=ERROR, stdout, F
# MyBatis logging configuration...
log4j.logger.com.dao=TRACE
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
log4j.appender.F = org.apache.log4j.DailyRollingFileAppender
log4j.appender.F.File =myproj.log
log4j.appender.F.Append = true
log4j.appender.F.Threshold = DEBUG
log4j.appender.F.layout=org.apache.log4j.PatternLayout
log4j.appender.F.layout.ConversionPattern=%-d{yyyy-MM-dd HH\:mm\:ss}-[%p %F\:%L] %m%n
-
配置文件结束,环境搭建完毕,开始编写代码, User.java
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int uid;
private String username;
private String password;
private int age;
private String addr;
}
-
UserController.java
@Controller
public class UserController {
/**
* 动态注入service对象
*/
@Resource
private IUserService userService;
@GetMapping("/Users")
@ResponseBody
public List<User> getUsers(){
return userService.getAllUsers();
}
@GetMapping("/Users/{uid}")
@ResponseBody
public User getUserByUid(@PathVariable int uid){
return userService.getUserByUid(uid);
}
@GetMapping("/UsersPage")
public String getUsersPage(Model model){
model.addAttribute("users", userService.getAllUsers());
return "user";
}
@GetMapping("/getUserByUidPage/{uid}")
public String getUserByUidPage(@PathVariable int uid, Model model){
model.addAttribute("u", userService.getUserByUid(uid));
return "updateUser";
}
}
-
IUserService.java
public interface IUserService {
List<User> getAllUsers();
User getUserByUid(int uid);
}
-
UserServiceImpl.java
/**
* 注意Service的实现类之上一定要添加service注解
*/
@Service
public class UserServiceImpl implements IUserService {
/**
* 动态注入dao组件
*/
@Resource
private IUserDao userDao;
@Override
public List<User> getAllUsers() {
return userDao.getAllUsers();
}
@Override
public User getUserByUid(int uid) {
return userDao.getUserByUid(uid);
}
}
-
IUserDao.java
public interface IUserDao {
List<User> getAllUsers();
User getUserByUid(int uid);
}
-
dao/mapper下新增 UserMapper.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属性 -->
<mapper namespace="com.dao.IUserDao">
<sql id="all">
select * from user
</sql>
<select id="getAllUsers" resultType="user">
<include refid="all" />
</select>
<select id="getUserByUid" resultType="user">
<include refid="all" />
where uid = #{uid}
</select>
</mapper>
- 双击Maven菜单下的Plugins下的tomcat7下的tomcat7:run运行;运行结果如下:
D:\Java\JDK\bin\java.exe -Dmaven.multiModuleProjectDirectory=F:\IDEA-Work\MySSM -Dmaven.home=D:\Java\Maven\apache-maven-3.6.3 -Dclassworlds.conf=D:\Java\Maven\apache-maven-3.6.3\bin\m2.conf "-Dmaven.ext.class.path=D:\JetBrains\IntelliJ IDEA 2019\plugins\maven\lib\maven-event-listener.jar" "-javaagent:D:\JetBrains\IntelliJ IDEA 2019\lib\idea_rt.jar=54290:D:\JetBrains\IntelliJ IDEA 2019\bin" -Dfile.encoding=UTF-8 -classpath D:\Java\Maven\apache-maven-3.6.3\boot\plexus-classworlds-2.6.0.jar;D:\Java\Maven\apache-maven-3.6.3\boot\plexus-classworlds.license org.codehaus.classworlds.Launcher -Didea.version2019.3 -s D:\Java\Maven\apache-maven-3.6.3\conf\settings.xml org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run
[INFO] Scanning for projects...
[INFO]
[INFO] -----------------------------< com:MySSM >------------------------------
[INFO] Building MySSM 1.0-SNAPSHOT
[INFO] --------------------------------[ war ]---------------------------------
[INFO]
[INFO] >>> tomcat7-maven-plugin:2.2:run (default-cli) > process-classes @ MySSM >>>
[INFO]
[INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ MySSM ---
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] Copying 1 resource
[INFO] Copying 5 resources
[INFO]
[INFO] --- maven-compiler-plugin:3.6.1:compile (default-compile) @ MySSM ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] <<< tomcat7-maven-plugin:2.2:run (default-cli) < process-classes @ MySSM <<<
[INFO]
[INFO]
[INFO] --- tomcat7-maven-plugin:2.2:run (default-cli) @ MySSM ---
[INFO] Running war on http://localhost:8081/
[INFO] Using existing Tomcat server configuration at F:\IDEA-Work\MySSM\target\tomcat
[INFO] create webapp with contextPath:
三月 18, 2020 9:52:43 上午 org.apache.coyote.AbstractProtocol init
信息: Initializing ProtocolHandler ["http-bio-8081"]
三月 18, 2020 9:52:43 上午 org.apache.catalina.core.StandardService startInternal
信息: Starting service Tomcat
三月 18, 2020 9:52:43 上午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet Engine: Apache Tomcat/7.0.47
三月 18, 2020 9:52:51 上午 org.apache.catalina.core.ApplicationContext log
信息: No Spring WebApplicationInitializer types detected on classpath
三月 18, 2020 9:52:52 上午 org.apache.coyote.AbstractProtocol start
信息: Starting ProtocolHandler ["http-bio-8081"]
三月 18, 2020 9:52:57 上午 org.apache.catalina.core.ApplicationContext log
信息: Initializing Spring FrameworkServlet 'dispatcherServlet'
- 在浏览器中输入 http://localhost:8081/ 来检测框架是否搭建成功。