一.基于XML配置方式整合SSM框架实现用户登录
(一)创建数据库与表
1、创建数据库
- 数据库simonshop,采用utf8mb4编码
- 单击【确定】按钮
2、创建用户表
- 创建用户表t_user
3、在用户表里插入记录
- 插入4条记录
INSERT INTO `t_user` VALUES ('1', 'admin', '12345', '15734345678', '2021-12-02 08:40:35', '0');
INSERT INTO `t_user` VALUES ('2', '郑晓红', '11111', '13956567889', '2022-12-20 09:51:43', '1');
INSERT INTO `t_user` VALUES ('3', '温志军', '22222', '13956678907', '2022-12-20 09:52:36', '1');
INSERT INTO `t_user` VALUES ('4', '涂文艳', '33333', '15890905678', '2022-12-05 09:52:56', '1');
(二)创建Maven项目
- 创建Maven项目 - SSMLogin
- 单击【create】按钮
(三)项目添加相关依赖
<?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>net.huawei.ssm</groupId>
<artifactId>SSMLogin</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<!-- spring.version -->
<spring.version>5.3.25</spring.version>
</properties>
<dependencies>
<!--Spring核心-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring Bean-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring容器-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring测试-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring数据库支持-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--数据库驱动工具包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.49</version>
</dependency>
<!--数据库连接池框架-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.24</version>
</dependency>
<!--持久层框架-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!--提供MyBatis与Spring整合的支持-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
<!--日志框架-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<!--Spring Web-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!--Spring MVC-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--JSP标准标签库-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
- 刷新项目Maven依赖
(四)创建日志属性文件
- 日志属性文件 - log4j.properties
log4j.rootLogger=WARN, stdout, logfile
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - %m%n
log4j.appender.logfile=org.apache.log4j.FileAppender
log4j.appender.logfile.File=target/ssm.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
(五)创建数据库属性文件
- 数据库属性文件 - jdbc.properties
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/simonshop?useSSL=false
jdbc.username = root
jdbc.password = root
(六)给项目添加Web功能
- 打开项目结构窗口,切换到Modules
- 添加Web功能
- 单击【Create Artifact】按钮
- 修改Artifact名称 - SSMLogin
- 将项目依赖添加到输出目录
- 单击【Put into /WEB-INF/lib】命令
- 单击【OK】按钮
(七)配置Tomcat服务器
- 单击工具栏上的【Add Configuration…】,打开【运行/调试配置】窗口
- 添加本地的Tomcat服务器、
- 单击【Configure…】按钮
- 单击【OK】按钮
- 修改名称,启动的浏览器
- 单击【Fix】按钮
- 切换到【Server】选项卡
- 单击【OK】按钮
(八)创建用户实体类
- 创建net.wtt.ssm.bean包,在包里创建User类
package net.wtt.ssm.bean;
import java.util.Date;
public class User {
private int id;
private String username;
private String password;
private String telephone;
private Date registerTime;
private int popedom;
public int getId() {
return id;
}
public void setId(int 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;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Date getRegisterTime() {
return registerTime;
}
public void setRegisterTime(Date registerTime) {
this.registerTime = registerTime;
}
public int getPopedom() {
return popedom;
}
public void setPopedom(int popedom) {
this.popedom = popedom;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", telephone='" + telephone + '\'' +
", registerTime=" + registerTime +
", popedom=" + popedom +
'}';
}
}
(九)创建用户映射器接口
- 创建net.wtt.ssm.mapper包,在包里创建UserMapper接口
package net.wtt.ssm.mapper;
import net.wtt.ssm.bean.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
@Mapper
public interface UserMapper {
User login(@Param("username") String username, @Param("password") String password);
}
(十)创建用户服务类
- 在net.wtt.ssm包里创建service子包,然后在子包里创建UserService类
package net.wtt.ssm.service;
import net.wtt.ssm.bean.User;
import net.wtt.ssm.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User login(String username, String password) {
return userMapper.login(username, password);
}
}
(十一)创建用户控制器
- 在net.wtt.ssm包里创建controller子包,然后在子包里创建UserController类
package net.wtt.ssm.service;
import net.wtt.ssm.bean.User;
import net.wtt.ssm.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User login(String username,String password){
return userMapper.login(username,password);
}
}
(十二)项目配置文件
1、创建用户映射器配置文件
- 在resources里创建mapper子目录,然后在子目录里创建UserMapper.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="net.wtt.ssm.mapper.UserMapper">
<!--定义结果映射,因为表字段名与实体属性名不完全一致-->
<resultMap id="userMap" type="net.wtt.ssm.bean.User">
<result property="id" column="id"/>
<result property="username" column="username"/>
<result property="password" column="password"/>
<result property="telephone" column="telephone"/>
<result property="registerTime" javaType="java.util.Date" column="register_time" jdbcType="TIMESTAMP"/>
<result property="popedom" column="popedom"/>
</resultMap>
<!--定义登录映射语句-->
<select id="login" resultMap="userMap">
SELECT * FROM t_user WHERE username = #{username} AND password = #{password};
</select>
</mapper>
2、创建Spring配置文件
- 在resources里创建config子目录,然后在子目录里创建spring-config.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"
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
https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--组件扫描-->
<context:component-scan base-package="net.wtt.ssm"/>
<!--读取数据库属性文件,供创建数据源使用-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--配置数据源Bean,采用阿里的Druid数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<!--配置数据源基本属性-->
<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>
<!--配置MyBatis的SQL会话工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--配置数据源,指定操作对象-->
<property name="dataSource" ref="dataSource"/>
<!--配置映射器配置,负责操作方法-->
<property name="mapperLocations" value="classpath:mapper/UserMapper.xml"/>
</bean>
<!--配置MyBatis映射扫描配置器-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--绑定SQL会话工厂-->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!--配置映射器接口要扫描的根包-->
<property name="basePackage" value="net.wtt.ssm.mapper"/>
</bean>
<!--定义事务管理器-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 事务注解驱动,标注@Transactional的类和方法将具有事务性 -->
<tx:annotation-driven transaction-manager="txManager" />
<!--定义事务管理通知-->
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="find*" read-only="true"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
<!--声明式事务通知器,需要在pom.xml里添加基于AspectJ的AOP支持-->
<aop:config>
<aop:pointcut id="mypt" expression="execution(public * net.wtt.ssm.service..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="mypt"/>
</aop:config>
</beans>
- 说明:本案例没有对数据库进行更新操作,因此没有引入事务管理
- 如果项目里对数据库有更新操作,那么UserService应该添加@Transactional注解,而且Spring配置文件里还要添加事务管理
3、创建Spring MVC配置文件
- 在resources/config目录里创建spring-mvc-config.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:p="http://www.springframework.org/schema/p"
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">
<!--处理对静态资源的请求-->
<mvc:resources mapping="/css/**" location="/WEB-INF/css/"/>
<mvc:resources mapping="/js/**" location="/WEB-INF/js/"/>
<mvc:resources mapping="/images/**" location="/WEB-INF/img/"/>
<!--采用注解驱动-->
<mvc:annotation-driven/>
<!--定义视图控制器-->
<mvc:view-controller path="user/login" view-name="frontend/login" />
<!--扫描添加Controller注解的类-->
<context:component-scan base-package="net.wtt.ssm.controller"/>
<!--定义内部资源视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/WEB-INF/views/"
p:suffix=".jsp"/>
<!-- 扫描业务组件,让spring不扫描带有@Service注解的类(留在spring-config.xml中扫描@Service注解的类),防止事务失效 -->
<context:component-scan base-package="net.wtt.ssm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
</context:component-scan>
</beans>
- 因为在WEB-INF里尚未创建静态资源目录,处理静态资源的元素以及视图控制器的元素会报错
4、编辑Web部署描述文件
- 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_4_0.xsd"
version="4.0">
<display-name>simonshop</display-name>
<welcome-file-list>
<welcome-file>/WEB-INF/views/frontend/login.jsp</welcome-file>
</welcome-file-list>
<!--Spring监听器,让Spring随Web项目启动而初始化-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定Spring配置文件位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/spring-config.xml</param-value>
</context-param>
<!--配置Spring前端控制器,通过初始化参数设置读取控制器配置文件-->
<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:config/spring-mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--设置字符编码过滤器-->
<filter>
<filter-name>Character Encoding</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>Character Encoding</filter-name>
<url-pattern>
(十三)准备静态资源
1、准备图片资源
- 在WEB-INF里创建images目录,用来存放图片资源 - bear.png
2、创建样式文件
- 在WEB-INF里创建css子目录,然后在子目录里创建login.css
3、创建脚本文件
- 在WEB-INF里创建js子目录,然后在子目录里创建check.js
(十四)创建页面
1、创建目录结构
- 在WEB-INF里创建views目录,在views里创建frontend与backend两个目录
2、创建登录页面
- 在views/frontend里创建login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<html>
<head>
<title>用户登录</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" >
<base href="${basePath}">
<script src="js/check.js"></script>
<link href="css/login.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<h3 style="text-align: center">用户登录</h3>
<form id="frmLogin" action="user/login" method="post">
<table class="tb" border="1" cellpadding="10" style="margin: 0px auto">
<tr>
<td align="center">账号</td>
<td><input id="username" type="text" name="username"/></td>
</tr>
<tr>
<td align="center">密码</td>
<td><input id="password" type="password" name="password"/></td>
</tr>
<tr align="center">
<td colspan="2">
<input type="submit" value="登录" onclick="return checkLoginForm()"/>
<input type="reset" value="重置"/>
</td>
</tr>
</table>
</form>
<c:if test="${loginMsg!=null}">
<script type="text/javascript">alert("${loginMsg}")</script>
<c:remove var="loginMsg"/>
</c:if>
</body>
</html>
- 代码说明:基路径basePath,针对我们这个项目,其实就是http://localhost:8080/SSMLogin
- 如果loginMsg非空,登录页面就会一个消息框,告知用户登录失败的消息:温馨提示:用户名或密码错误~
3、创建网站首页
- 在views/frontend里创建index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<html>
<head>
<title>首页</title>
<base href="${basePath}">
</head>
<body style="text-align: center; background: antiquewhite">
<h3>欢迎访问西蒙购物网</h3>
登录用户:${user.username} —— <a href="user/logout">注销</a><br/>
<img src="images/bear.png" width="300" height="250">
</body>
</html>
4、创建后台管理页面
- 在views/backend里创建management.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>
<c:set var="basePath"
value="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${path}/"/>
<html>
<head>
<title>后台管理</title>
<base href="${basePath}">
</head>
<body style="text-align: center; background: pink">
<h3>西蒙购物网后台管理</h3>
管理员:${user.username} —— <a href="user/logout">注销</a><br/>
<img src="images/bear.png" width="300" height="250">
</body>
</html>
(十五)启动服务器,查看效果
- 启动服务器,首先看到的是登录页面,大家可以看到登录样式表是起了作用的
- 检查脚本(非空校验)是否起作用
不输入用户名和密码,单击【登录】按钮
- 输入用户名,单击【登录】按钮
- 输入错误的密码,单击【登录】按钮
- 单击【确定】按钮,输入正确的管理员用户名和密码
- 单击【注销】超链接
- 下面,我们以普通用户来登录(输入正确的用户名和密码:郑晓红 - 11111)
- 单击【登录】按钮