闲言碎语: 框架在手,项目我有。
SSM 作为 JAVA 里面开发 WEB 项目比较成熟的项目,对像我这样的小朋友学习来开发项目来说还是比较友好的,整合相对来说还是困难一些的,不过,苦心人,天不负,终于搭建成功啦。如果你也在学习 SSM 整合,希望下面的文章对您有帮助。
SSM 整合有很多的方式,这里采用 xml 文件 + 注解的方式。
- 先搭建整合的环境。
- 搭建 Spring 的配置环境。
- 使用 Spring 整合 SpringMVC 框架。
- 使用 Spring 整合 MyBatis 框架。
CREATE TABLE `account` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
`money` double(10, 2) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
Account: 实体类 – 对应数据库中的一张表。
package com.ssm.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
/**
* 实体类层
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Account {
private Integer id;
private String name;
private Double money;
}
AccountDao: 数据访问层 – 和数据库打交道。
- 其实现类在整合 Mybatis 的时候可以通过 mapper 代理对象进行实现。
package com.ssm.dao;
import com.ssm.entity.Account;
import java.util.*;
public interface AccountDao {
/**
* 查找所有用户
* @return
*/
public List<Account> findAll();
/**
* 添加一个用户
* @param account
*/
public void save(Account account);
}
AccountService: 业务逻辑层 – Service 接口。
package com.ssm.service;
import com.ssm.entity.Account;
import java.util.List;
/**
* 业务逻辑层: Service 接口
*
*/
public interface AccountService {
/**
* 查找所有用户
* @return
*/
public List<Account> findAll();
/**
* 添加一个用户
* @param account
*/
public void save(Account account);
}
AccountServiceImpl: 业务逻辑层的实现类。
package com.ssm.service;
import com.ssm.entity.Account;
import java.util.List;
/**
* 业务逻辑层: Service 接口实现类
*/
public class AccountServiceImpl implements AccountService {
public List<Account> findAll() {
System.out.println("业务层,查询所有的用户");
return null;
}
public void save(Account account) {
System.out.println("业务层,添加一个用户");
}
}
AccountController: 控制器
package com.ssm.controller;
/**
* 控制器层
*/
public class AccountController {
}
<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">
<context:component-scan base-package="com.ssm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
beans>
import com.ssm.service.AccountService;
import com.ssm.service.AccountServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MyTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountServiceImpl bean = context.getBean(AccountServiceImpl.class);
System.out.println(bean);
bean.findAll();
}
}
<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>springMVCservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring-mvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springMVCservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
<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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.ssm">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
bean>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/images/**" location="/images/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:annotation-driven/>
beans>
package com.ssm.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 控制器层
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAll")
public String findAll() {
System.out.println("Controller,查询所有的用户信息。");
return "success";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
测试
启动 Tomcat 服务器的时候,就加载 spring 的配置文件,目的是将 spring 注解下的类所产生的对象注入到 IOC容器中。
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
这样 AccountServiceImpl 对象就注入到 Spring 的 IOC 容器中了,然后将其作为 AccountController 的私有属性,从而实现 Controller 调用 Service 层。
package com.ssm.controller;
import com.ssm.entity.Account;
import com.ssm.service.AccountService;
import com.ssm.service.AccountServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
/**
* 控制器层
*/
@Controller
@RequestMapping("/account")
public class AccountController {
/**
* 自动装配其对象属性
*/
@Autowired
@Qualifier("accountServiceImpl")
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(Model model) {
// 调用 Service 层的方法
List<Account> list = accountService.findAll();
model.addAttribute("list",list);
return "success";
}
}
这里采用注解的方式,与 xml 作用相同。
package com.ssm.dao;
import com.ssm.entity.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.*;
@Repository
public interface AccountDao {
/**
* 查找所有用户
* @return
*/
@Select("select * from account")
public List<Account> findAll();
/**
* 添加一个用户
* @param account
*/
@Insert("insert into account(name,money) values (#{name},#{money})")
public void save(Account account);
}
<configuration>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm?useSSL=false&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
dataSource>
environment>
environments>
<mappers>
<mapper class="com.ssm.dao.AccountDao"/>
mappers>
configuration>
public void test1() throws IOException {
// 加载配置文件
InputStream io = Resources.getResourceAsStream("spring-dao.xml");
// 创建 SqlSessionFactory ,解析配置资源
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(io);
// 创建 SqlSession 对象
SqlSession session = sqlSessionFactory.openSession();
// 获得代理对象
AccountDao dao = session.getMapper(AccountDao.class);
// 遍历集合
List<Account> accounts = dao.findAll();
for (Account account : accounts) {
System.out.println(account);
}
// 关闭资源
session.close();
io.close();
}
@Test
public void test2() throws IOException {
Account account = new Account(4,"熊三",500.0);
// 加载配置文件
InputStream io = Resources.getResourceAsStream("spring-dao.xml");
// 创建 SqlSessionFactory ,解析配置资源
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(io);
// 创建 SqlSession 对象
SqlSession session = sqlSessionFactory.openSession();
// 获得代理对象
AccountDao dao = session.getMapper(AccountDao.class);
dao.save(account);
// 需要进行手动提交事务
session.commit();
// 关闭资源
session.close();
io.close();
}
目的: 将代理对象注入到 Spring IOC 容器中,便于 Service 层调用代理对象的方法。
<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
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.ssm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm?useSSL=false&serverTimezone=UTC"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapper">
<property name="basePackage" value="com.ssm.dao"/>
bean>
beans>
package com.ssm.service;
import com.ssm.dao.AccountDao;
import com.ssm.entity.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 业务逻辑层: Service 接口实现类
*/
@Service("accountServiceImpl")
public class AccountServiceImpl implements AccountService {
/**
自动装配 AccountDao 对象,创建该对象的前提是先注入到 IOC 容器中
*/
@Autowired
@Qualifier("accountDao")
private AccountDao accountDao;
public List<Account> findAll() {
return accountDao.findAll();
}
public void save(Account account) {
System.out.println("业务层,添加一个用户");
accountDao.save(account);
}
}
package com.ssm.controller;
import com.ssm.entity.Account;
import com.ssm.service.AccountService;
import com.ssm.service.AccountServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServlet;
import java.util.List;
/**
* 控制器层
*/
@Controller
@RequestMapping("/account")
public class AccountController {
/**
* 自动装配其对象属性
*/
@Autowired
@Qualifier("accountServiceImpl")
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(Model model) {
// 调用 Service 层的方法
List<Account> list = accountService.findAll();
model.addAttribute("list",list);
return "success";
}
@RequestMapping("/save")
public String save(Account account) {
// 调用 Service 的方法
accountService.save(account);
// 重定向到 查询所有账户的 Controller
return "redirect:/account/findAll";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
head>
<body>
<a href="${pageContext.request.contextPath}/account/findAll">测试a>
<form action="${pageContext.request.contextPath}/account/save" method="">
<input type="text" name="name">
<input type="text" name="money">
<input type="submit" value="提交">
form>
body>
html>
目的 : 提高其安全性。
在 spring 的配置文件 applicationContext.xml 文件中添加下列内容即可:
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:advice id="txAdvice" transaction-manager="dataSourceTransactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="*" isolation="DEFAULT"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.ssm.service.*ServiceImpl.*(..))"/>
aop:config>