0️⃣概述
👾SSM与三层架构对应关系
SpringMVC —— 表示层(controller、view)
Spring —— 业务逻辑层(service)
MyBatis —— 数据访问层(dao、pojo)
👾配置文件
spring-config.xml —— Spring容器,管理service和dao等对象,是业务逻辑层的容器
springmvc-config.xml —— SpringMVC容器,管理controller等对象,是视图层的容器
web.xml —— 配置SpringMVC前端控制器、过滤器等
👾项目结构
👾开发工具
编辑器:IDEA企业版
构建系统:Maven
数据库:MySQL 8.0.31
1️⃣导入依赖
使用maven构建工具开发,在pom.xml目录下导入相关依赖:
👾MyBatis与数据库相关依赖
🔴MySQL连接
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
🔴Druid数据库连接池
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
🔴MyBatis
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
👾Spring与SpringMVC相关依赖
🔴Spring与SpringMVC
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
🔴Spring对ORM支持的依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
👾MyBatis和Spring关联依赖
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
👾其他依赖
🔴Servlet依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
🔴JSON依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.4</version>
</dependency>
👾总览
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>Demo</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>Demo Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<!--MyBatis依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>
<!--SpringMVC依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--Spring对ORM支持的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.2.9.RELEASE</version>
</dependency>
<!--MyBatis和Spring关联的依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.2</version>
</dependency>
<!--json的依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.4</version>
</dependency>
</dependencies>
<build>
<finalName>Demo</finalName>
</build>
</project>
点击右上角的小按钮刷新导入
2️⃣编写配置文件
👾编写Spring-config.xml
🔴创建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.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
</beans>
🔴Dao层配置
<!--配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db_study?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!--配置SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置MapperScannerConfigurer-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
<property name="basePackage" value="com.app.dao"/>
</bean>
🔴Service层配置
<!--扫描所有的注解的类-->
<context:component-scan base-package="com.app">
<!--IoC容器排除@Controller注解的类-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--声明式事务-->
<tx:annotation-driven/>
🔴总览
<?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.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--Dao层-->
<!--配置数据源-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db_study?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!--配置SqlSessionFactoryBean-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置MapperScannerConfigurer-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
<property name="basePackage" value="com.app.dao"/>
</bean>
<!--Service层-->
<!--扫描所有的注解的类-->
<context:component-scan base-package="com.app">
<!--IoC容器排除@Controller注解的类-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--声明式事务-->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
👾编写Springmvc-config.xml
🔴创建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.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
</beans>
🔴Controller层
<!--扫描所有的Controller-->
<context:component-scan base-package="com.app.controller"/>
<!--配置映射器和适配器bean,同时增加其他功能-->
<mvc:annotation-driven/>
<!--交给web服务器处理,处理所有静态资源-->
<mvc:default-servlet-handler/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
🔴总览
<?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.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描所有的Controller-->
<context:component-scan base-package="com.app.controller"/>
<!--配置映射器和适配器bean,同时增加其他功能-->
<mvc:annotation-driven/>
<!--交给web服务器处理,处理所有静态资源-->
<mvc:default-servlet-handler/>
<!--视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
👾编写web.xml
🔴Spring监听器
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
🔴编码过滤器
<!--编码过滤器-->
<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>
🔴隐藏域过滤器
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
🔴前端控制器
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
🔴总览
<!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>
<!--spring-config.xml配置文件位置-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml</param-value>
</context-param>
<!--编码过滤器-->
<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>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--上下文加载程序监听器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3️⃣MySQL数据库配置
👾登录MySQL
管理员身份启动cmd,输入 net start mysql 启动 mysql 数据库服务。
net start mysql
输入用户名、密码登录 mysql
mysql -u 你的用户名 -p
查看 mysql 中的数据库,选择你的数据库
show databases;
use 你的数据库;
👾创建 user 表
创建了一张 user 表,包含了 id,name,password 三个字段。其中 id 字段为主键,设置为自动增长。
create table user(
id int primary key auto_increment,
name varchar(20),
password varchar(20)
);
👾插入数据
插入若干条记录,用于后面的测试
insert into user values(null,"ketty","root");
查看表
select * from user;
4️⃣IDEA连接数据库
👾选择MySQL
打开IDEA右侧的数据库连接,选择 + 号,选择MySQL.
👾填写相关配置
填写相关配置,包括MySQL连接的用户名和密码,要连接的数据库,在URL的后面添加如下字段:
?serverTimezone=GMT&useSSL=false
连接成功后,可以看见我们数据库中的表。如果没有出现表,可以点击上面的刷新按钮刷新一下
5️⃣数据访问层(dao、pojo)编写
数据访问层需要编写dao类、pojo类、dao.xml文件。我们使用IDEA插件自动生成。
👾添加插件
找到插件,在搜索栏搜索better-mybatis-generator插件,点击添加。
👾新建目录存放类
右键src/main/java目录,新建com.app.pojo、com.app.dao、com.app.service目录
👾填写要生成类的相关信息
右键user类,选择mabatis-generate选项。
这里我们修改pojo类、dao类、dao.xml 三大类文件生成的位置(红框标注处),分别修改成我们刚刚新建的com.app.pojo包以及com.app.dao包。
❗注意如果你的mysql版本是8.0及以上,需要勾选下面mysql_8(红框标注处)
❗查看mysql版本:打开cmd,输入mysql -V
mysql -V
修改完毕后,点击确定。第一次连接会要我们输入数据库连接的账号和密码。填写后在点击确定。
可以看见,我们的com.app.pojo和com.app.dao目录下多了四个文件。这四个文件是插件自动帮我们生成的,包括生成了一些常用的SQL单表操作,如根据条件查询,根据条件修改等。我们在service中就可以直接使用他们了。
6️⃣业务逻辑层(service)编写
👾UserService接口
package com.app.service;
import com.app.pojo.User;
public interface UserService {
User findUserByNameAndPassword(User user);
}
👾UserServiceImpl实现类
package com.app.service.impl;
import com.app.dao.UserDao;
import com.app.pojo.User;
import com.app.pojo.UserExample;
import com.app.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired // Spring自动注入
private UserDao userDao;
public User findUserByNameAndPassword(User user) {
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.createCriteria();
criteria.andNameEqualTo(user.getName());
criteria.andPasswordEqualTo(user.getPassword());
List<User> userList = userDao.selectByExample(userExample);
return userList.size() > 0 ? userList.get(0) : null;
}
}
7️⃣表示层(controller、view)编写
👾UserController类(示例:用户登录)
package com.app.controller;
import com.app.pojo.User;
import com.app.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
// 使用RESTful风格编写
public String login(User user) {
User loginUser = userService.findUserByNameAndPassword(user);
if (loginUser != null) return "welcome";
else return "redirect:login.jsp";
}
}
👾login.jsp(用户登录界面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title>
</head>
<body>
<form action="user" method="get">
name:<input name="name"><br>
password:<input name="password"><br>
<input type="submit">
</form>
</body>
</html>
👾welcome.jsp(登录成功界面)
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>welcome</title>
</head>
<body>
<h1>Welcome!!</h1>
</body>
</html>
8️⃣验证
打开浏览器,输入 http://localhost:8080/Demo_war/login.jsp
👾登录成功
输入存在的用户,转到welcom.jsp页面
👾登录失败
输入不存在的用户信息,重定向回login.jsp页面