目录
spring配置文件applicationContext.xml
jdbc属性文件jdbc.propertise(不影响ssm的整合)
日志属性文件log4j.properties(不影响ssm的整合)
entity层,实体类名与数据库中的表名一致,成员变量与表中字段一致
Controller层,提供多种控制器,灵活地调用业务逻辑,与前端进行交互
一、ssm简介
ssm,即springmvc + spring +mybatis。ssm的搭建,就在于这三个框架的整合。
准备工作有导入依赖包,配置文件。
使用maven导包,会比较轻松。
二、准备工作
配置文件相关目录结构:
-
相关依赖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.lanqiao</groupId> <artifactId>maven_ssms</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>maven_ssms 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.7</maven.compiler.source> <maven.compiler.target>1.7</maven.compiler.target> </properties> <dependencies> <!--导入相关依赖--> <!--带入springmvc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.9</version> </dependency> <!--提供对servlet的交互--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!--提供对jsp的交互--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <!--提供对mybatis的支持,提供mybatis对spring的整合--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.6</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <!--使用spring的jdbc--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.9</version> </dependency> <!--提供jdbc对数据库的连接支持--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <!--druid连接池,便于连接--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.6</version> </dependency> <!--aspect依赖,支持文件上传--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.7</version> <scope>runtime</scope> </dependency> <!--使用jsp标准标签库,导入jstl和standard包--> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!--导入日志,可以记录和查看运行的相关信息,对ssm框架没有影响--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!--导入测试,便于使用测试类检验,对ssm框架没有影响--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.7.0</version> <scope>test</scope> </dependency> <!--lombok的导入,对ssm没有影响,但是可以简化各种get、set方法和构造器的书写--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.20</version> <scope>provided</scope> </dependency> <!--提供对json的支持,前端和后端数据的传输--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> </dependencies> </project>
-
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:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- 自动扫描,支持使用注解方式,自动装配bean --> <context:component-scan base-package="org.group" /> <!-- 加载jdbc的属性文件到上下文 --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置数据源 --> <bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性 url、user、password --> <property name="driverClassName" value="${jdbc_driverClass}"/> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> </bean> <!-- 配置mybatis的sqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="druidDataSource" /> <!-- 自动扫描mappers.xml文件 --> <property name="mapperLocations" value="classpath:org/group/mapper/*.xml"></property> <!-- mybatis配置文件 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类,mapper下的接口会自动扫描到ioc容器,可以不需要注解 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="org.group.mapper" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="druidDataSource" /> </bean> <tx:annotation-driven transaction-manager="transactionManager"/> <aop:aspectj-autoproxy/> </beans>
-
springmvc配置文件springmvc.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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 使用注解的包,包括子集 --> <context:component-scan base-package="org.group.controller" /> <!-- 注解的驱动,会自动注册几个bean,其中一个功能把对象和json进行转化 --> <mvc:annotation-driven></mvc:annotation-driven> <!-- 定义静态资源文件映射路径 --> <mvc:resources location="/images/" mapping="/images/**"></mvc:resources> <mvc:resources location="/css/" mapping="/css/**"></mvc:resources> <mvc:resources location="/js/" mapping="/js/**"></mvc:resources> <!-- 视图解析器,给返回值加上前缀和后缀 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--返回值前缀--> <property name="prefix" value="/" /> <!--返回值后缀--> <property name="suffix" value=".jsp"></property> </bean> </beans>
-
mybatis配置文件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> <!--对其中的类起别名--> <typeAliases> <package name="org.group"/> </typeAliases> </configuration>
-
web配置文件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" metadata-complete="true"> <!--未找到路径时,跳转--> <welcome-file-list> <welcome-file>login.jsp</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>index.html</welcome-file> </welcome-file-list> <!-- 定义了一个全局的上下文参数,参数里定义一个全局的spring配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext*.xml</param-value> </context-param> <!-- 定义了一个上下文 监听器,当上下文加载的时候会自动加载上面的applicationContext.xml--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 由spring框架提供的字符编码过滤器,把所有的编码转换成UTF-8 --> <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> <!-- springmvc的核心控制分发器 ,加载springmvc,并加载后缀有.do的路径--> <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:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
-
jdbc属性文件jdbc.propertise(不影响ssm的整合)
jdbc_url=jdbc:mysql://localhost:3306/mysql?allowMultiQueries=true jdbc_driverClass=com.mysql.jdbc.Driver jdbc_username=root jdbc_password=123
-
日志属性文件log4j.properties(不影响ssm的整合)
log4j.rootLogger=debug,std,f1 log4j.appender.std=org.apache.log4j.ConsoleAppender log4j.appender.std.layout=org.apache.log4j.PatternLayout log4j.appender.std.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm} %l%m%n log4j.appender.f1=org.apache.log4j.FileAppender log4j.appender.f1.File=f:/ssm.log log4j.appender.f1.layout=org.apache.log4j.TTCCLayout log4j.appender.f1.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH:mm} %l%m%n
三、使用ssm的示例
整合ssm之后,就可以使用ssm框架,就可以专注业务方面的开发了。
相关层级目录结构:
数据库及代码展示
数据库表结构
表数据
-
entity层,实体类名与数据库中的表名一致,成员变量与表中字段一致
package org.group.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /*使用注解,省去get、set方法和全参和无参的构造方法*/ @Data @AllArgsConstructor @NoArgsConstructor public class Student { /*成员变量与数据库表字段一致*/ private Integer id; private Integer name; private String age; }
-
Mapper层,与数据库进行交互
package org.group.mapper; import org.apache.ibatis.annotations.Select; import org.group.entity.Student; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface StudentMapper { /*使用mybatis注解,进行查询,得到所有student*/ @Select("select * from student") List<Student> selectAllStudents(); }
-
Service层,对传回的数据进行处理
package org.group.service; import org.group.entity.Student; import java.util.List; /*抽象类定义功能*/ public interface StudentService { List<Student> getAllStudents(); }
package org.group.service.impl; import org.group.entity.Student; import org.group.mapper.StudentMapper; import org.group.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /*定义bean的id名*/ @Service("studentService") public class StudentServiceImpl implements StudentService { /*使用Ioc来注入需要的studeMapper对象*/ @Autowired StudentMapper studentMapper; /*实现抽象方法定义的功能*/ @Override public List<Student> getAllStudents() { return studentMapper.selectAllStudents(); } }
-
Controller层,提供多种控制器,灵活地调用业务逻辑,与前端进行交互
package org.group.controller; import org.group.entity.Student; import org.group.service.StudentService; 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 java.util.ArrayList; import java.util.List; /*加入注解,识别为控制器*/ @Controller public class StudentController { /*使用IoC容器注入studentService对象*/ @Autowired StudentService studentService; /*定义控制器路径*/ @RequestMapping("/selectStudent.do") public String getAllStudents(Model model){ List<Student> studentList = new ArrayList<>(); /*调用业务逻辑,得到student集合*/ studentList = studentService.getAllStudents(); /*将集合放入model范围*/ model.addAttribute("studentList",studentList); /*跳转至test.jsp*/ return "forward:test.jsp"; } }
-
前端网页
test.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<!--通过连接,调用控制器-->
<a href="/selectStudent.do">查询所有学生</a>
</body>
</html>
test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false" %>
<%--加载标签库,并可以使用el表达式--%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<body>
<%--得到model里的student集合,并遍历显示--%>
<c:forEach items="${studentList}" var="student">
<table>
<tr>
<td>${student.id}</td>
<td>${student.name}</td>
<td>${student.age}</td>
</tr>
</table>
</c:forEach>
</body>
</html>
四、运行效果
首先进入到test.html页面
点击超链接,通过控制器,跳转到控制器,获取student集合,随后跳转至test.jsp页面显示
五、总结
ssm框架的搭建,准备工作比较多,导入依赖,容易因为版本问题,而导致后期出错。ssm是通过配置文件来整合的。mybatis的部分内容,放置在spring配置文件中,完成spring和mybatis的整合;启动Tomcat之后,使用servlet来加载springmvc,接着通过监听上下文的加载,来装在spring的配置文件,达到了springmvc和spring整合的效果。