大家好,又见面了,我是你们的朋友全栈君。
目录
【1】创建存放 javabean 类文件:cn.star.domain.Users
【2】创建数据访问层 UsersDao 接口:cn.star.dao.UsersDao
【3】创建业务层 UsersService 接口:cn.star.service.UsersService
【4】Service 实现类:cn.star.service.impl.UsersServiceImpl
【5】创建用户控制层UsersController类:cn.star.controller.UsersController
零、前言
当下 Spring 全家桶如日中天,Spring 系列框架已然成为 Java 后端开发的必备知识,接触了 Spring、Spring MVC、Mybatis 框架后,是不是想尝试将他们整合一下呢,虽然说 SSM 框架比不上 Spring boot 的简便高效(Springboot整合请看:使用IDEA搭建SpringBoot框架整合Mybatis、MySQL、Thymeleaf实现用户查询、注册、登录),但 SSM 还是在很多公司中使用,况且整合 SSM 框架对于学习理解 Spring 还是有一定帮助的,博主萌新,大佬轻拍|=_=|话不多说,开拔!
一、说明
1、整合说明
- 服务器开发分为三层,表现层、业务层、持久层
- 表现层使用SpringMVC实现,业务程使用Spring实现,持久层使用Mybatis实现
- 使用Spring框架来整合 SpringMVC和Mybatis框架
- 这里使用xml配置文件+注解的方式进行搭建
2、最终目标
- 最终实现通过前端页面对数据库进行查询和插入,实现用户的登录注册功能
3、数据库准备
CREATE DATABASE myssm;
USE myssm;
CREATE TABLE users(
id INT PRIMARY KEY AUTO_INCREMENT COMMENT ‘id主键’,
username VARCHAR(20) NOT NULL COMMENT ‘用户名’,
PASSWORD VARCHAR(20) NOT NULL COMMENT’用户密码’
);INSERT INTO users (username,PASSWORD) VALUES(“onestar”,”123″);
INSERT INTO users (username,PASSWORD) VALUES(“twostar”,”456″);
二、搭建整合环境
1、创建 maven 工程
【1】点击:文件—>模块,选择 Maven,勾选 Create from achetype,选择webapp,如下图,点击写一个
【2】创建模块名
【3】选择maven配置(已选可不用管),点击下一个
【4】给项目命名并保存到相应路径下,点击完成
创建好后目录结构如下:
2、导入依赖坐标
在pom.xml里面导入坐标,我的pom文件内容如下:
<?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>cn.star</groupId>
<artifactId>myssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>myssm 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>5.1.6</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>myssm</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>
3、创建java和resources文件夹
在main目录下面创建java和resources文件夹,并设置相应文件
4、创建类和接口文件
在java文件夹下创建类文件,所需的类文件有以下几个:
- 存放javabean的 domain 包下的用户类:cn.star.domain.Users
- 数据访问层 dao 包下的用户 dao 接口:cn.star.dao.UsersDao
- 业务层 service 包下的 UsersService 接口:cn.star.service.UsersService
- 业务层 service 包下的 service 实现类,继承service接口:cn.star.service.impl.UsersServiceImpl
- 控制层 controller 包下的用户控制层UsersController类:cn.star.controller.UsersController
【1】创建存放 javabean 类文件:cn.star.domain.Users
package cn.star.domain;
import java.io.Serializable;
/**
* 〈一句话功能简述〉<br>
* 〈用户类〉
*
* @author OneStar
* @create 2019/11/8
* @since 1.0.0
*/
public class Users implements Serializable {
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 "Users{" +
"id=" + id +
", username='" + username + '\'' +
", PASSWORD='" + PASSWORD + '\'' +
'}';
}
}
【2】创建数据访问层 UsersDao 接口:cn.star.dao.UsersDao
这里只需要编写接口就可以了,框架会帮我们生成一个代理对象
package cn.star.dao;
import cn.star.domain.Users;
import java.util.List;
/**
* 〈一句话功能简述〉<br>
* 〈数据访问层 UsersDao 接口〉
*
* @author OneStar
* @create 2019/11/8
* @since 1.0.0
*/
public interface UsersDao {
//查询所有用户
public List<Users> findUsers();
//用户注册
public void insertUsers(Users users);
//用户登录
public Users login(Users users);
}
【3】创建业务层 UsersService 接口:cn.star.service.UsersService
package cn.star.service;
import cn.star.domain.Users;
import java.util.List;
/**
* 〈一句话功能简述〉<br>
* 〈业务层接口〉
*
* @author OneStar
* @create 2019/11/9
* @since 1.0.0
*/
public interface UsersService {
//查询所有用户
public List<Users> findUsers();
//用户注册
public void insertUsers(Users users);
//用户登录
public boolean login(Users users);
}
【4】Service 实现类:cn.star.service.impl.UsersServiceImpl
继承 UsersService 接口
package cn.star.service.impl;
import cn.star.domain.Users;
import cn.star.service.UsersService;
import java.util.List;
/**
* 〈一句话功能简述〉<br>
* 〈Service 实现类〉
*
* @author OneStar
* @create 2019/11/9
* @since 1.0.0
*/
public class UsersServiceImpl implements UsersService {
@Override
public List<Users> findUsers() {
System.out.println("业务层:查询用户");
return null;
}
@Override
public void insertUsers(Users users) {
System.out.println("业务层:用户注册");
}
@Override
public boolean login(Users users) {
System.out.println("业务层:用户登录");
}
}
【5】创建用户控制层UsersController类:cn.star.controller.UsersController
5、创建配置文件
在resources文件夹下创建多个配置文件,主要有:
- spring相关配置:spring.xml
- springmvc相关配置:spring-mvc.xml
- mybatis相关配置:mybatis.xml
- 日志相关配置:log4j.properties
【1】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】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.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】目录结构
至此,整个目录结构如下
三、整合框架编写
1、编写spring框架
【1】配置注解扫描
在spring.xml中配置注解扫描,加上以下配置:
<!--开启注解扫描,这里service和dao是需要扫描的,controller是不需要扫描的-->
<context:component-scan base-package="cn.star">
<!--配置要忽略的注解-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
【2】为service实现类添加注解
在UsersServiceImpl类中添加注解,把service交给IOC容器管理
@Service("usersService")
public class UsersServiceImpl implements UsersService {...}
【3】测试spring框架
这里只做用户查询测试,创建测试类:cn.star.test.springtest
package cn.star.test;
import cn.star.service.UsersService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* 〈一句话功能简述〉<br>
* 〈测试类〉
*
* @author OneStar
* @create 2019/11/11
* @since 1.0.0
*/
public class springtest {
@Test
public void Test(){
//加载配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml");
//获取对象
UsersService us = (UsersService) ac.getBean("usersService");
//调用方法
us.findUsers();
}
}
运行,打印以下信息则搭建成功:
2、编写 SpringMVC 框架
【1】配置 web.xml
- 配置前端控制器
- 加载spring-mvc.xml配置文件
- 启动服务器,创建Servlet
- 配置过滤器解决中文乱码
<!--配置前端控制器-->
<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>
<!--解决中文乱码的过滤器-->
<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>
【2】配置 spring-mvc.xml
- 开启注解扫描,只扫描 controller
- 配置视图解析器
- 过滤静态资源
- 开启SpringMVC注解支持
<!--开启注解扫描,只扫描Controller注解-->
<context:component-scan base-package="cn.star">
<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】测试SpringMVC
- 编写用户控制层
- 编写index.jsp页面
- 编写跳转页面
1. 编写UsersController用户控制层
package cn.star.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 〈一句话功能简述〉<br>
* 〈用户控制层〉
*
* @author OneStar
* @create 2019/11/9
* @since 1.0.0
*/
@Controller
@RequestMapping("/users")
public class UsersController {
@RequestMapping("/findUsers")
public String findUsers(){
System.out.println("表现层:查询用户");
return "Users";
}
}
2. 编写index.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="users/findUsers">查询用户</a>
</body>
</html>
3. 编写跳转页面
在 WEB-INF 目录下新建 pages 目录,pages 目录下创建 Users.jsp 页面,编写 Users.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>查询所有用户</h3>
</body>
</html>
4. 部署Tomcat项目并测试
部署好后运行,点击测试查询链接,跳转到查询用户界面,SpringMVC配置成功
3、Spring 整合 SpringMVC 框架
使用spring框架整合springmvc框架,目的就是能够使用 controller 层方法调用 service 业务层方法,那要如何实现呢?分析如下:
- 浏览器发送请求,通过web.xml中配置的前端控制器加载springmvc.xml配置文件
- 在springmvc.xml配置文件中配置Spring的监听器,默认只加载WEB-INF目录下的spring.xml配置文件
- 将service注入controller,调用service对象的方法进行测试
【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>
【2】service注入controller
修改 UsersController 类,将service注入controller,调用service对象的方法进行测试,修改后如下:
package cn.star.controller;
import cn.star.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* 〈一句话功能简述〉<br>
* 〈用户控制层〉
*
* @author OneStar
* @create 2019/11/9
* @since 1.0.0
*/
@Controller
@RequestMapping("/users")
public class UsersController {
@Autowired
private UsersService usersService;
@RequestMapping("/findUsers")
public String findUsers(){
System.out.println("表现层:查询用户");
//调用service对象的方法进行测试
usersService.findUsers();
return "Users";
}
}
【3】测试运行
点击测试查询链接后,在后台打印一下信息,说明spring成功整合springmvc
4、编写 mybatis 框架
【1】配置mybatis.xml配置文件
在configuration标签内添加以下配置:
<!-- 配置环境 -->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///myssm"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<!-- 引入映射配置文件 -->
<mappers>
<package name="cn.star.dao"/>
</mappers>
【2】编写UserDao类
public interface UsersDao {
//查询所有用户
@Select("select * from users")
public List<Users> findUsers();
//用户注册
@Insert("INSERT INTO USERS (username,PASSWORD) VALUES(#{username},#{PASSWORD})")
public void insertUsers(Users users);
//用户登录
@Select("select * from users where username=#{username} and PASSWORD=#{PASSWORD}")
public Users login(Users users);
}
【3】编写测试类
这里测试用户查询和注册,创建测试类:cn.star.test.mybatistest
package cn.star.test;
import cn.star.dao.UsersDao;
import cn.star.domain.Users;
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.InputStream;
import java.util.List;
/**
* 〈一句话功能简述〉<br>
* 〈mybatis测试类〉
*
* @author OneStar
* @create 2019/11/11
* @since 1.0.0
*/
public class mybatistest {
/**
* 测试查询用户
* @throws Exception
*/
@Test
public void run1() throws Exception {
// 加载配置文件
InputStream in = Resources.getResourceAsStream("mybatis.xml");
// 创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 创建SqlSession对象
SqlSession session = factory.openSession();
// 获取到代理对象
UsersDao dao = session.getMapper(UsersDao.class);
// 查询所有数据
List<Users> list = dao.findUsers();
for(Users users : list){
System.out.println(users);
}
// 关闭资源
session.close();
in.close();
}
/**
* 测试注册
* @throws Exception
*/
@Test
public void run2() throws Exception {
Users users = new Users();
users.setUsername("threestar");
users.setPASSWORD("789");
// 加载配置文件
InputStream in = Resources.getResourceAsStream("mybatis.xml");
// 创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 创建SqlSession对象
SqlSession session = factory.openSession();
// 获取到代理对象
UsersDao dao = session.getMapper(UsersDao.class);
// 保存
dao.insertUsers(users);
// 提交事务
session.commit();
// 关闭资源
session.close();
in.close();
}
}
测试查询用户和测试注册用户,能查询出用户数据和注册成功,mybatis框架搭建成功
5、Spring整合Mybatis框架
Spring要想成功整合Mybatis框架,就需要service层成功调用dao对象,然后进行相关数据库的增删改查操作
- 将dao代理对象存到IOC容器中
- 通过service注入dao
【1】配置spring.xml
- 配置连接池
- 配置SqlSessionFactory工厂
- 配置UsersDao接口所在包
<!--Spring整合MyBatis框架-->
<!--配置连接池-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql:///myssm"/>
<property name="user" value="root"/>
<property name="password" value="123456"/>
</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="cn.star.dao"/>
</bean>
配置好后,就没 mybatis.xml 什么事了,可以删去
【2】注入dao数据
修改Usersdao类,添加注解
@Repository
public interface UsersDao {...}
【3】在service注入dao
修改UsersServiceImpl类,修改后如下:
package cn.star.service.impl;
import cn.star.dao.UsersDao;
import cn.star.domain.Users;
import cn.star.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 〈一句话功能简述〉<br>
* 〈Service 实现类〉
*
* @author OneStar
* @create 2019/11/9
* @since 1.0.0
*/
@Service("usersService")
public class UsersServiceImpl implements UsersService {
@Autowired
private UsersDao usersDao;
@Override
public List<Users> findUsers() {
System.out.println("业务层:查询用户");
return usersDao.findUsers();
}
@Override
public void insertUsers(Users users) {
System.out.println("业务层:用户注册");
usersDao.insertUsers(users);
}
@Override
public boolean login(Users users) {
System.out.println("业务层:用户登录");
if(usersDao.login(users) == null){
return false;
}else{
return true;
}
}
}
【4】测试用户查询、注册、登录
1、修改UsersController类,将数据显示在页面上,修改后如下:
package cn.star.controller;
import cn.star.domain.Users;
import cn.star.service.UsersService;
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;
/**
* 〈一句话功能简述〉<br>
* 〈用户控制层〉
*
* @author OneStar
* @create 2019/11/9
* @since 1.0.0
*/
@Controller
@RequestMapping("/users")
public class UsersController {
@Autowired
private UsersService usersService;
/**
* 查询用户
* @param model
* @return
*/
@RequestMapping("/findUsers")
public String findUsers(Model model){
System.out.println("表现层:查询用户");
//调用service对象的方法进行测试
List<Users> list = usersService.findUsers();
model.addAttribute("list",list);
return "Users";
}
/**
* 用户注册
* @param users
* @return
*/
@RequestMapping("/insert")
public String insert(Users users) {
System.out.println("注册");
// 调用注入的 usersService 调用 insertUsers 方法
usersService.insertUsers(users);
return "success";
}
/**
* 用户登录
* @param users
* @return
*/
@RequestMapping("/login")
public String login(Users users) {
System.out.println("登录");
// 调用注入的 usersService 调用 login 方法
if(usersService.login(users)){
return "successlogin";
}else{
return "falselogin";
}
}
}
2、修改 index.jsp 页面,为 index.jsp 页面添加注册表单和登录表单
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="users/findUsers">测试查询</a>
<hr>
<form method="post" action="/users/insert">
用户:<input type="text" name="username"><br>
密码:<input type="text" name="PASSWORD"><br>
<input type="submit" value="注册"><br>
</form>
<hr>
<form method="post" action="/users/login">
用户:<input type="text" name="username"><br>
密码:<input type="text" name="PASSWORD"><br>
<input type="submit" value="登录"><br>
</form>
<hr>
</body>
</html>
3、修改用户查询跳转页面Users.jsp,将查询数据显示在页面上
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>查询所有用户</h3>
${list}
</body>
</html>
4、创建注册成功提醒页面:success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>注册成功</h1>
</body>
</html>
5、创建登录成功和登录失败提醒页面:successlogin.jsp、falselogin.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>登录成功</h1>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>登录失败</h1>
</body>
</html>
6、运行Tomcat服务器,点击“测试查询”可以查询用户,输入用户名和密码可以进行登录和注册
四、源码
至此,SSM框架实现用户查询、注册、登录——IDEA整合Spring、Spring MVC、Mybatis 框架搭建完成,这个框架目录结构如下:
能看到这里,实属不易,不如点赞收藏+关注<(▰˘◡˘▰)
源码地址:
链接:https://pan.baidu.com/s/1-nERI56kzOGmkd8uVjhhrg
提取码:mh4m
啥?没网盘?那就留下邮箱,小弟亲自奉上٩(๑❛︶❛๑)۶
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/159289.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...