众所周知,SSM项目是指spring+springmvc+mybatis合成的一个项目,接下来将带着大家快速搭建SSM项目
一、创建项目
- 在这里我们使用的是
Intellj Idea
作为开发工具进行创建
项目结构如图:
二、集成spring依赖
<!--spring start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <!--suppress UnresolvedMavenProperty --> <version>4.3.20.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <!--suppress UnresolvedMavenProperty --> <version>4.3.20.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <!--suppress UnresolvedMavenProperty --> <version>4.3.20.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.3.20.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>4.3.20.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.20.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.3.20.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.3.20.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.20.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.3.20.RELEASE</version> </dependency> <!--spring end -->
三、创建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" 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"> <context:component-scan base-package="com.ay"/> </beans>
四、配置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> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置DispatcherServlet --> <servlet> <servlet-name>spring-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置SpringMVC需要加载的配置文件 spring-mvc.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring-dispatcher</servlet-name> <!--默认匹配所有的请求 --> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
五、创建springTest类进行测试
package com.ay.test; import org.junit.jupiter.api.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Service; @Service public class SpringTest { @Test public void testSpring(){ ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); SpringTest springTest = (SpringTest) applicationContext.getBean("springTest"); springTest.sayHello(); } public void sayHello(){ System.out.println("Hello ay"); } }
六、集成springmvc框架
- 添加springmvc依赖
<!--springmvc start --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <!--suppress UnresolvedMavenProperty --> <version>3.1.0</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <!--suppress UnresolvedMavenProperty --> <version>4.3.20.RELEASE</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> <!--springmvc end -->
七、在web.xml中添加DispatcherServlet设置
<!--配置DispatcherServlet --> <servlet> <servlet-name>spring-dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置SpringMVC需要加载的配置文件 spring-mvc.xml --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring-dispatcher</servlet-name> <!--默认匹配所有的请求 --> <url-pattern>/</url-pattern> </servlet-mapping>
八、配置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" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <!-- 扫描controller(后端控制器),并且扫描其中的注解--> <context:component-scan base-package="com.ay.controller"/> <!--设置配置方案 --> <mvc:annotation-driven/> <!-- 自定义RequestMappingHandlerAdapter --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"> <property name="messageConverters"> <list> <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/> <bean class="org.springframework.http.converter.StringHttpMessageConverter"/> <bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/> </list> </property> </bean> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"/> <!--配置JSP 显示ViewResolver(视图解析器)--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <aop:aspectj-autoproxy proxy-target-class="true"> </aop:aspectj-autoproxy> </beans>
九、创建hello.jsp文件
<%-- Created by IntelliJ IDEA. User: 编程小哥令狐 Date: 2020/12/14 Time: 15:25 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> hello ,ay </body> </html>
十、集成mybatis
10.1、导入mybatis框架所需依赖
pom.xml
<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> <javax.servlet.version>4.0.0</javax.servlet.version> <jstl.version>1.2</jstl.version> <mybatis.version>3.4.6</mybatis.version> <mysql.connector.java.version>8.0.9-rc</mysql.connector.java.version> <druid.version>1.1.9</druid.version> <mybatis.spring.version>1.3.2</mybatis.spring.version> </properties> <!--mybatis start --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.16</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.2.9.RELEASE</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!--mybatis end -->
10.2、创建jdbc.properties文件
jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/springmvc-mybatis-book?serverTimezone=GMT&useSSL=false jdbc.username=root jdbc.password=123456
10.3、配置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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="com.ay"/> <!--1、配置数据库相关参数--> <context:property-placeholder location="classpath:jdbc.properties"/> <!--2.数据源 druid --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--3、配置SqlSessionFactory对象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--注入数据库连接池--> <property name="dataSource" ref="dataSource"/> <!--扫描sql配置文件:mapper需要的xml文件--> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg index="0" ref="sqlSessionFactory"/> </bean> <!-- 扫描basePackage下所有以@MyBatisDao注解的接口 --> <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <property name="basePackage" value="com.ay.dao"/> </bean> </beans>
十一、创建数据库表结构
- 数据库名:
springmvc-mybatis-book
- 表名称:
ay_user
- 数据库工具:Navicat for MySQL
- SQL创建命令:
/* Navicat Premium Data Transfer Source Server : localhost_3306 Source Server Type : MySQL Source Server Version : 80011 Source Host : localhost:3306 Source Schema : springmvc-mybatis-book Target Server Type : MySQL Target Server Version : 80011 File Encoding : 65001 Date: 16/12/2020 18:45:59 */ SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- ---------------------------- -- Table structure for ay_user -- ---------------------------- DROP TABLE IF EXISTS `ay_user`; CREATE TABLE `ay_user` ( `id` bigint(32) NOT NULL AUTO_INCREMENT, `name` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `password` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of ay_user -- ---------------------------- INSERT INTO `ay_user` VALUES (1, '阿毅', '123'); INSERT INTO `ay_user` VALUES (2, '阿兰', '123'); SET FOREIGN_KEY_CHECKS = 1;
十二、创建实体类
12.1、创建model层的AyUser类
package com.ay.model; import java.io.Serializable; import java.util.List; /** * 用户实体 * * @author Ay * @date 2018/04/02 */ public class AyUser implements Serializable { private Integer id; private String name; private String password; 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 String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
12.2、创建dao层AyUserDao接口
package com.ay.dao; import com.ay.model.AyUser; import org.apache.ibatis.annotations.*; import org.apache.ibatis.session.RowBounds; import org.springframework.stereotype.Repository; import java.util.List; import java.util.Map; @Repository public interface AyUserDao { List<AyUser> findAll(); }
12.3、创建service层AyUserService接口
package com.ay.service; import com.ay.model.AyUser; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.session.RowBounds; import java.util.List; import java.util.Map; public interface AyUserService { List<AyUser> findAll(); }
12.4、创建impl文件夹存放一个新的AyUserService接口实现类AyUserServiceImpl
package com.ay.service.impl; import com.ay.dao.AyUserDao; import com.ay.model.AyUser; import com.ay.service.AyUserService; import org.apache.ibatis.session.RowBounds; import org.springframework.stereotype.Repository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.List; import java.util.Map; @Service public class AyUserServiceImpl implements AyUserService { @Resource private AyUserDao ayUserDao; public List<AyUser> findAll() { return ayUserDao.findAll(); } }
12.5、创建controller层和AyUserController类
package com.ay.controller; import com.ay.model.AyUser; import com.ay.service.AyUserService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.Errors; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List; /** * 用户控制层 * * @author Ay * @date 2020/04/02 */ @Controller @RequestMapping("/user") public class AyUserController { @Resource private AyUserService ayUserService; @GetMapping("/findAll") public String findAll(Model model){ List<AyUser> ayUserList = ayUserService.findAll(); for(AyUser ayUser : ayUserList){ System.out.println("id: " + ayUser.getId()); System.out.println("name: " + ayUser.getName()); } return "hello"; } }
12.6、在resources/mapper文件下创建AyUserMapper.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="com.ay.dao.AyUserDao"> <sql id="userField"> a.id as "id", a.name as "name", a.password as "password" </sql> <select id="findAll" resultType="com.ay.model.AyUser"> select <include refid="userField"/> from ay_user a </select> </mapper>
十三、访问:http://localhost:8080/SSM_war/user/findAll
6、在resources/mapper文件下创建AyUserMapper.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="com.ay.dao.AyUserDao"> <sql id="userField"> a.id as "id", a.name as "name", a.password as "password" </sql> <select id="findAll" resultType="com.ay.model.AyUser"> select <include refid="userField"/> from ay_user a </select> </mapper>
十三、访问:http://localhost:8080/SSM_war/user/findAll