本文主要是对于ssm项目整合简单入门做一些介绍,并不深入了解,只接触表面,对一些较复杂的内容也不过多描述。如文中有错误之处,望不吝赐教,谢谢~
一、SSM简介
顾名思义,ssm即为 spring+spring mvc+mybatis。ssm是这三种框架的集合,在开发中不单单使用某一框架,而使用多个框架,ssm恰好满足了这一功能。
ssm在Java web项目中的结构如下所示:
二、SSM简单项目入门
(1)准备好数据库
数据库名为test,有一张用户表user
(2)新建maven项目
并且选择好自己的maven配置以及仓库.
(3)引入依赖
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>org.example</groupId>
<artifactId>ssm_study_demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>ssm_study_demo Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<!--spring 版本号-->
<spring.version>5.2.3.RELEASE</spring.version>
<!--mybatis 版本号-->
<mybatis.version>3.4.5</mybatis.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>5.1.6</mysql.version>
</properties>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- log start -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<!-- log end -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<finalName>ssm_study_demo</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
(4)在mian目录下创建java、resources文件夹并分别指明为sources root和resources root。再在Java目录下创建controller包(控制器层)、dao包(持久层)、service包(服务层)和domain包(实物对象)。
(5)在domain目录下创建user类
package com.example.domain;
import java.io.Serializable;
public class User implements Serializable {
//id
private Integer id;
//用户名
private String username;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
'}';
}
}
(6)在dao目录下创建UserDao接口
package com.example.dao;
import com.example.domain.User;
public interface UserDao {
//根据用户名查询用户
public User findByUsername(String username);
}
(7)在service目录下创建UserService接口及其实现类UserServiceImpl
UserService
package com.example.service;
import com.example.domain.User;
public interface UserService {
/**
* 根据用户名查询用户
* @param username
* @return
*/
public User findByUsername(String username);
}
UserServiceImpl
(8)在controller目录下编写UserController类
(9)在resources目录下创建spring配置文件applicationContext.xml
(10)在resources目录下创建spring mvc配置文件springmva.xml
(11)在webapp下面的WEB-INF目录下新建pages目录,然后在pages目录下新建user,jsp文件
<%--
Created by IntelliJ IDEA.
User: 51954
Date: 2020/3/15
Time: 19:55
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>查询到用户</h3>
</body>
</html>
(12)将该项目部署到tomcat服务器上
(13)运行项目,点击测试,转到user.jsp页面,说明controller(使用spring mvc)这部分成功。
(14)整合spring和spring mvc,由于spring mvc主要是在controller方面,而spring主要在service和dao方面,在此案例中若UserController可以成功调用userService中的方法,则可说明二者已经成功整合在一起去了。
- 在web.xml文件中添加spring的监听器,以便启动spring的配置文件
<!--配置Spring的监听器(以启动spring的配置文件),默认只加载WEB-INF目录下的applicationContext.xml配置文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--设置配置文件的路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
- 在UserController里面调用UserService里面的方法
package com.example.controller;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(path = "/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(path = "findByUsername")
public String findByUsername(String username){
//调用service方法
System.out.println(userService.findByUsername("xiaoming"));
return "user";
}
}
再执行程序,发现结果与上面一致。注意控制台输出的null值是因为此时还未连接数据库,因此查不到数据,如果单纯是为验证的话,可以将findByUsername函数里面直接改为输出一段话,这样测试起来更方便一些,这里不这样只是为了后后面连接数据库更好的衔接。
(15)在resources目录下新建mybatis核心配置文件SqlMapConfig.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>
<!--配置环境-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!--引入映射配置文件-->
<mappers>
<package name="com.example.dao"/>
</mappers>
</configuration>
(16)在UserDao中添加相应的注解来完成对数据库的操作
package com.example.dao;
import com.example.domain.User;
import org.apache.ibatis.annotations.Select;
public interface UserDao {
//根据用户名查询用户
@Select("select * from user where username=#{username}")
public User findByUsername(String username);
}
(17)创建TestMybatis来验证导入mybatis是否成功
package com.example.test;
import com.example.dao.UserDao;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
public class TestMybatis {
@Test
public void run1() throws IOException {
//加载配置文件
InputStream in=Resources.getResourceAsStream("SqlMapConfig.xml");
//创建SqlSessionFactory对象
SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(in);
//创建sqlSession对象
SqlSession session=factory.openSession();
//获取代理对象
UserDao userDao=session.getMapper(UserDao.class);
//执行方法
System.out.println(userDao.findByUsername("xiaoming"));
//关闭资源
session.close();
in.close();
}
}
输出结果如下,说明成功使用了mybatis。
(18)整合mybatis,在spring的配置文件里面配置有关mybatis的选项,并删除之前的mybatis配置文件SqlMapConfig
<?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:aop="http://www.springframework.org/schema/aop"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--开启注解的扫描,希望处理service和dao,controller不需要Spring框架去处理而是用spring mvc-->
<context:component-scan base-package="com.example" >
<!--配置哪些注解不扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--Spring整合MyBatis框架-->
<!--配置连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3306/test"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
</bean>
<!--配置SqlSessionFactory工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置Dao接口所在包-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.example.dao"/>
</bean>
<!--配置Spring框架声明式事务管理-->
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
</tx:attributes>
</tx:advice>
<!--配置AOP增强-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.service.impl.*ServiceImpl.*(..))"/>
</aop:config>
</beans>
(19)在UserDao上面添加@Repository注解,在UserServiceImpl里面调用UserDao的函数
UserDao
package com.example.dao;
import com.example.domain.User;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
@Repository
public interface UserDao {
//根据用户名查询用户
@Select("select * from user where username=#{username}")
public User findByUsername(String username);
}
UserServiceImpl
package com.example.service.impl;
import com.example.dao.UserDao;
import com.example.domain.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
/**
* 根据用户名查询用户
* @param username
* @return
*/
@Override
public User findByUsername(String username) {
return userDao.findByUsername(username);
}
}
(20)启动项目,运行结果与上面一致,说明mybatis整合成功。
三、总结
SSM项目整合以spring为核心,并且spring mvc主要是处理控制器方面,mybatis主要是处理持久层方面,而spring是统筹这两部分以及处理其他部分的内容。
2020.03.15
转载:https://blog.csdn.net/ataraxy_/article/details/104882270