环境准备
前提须知
在SSM整合的时候,我们是用Spring框架去整合SpringMVC框架和MyBatis框架。
创建数据库和表结构
create database ssm; create table account( id int primary key auto_increment, name varchar(100), money double(7,2) );
创建 Maven 工程 ssm
目录结构:
导入坐标并建立依赖
MyBatis 和 Spring 的版本对应关系
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.keafmd</groupId> <artifactId>ssm</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>ssm 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.version>5.2.7.RELEASE</spring.version> <slf4j.version>1.7.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mysql.version>5.1.49</mysql.version> <mybatis.version>3.4.5</mybatis.version> </properties> <dependencies> <!-- spring --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.5</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.2</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.1</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies> <build> <finalName>ssm</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>
编写实体类
Account:
package com.keafmd.domain; import java.io.Serializable; /** * Keafmd * * @ClassName: Account * @Description: 账户实体类 * @author: 牛哄哄的柯南 * @date: 2021-02-17 21:03 */ public class Account implements Serializable { private Integer id; private String name; private Double money; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getMoney() { return money; } public void setMoney(Double money) { this.money = money; } @Override public String toString() { return "Account{" + "id=" + id + ", name='" + name + '\'' + ", money=" + money + '}'; } }
编写持久层接口
package com.keafmd.dao; import com.keafmd.domain.Account; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Select; import org.springframework.stereotype.Repository; import java.util.List; /** * Keafmd * * @ClassName: AccountDao * @Description: 账户dao接口 * @author: 牛哄哄的柯南 * @date: 2021-02-17 21:05 */ public interface AccountDao { //查询所有账户 public List<Account> findAll(); //保存账户 public void saveAccount(Account account); }
编写业务层接口
package com.keafmd.service; import com.keafmd.domain.Account; import java.util.List; /** * Keafmd * * @ClassName: AccountService * @Description: * @author: 牛哄哄的柯南 * @date: 2021-02-17 21:15 */ public interface AccountService { //查询所有账户 public List<Account> findAll(); //保存账户 public void saveAccount(Account account); }
编写业务层实现类
package com.keafmd.service.impl; import com.keafmd.dao.AccountDao; import com.keafmd.domain.Account; import com.keafmd.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Keafmd * * @ClassName: AccountServiceImpl * @Description: 账户的业务层实现类 * @author: 牛哄哄的柯南 * @date: 2021-02-17 21:16 */ public class AccountServiceImpl implements AccountService { @Override public List<Account> findAll() { System.out.println("业务层,查询所有。。。"); return null; } @Override public void saveAccount(Account account) { System.out.println("业务层,保存账户。。。"); } }
编写 Controller
package com.keafmd.controller; /** * Keafmd * * @ClassName: AccountController * @Description: 账户控制器 web * @author: 牛哄哄的柯南 * @date: 2021-02-17 21:19 */ public class AccountController { }
整合步骤
保证 Spring 框架在 web 工程中独立运行
第一步:编写 spring 配置文件并导入约束
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: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层的注解,要忽略web层注解,因为web层让SpringMVC框架去管理 --> <context:component-scan base-package="com.keafmd"> <!-- 配置要忽略的注解 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
第二步:使用注解配置业务层
AccountServiceImpl:
package com.keafmd.service.impl; import com.keafmd.dao.AccountDao; import com.keafmd.domain.Account; import com.keafmd.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Keafmd * * @ClassName: AccountServiceImpl * @Description: 账户的业务层实现类 * @author: 牛哄哄的柯南 * @date: 2021-02-17 21:16 */ @Service("accountService") public class AccountServiceImpl implements AccountService { @Override public List<Account> findAll() { System.out.println("业务层,查询所有。。。"); return null; } @Override public void saveAccount(Account account) { System.out.println("业务层,保存账户。。。"); } }
第三步:导入log4j.properties配置文件
# Set root category priority to INFO and its only appender to CONSOLE. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal log4j.rootCategory=info, CONSOLE, LOGFILE # Set the enterprise logger category to FATAL and its only appender to CONSOLE. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n # LOGFILE is set to be a File appender using a PatternLayout. log4j.appender.LOGFILE=org.apache.log4j.FileAppender log4j.appender.LOGFILE.File=d:\axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
第四步:测试 spring 能否独立运行
测试代码:
package com.keafmd.test; import com.keafmd.service.AccountService; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Keafmd * * @ClassName: TestSpring * @Description: 测试类 * @author: 牛哄哄的柯南 * @date: 2021-02-17 22:37 */ public class TestSpring { @Test public void run1(){ //加载配置文件 ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml"); //获取对象 AccountService as = (AccountService)ac.getBean("accountService"); //调用方法 as.findAll(); } }
运行结果:
业务层,查询所有。。。 Process finished with exit code 0
保证 SpringMVC 在 web 工程中独立运行
第一步:在 web.xml 中配置核心控制器(DispatcherServlet)
web.xml:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <!-- 配置前端控制器:服务器启动必须加载,需要加载springmvc.xml配置文件 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置初始化参数,加载springmvc.xml配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 启动服务器,创建该servlet --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</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> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
第二步:编写 SpringMVC 的配置文件
springmvc.xml:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 开启注解扫描,扫描controller的注解,别的不扫描 --> <context:component-scan base-package="com.keafmd"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 配置视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- JSP文件所在的目录 --> <property name="prefix" value="/WEB-INF/pages/"/> <!-- 文件的后缀名 --> <property name="suffix" value=".jsp"/> </bean> <!-- 过滤静态资源,设置静态资源不过滤 --> <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <!-- 开启对SpringMVC注解的支持 --> <mvc:annotation-driven/> </beans>
第三步:编写 Controller 和 jsp 页面
index.jsp:
<%-- Created by IntelliJ IDEA. User: Keafmd Date: 2021/2/17 Time: 23:20 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> <a href="account/findAll">测试查询</a> </body> </html>
AccountController:
package com.keafmd.controller; import com.keafmd.domain.Account; import com.keafmd.service.AccountService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; /** * Keafmd * * @ClassName: AccountController * @Description: 账户控制器 web * @author: 牛哄哄的柯南 * @date: 2021-02-17 21:19 */ @Controller @RequestMapping("/account") public class AccountController { /** * 查询所有 * @param * @return */ @RequestMapping("/findAll") public String findAll(){ System.out.println("表现层,查询所有账户信息。。。"); return "list"; } }
list.jsp:
<%-- Created by IntelliJ IDEA. User: Keafmd Date: 2021/2/18 Time: 15:50 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> <h1>查询所有的账户</h1> </body> </html>
第四步:部署tomcat服务器
启动服务器,进行测试
控制台输出:
表现层,查询所有账户信息。。。