1 环境搭建
1.1 数据库文件
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int NOT NULL AUTO_INCREMENT COMMENT 'id主键',
`username` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`password` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户密码',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 3 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = DYNAMIC;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES (1, 'admin', 'admin');
INSERT INTO `user` VALUES (2, 'tom', 'tom');
INSERT INTO `user` VALUES (3, 'kate', 'kate');
SET FOREIGN_KEY_CHECKS = 1;
1.2 创建Maven工程
【1】点击:File ---> Module,选择 Maven,勾选 Create from achetype,选择webapp,如下图,点击NEXT
【2】创建模块名, 给项目命名并保存到相应路径下,点击NEXT
【3】选择maven配置(已选可不用管),点击Finish
【4】目录结构如下:
1.3 引入依赖
<?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.spg</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.0.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mysql.version>8.0.16</mysql.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies>
<!-- spring -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</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>
</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.0</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</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>
1.3 创建java和resources文件夹
在main目录下面创建java和resources文件夹,并设置相应文件
1.4 创建类和接口文件
在java文件夹下创建类文件,所需的类文件有以下几个:
【1】存放JavaBean
的 domain
包下的用户类:com.spg.domain.User
package com.spg.domain;
/**
* 用户类
* @author shangpange
*/
public class User {
private Integer id;
private String username;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
【2】数据访问层 dao
包下的用户 dao
接口:com.spg.dao.UserDao
package com.spg.dao;
import com.spg.domain.User;
import java.util.List;
/**
* 用户持久层接口
* @author shangpange
*/
public interface UserDao {
// 查询所有用户
public List<User> findAllUser();
// 用户注册
public Integer insertUser(User user);
// 用户登录
public User login(User user);
}
【3】业务层 service
包下的 UserService
接口:com.spg.service.UserService
package com.spg.service;
import com.spg.domain.User;
import java.util.List;
/**
* 用户业务逻辑层
* @author shangpange
*/
public interface UserService {
// 查询所有用户
public List<User> findAllUser();
// 用户注册
public Integer insertUser(User user);
// 用户登录
public User login(User user);
}
【4】业务层 service
包下的 service
实现类,继承service
接口:com.spg.service.impl.UserServiceImpl
package com.spg.service.impl;
import com.spg.domain.User;
import com.spg.service.UserService;
import java.util.List;
/**
* 用户业务逻辑实现类
* @author shangpange
*/
public class UserServiceImpl implements UserService {
@Override
public List<User> findAllUser() {
System.out.println("业务层:查询用户");
return null;
}
@Override
public Integer insertUser(User user) {
System.out.println("业务层:用户注册");
return null;
}
@Override
public User login(User user) {
System.out.println("业务层:用户登录");
return null;
}
}
【5】控制层 controller
包下的用户控制层UserController
类:com.spg.controller.UserController
package com.spg.controller;
/**
* 用户控制器
* @author shangpange
*/
public class UserController {
}
1.5 创建配置文件
在resources
文件夹下创建多个配置文件,主要有:
【1】spring相关配置:spring.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">
</beans>
【2】springmvc相关配置:spring-mvc.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">
</beans>
【3】mybatis相关配置:mybatis.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>
</configuration>
【4】日志相关配置: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
【5】目录结构如下图:
2. 编写Spring框架
2.1 配置注解扫描
在spring.xml
中配置注解扫描,加上以下配置:
<!--开启注解扫描,这里service和dao是需要扫描的,controller是不需要扫描的-->
<context:component-scan base-package="com.spg">
<!--配置要忽略的注解-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
2.2 为service实现类添加注解
在UserServiceImpl
类中添加注解,把service
交给IOC
容器管理
@Service("userService")
public class UserServiceImpl implements UserService {
@Override
public List<User> findAllUser() {
System.out.println("业务层:查询用户");
return null;
}
}
2.3 测试spring框架
这里只做用户查询测试,创建测试类:com.spg.test.SpringTest
package com.spg.test;
import com.spg.service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Spring测试类
* @author shangpange
*/
public class SpringTest {
@Test
public void TestFindAllUser(){
// 加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml");
// 获取对象
UserService userService = (UserService) ac.getBean("userService");
// 调用方法
userService.findAllUser();
}
}
运行,打印以下信息则搭建成功:
3. 编写Spring MVC框架
3.1 配置 web.xml
- 配置前端控制器
- 加载
spring-mvc.xml
配置文件 - 启动服务器,创建
Servlet
- 配置过滤器解决中文乱码
<!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>
<!--解决中文乱码的过滤器-->
<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>
<!--配置前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--加载spring-mvc.xml配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.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>
</web-app>
3.2 配置 spring-mvc.xml
- 开启注解扫描,只扫描
controller
- 配置视图解析器
- 过滤静态资源
- 开启
SpringMVC
注解支持
<!--开启注解扫描,只扫描Controller注解-->
<context:component-scan base-package="com.spg">
<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 location="/css/" mapping="/css/**" />
<mvc:resources location="/images/" mapping="/images/**" />
<mvc:resources location="/js/" mapping="/js/**" />
<!--开启SpringMVC注解的支持-->
<mvc:annotation-driven/>
3.3 测试SpringMVC
【1】编写UserController
用户控制层
package com.spg.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 用户控制器
* @author shangpange
*/
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/findAllUser")
public String findAllUser() {
System.out.println("表现层:查询用户");
return "user";
}
}
【2】编写index.jsp
页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>SSM</title>
</head>
<body>
<a href="/user/findAllUser">查询用户</a>
</body>
</html>
【3】编写跳转页面
在 WEB-INF
目录下新建 pages
目录,pages
目录下创建 user.jsp
页面,编写user.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>SSM</title>
</head>
<body>
<h3>查询所有用户!</h3>
</body>
</html>
【4】 部署Tomcat
项目并测试
测试结果:
4. Spring整合Spring MVC框架
使用spring
框架整合Spring MVC
框架,目的就是能够使用 controller
层方法调用 service
业务层方法,那要如何实现呢?分析如下:
- 浏览器发送请求,通过
web.xml
中配置的前端控制器加载springmvc.xml
配置文件。 - 在
springmvc.xml
配置文件中配置Spring
的监听器,默认只加载WEB-INF
目录下的spring.xml
配
置文件。 - 将
service
注入controller
,调用service
对象的方法进行测试。
4.1 配置web.xml
配置Spring
的监听器和文件路径
<!--配置Spring的监听器,默认只加载WEB-INF目录下的spring.xml配置文件-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--设置配置文件的路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
4.2 service注入controller
修改 UserController
类,将service
注入controller
,调用service
对象的方法进行测试,修改后如下:
package com.spg.controller;
import com.spg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 用户控制器
* @author shangpange
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findAllUser")
public String findAllUser() {
System.out.println("表现层:查询用户");
// 调用service对象的方法
userService.findAllUser();
return "user";
}
}
4.3 测试运行
点击测试查询链接后,在后台打印一下信息,说明spring
成功整合Spring MVC
5. 编写MyBatis框架
5.1 配置mybatis.xml配置文件
在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?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 引入映射配置文件 -->
<mappers>
<package name="com.spg.dao"/>
</mappers>
5.2 编写UserDao类
package com.spg.dao;
import com.spg.domain.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* 用户持久层接口
* @author shangpange
*/
public interface UserDao {
// 查询所有用户
@Select("select * from user")
public List<User> findAllUser();
// 用户注册
@Insert("insert into user (username, password) values (#{username}, #{password})")
public Integer insertUser(User user);
// 用户登录
@Select("select * from user where username = #{username} and password = #{password}")
public User login(User user);
}
5.3 编写测试类
这里测试用户查询和注册,创建测试类:com.spg.test.MyBatisTest
package com.spg.test;
import com.spg.dao.UserDao;
import com.spg.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* MyBatis测试类
* @author shangpange
*/
public class MyBatisTest {
/**
* 测试查询
* @throws IOException
*/
@Test
public void TestFindAllUser() throws IOException {
// 1. 加载配置文件
InputStream in = Resources.getResourceAsStream("mybatis.xml");
// 2. 创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 3. 创建SqlSession对象
SqlSession session = factory.openSession();
// 4. 获取代理对象
UserDao userDao = session.getMapper(UserDao.class);
// 5. 查询数据
List<User> userList = userDao.findAllUser();
for (User user : userList) {
System.out.println(user);
}
// 6. 关闭资源
session.close();
in.close();
}
/**
* 测试添加
* @throws IOException
*/
@Test
public void TestInsertUser() throws IOException {
User user = new User();
user.setUsername("jerry");
user.setPassword("jerry");
// 1. 加载配置文件
InputStream in = Resources.getResourceAsStream("mybatis.xml");
// 2. 创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 3. 创建SqlSession对象
SqlSession session = factory.openSession();
// 4. 获取代理对象
UserDao userDao = session.getMapper(UserDao.class);
// 5. 查询数据
Integer count = userDao.insertUser(user);
if(count > 0){
System.out.println("添加成功!");
} else {
System.out.println("添加失败!");
}
// 6. 提交事务
session.commit();
// 7. 关闭资源
session.close();
in.close();
}
}
测试查询用户和测试注册用户,能查询出用户数据和注册成功,说明mybatis
框架搭建成功。
6. Spring整合MyBatis框架
Spring
要想成功整合Mybatis
框架,就需要service
层成功调用dao
对象,然后进行相关数据库的增删改查操作。
- 将
dao
代理对象存到IOC
容器中 - 通过
service
注入dao
6.1 配置spring.xml
- 配置连接池
- 配置
SqlSessionFactory
工厂 - 配置
UserDao
接口所在包
<!--Spring整合MyBatis框架-->
<!--配置连接池-->
<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?serverTimezone=UTC"/>
<property name="user" value="root"/>
<property name="password" value="root"/>
</bean>
<!--配置SqlSessionFactory工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<!--配置UsersDao接口所在包-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.spg.dao"/>
</bean>
配置完成之后,就没 mybatis.xml
什么事了,可以删去
6.2 注入dao数据
修改Userdao
类,添加注解
@Repository
public interface UserDao {
6.3 在service注入dao
修改UserServiceImpl
类,修改后如下:
package com.spg.service.impl;
import com.spg.dao.UserDao;
import com.spg.domain.User;
import com.spg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 用户业务逻辑实现类
* @author shangpange
*/
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public List<User> findAllUser() {
System.out.println("业务层:查询用户");
return userDao.findAllUser();
}
@Override
public Integer insertUser(User user) {
System.out.println("业务层:用户注册");
return userDao.insertUser(user);
}
@Override
public boolean login(User user) {
System.out.println("业务层:用户登录");
if (userDao.login(user) != null){
return true;
} else {
return false;
}
}
}
6.4 测试用户查询、注册、登录
【1】修改UserController
类,将数据显示在页面上,修改后如下:
package com.spg.controller;
import com.spg.domain.User;
import com.spg.service.UserService;
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.List;
/**
* 用户控制器
* @author shangpange
*/
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 查询用户
* @param model
* @return
*/
@RequestMapping("/findAllUser")
public String findAllUser(Model model) {
System.out.println("表现层:查询用户");
// 调用 service 对象的方法
List<User> userList = userService.findAllUser();
model.addAttribute("userList", userList);
return "user";
}
/**
* 用户注册
* @param user
* @return
*/
@RequestMapping("/insertUser")
public String insert(User user){
System.out.println("表现层:用户注册");
// 调用 service 对象的方法
Integer count = userService.insertUser(user);
if(count > 0){
return "regist_success";
} else {
return "regist_failed";
}
}
/**
* 用户登录
* @param user
* @return
*/
@RequestMapping("/login")
public String login(User user){
System.out.println("表现层:用户登录");
// 调用 service 对象的方法
boolean isLogin = userService.login(user);
if(isLogin){
return "login_success";
} else {
return "login_failed";
}
}
}
【2】修改 index.jsp
页面,为 index.jsp
页面添加注册表单和登录表单
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>SSM</title>
</head>
<body>
<a href="/user/findAllUser">查询用户</a>
<hr>
<form method="post" action="/user/insertUser">
用户:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
<input type="submit" value="注册"><br>
</form>
<hr>
<form method="post" action="/user/login">
用户:<input type="text" name="username"><br>
密码:<input type="text" name="password"><br>
<input type="submit" value="登录"><br>
</form>
<hr>
</body>
</html>
【3】修改用户查询跳转页面user.jsp
,将查询数据显示在页面上
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>SSM</title>
</head>
<body>
<h3>查询所有用户!</h3>
${userList}
</body>
</html>
【4】创建注册成功提醒页面:regist_success.jsp
、regist_failed.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>SSM</title>
</head>
<body>
<h3>注册成功!</h3>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>SSM</title>
</head>
<body>
<h3>注册失败!</h3>
</body>
</html>
【5】创建登录成功和登录失败提醒页面:login_success.jsp
、login_failed.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>SSM</title>
</head>
<body>
<h3>登录成功!</h3>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>SSM</title>
</head>
<body>
<h3>登录失败!</h3>
</body>
</html>
【6】运行Tomcat
服务器,点击 “查询用户” 可以查询用户,输入用户名和密码可以进行登录和注册
7. SSM整合目录结构
下载地址:https://gitee.com/shangpange/ssm-demo