创建用户表t_user
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`password` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
`telephone` varchar(11) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL,
`register_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0),
`popedom` int(11) DEFAULT NULL COMMENT '0:管理员;1:普通用户',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 5 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
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');
单击【Finish】按钮
在pom.xml文件里添加相关依赖
<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.0modelVersion>
<groupId>net.hf.ssmgroupId>
<artifactId>SSMLoginartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<spring.version>5.3.25spring.version>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-coreartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-beansartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.49version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.24version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.5version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.5version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13version>
<scope>testscope>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
dependencies>
project>
日志属性文件 - 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/spring.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%d %p [%c] - %m%n
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/simonshop?useSSL=false&useUnicode=true&characterEncoding=utf8
jdbc.username = root
jdbc.password = root
注意:数据库密码要改成你自己的
打开项目结构窗口,切换到Modules,添加Web功能
单击【Create Artifact】按钮,单击【Create Artifact】按钮
将项目依赖添加到输出目录
单击【OK】按钮
单击工具栏上的【Edit Configurations…】,打开【运行/调试配置】窗口
添加本地的Tomcat服务器
选择Local
修改名称,启动的浏览器
单击【Fix】按钮
切换到【Server】选项卡
单击【OK】按钮
创建net.hf.ssm.bean包,在包里创建User类
package net.hf.ssm.bean;
import java.util.Date;
/**
* 功能:用户实体类
* 作者:hf
* 日期:2023年04月18日
*/
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.hf.ssm.mapper包,在包里创建UserMapper接口
package net.hf.ssm.mapper;
import net.hf.ssm.bean.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* 功能:用户映射器接口
* 作者:hf
* 日期:2023年04月19日
*/
@Mapper // 映射器注解,纳入Spring容器管理
public interface UserMapper {
// 登录方法(注解参数名对应映射语句的参数#{username}, #{password}
User login(@Param("username") String username, @Param("password") String password);
}
10、创建用户服务类
在net.hf.ssm包里创建service子包,然后在子包里创建UserService类
package net.hf.ssm.service;
import net.hf.ssm.bean.User;
import net.hf.ssm.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* 功能:用户服务类
* 作者:hf
* 日期:2023年04月19日
*/
@Service // 服务注解,纳入Spring容器管理
public class UserService {
@Autowired // 自动装配,依赖注入
private UserMapper userMapper;
public User login(String username, String password) {
return userMapper.login(username, password);
}
}
在net.hf.ssm包里创建controller子包,然后在子包里创建UserController类
package net.hf.ssm.controller;
import net.hf.ssm.bean.User;
import net.hf.ssm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpSession;
/**
* 功能:用户控制器
* 作者:hf
* 日期:2023年04月19日
*/
@Controller // 控制器注解,纳入Spring容器管理
@RequestMapping("/user") // 请求根路径
public class UserController {
@Autowired // 自动装配,依赖注入
private UserService userService;
@RequestMapping("/login") // 请求子路径(请求完整路径:/user/login)
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
HttpSession session) {
// 调用用户服务对象的登录方法得到登录用户对象
User user = userService.login(username, password);
// 判断用户是否登录成功,看返回的用户对象是否为空
if (user != null) { // 登录成功
// 将成功登录用户名写入会话
session.setAttribute("user", user);
// 删除会话里可能存在的登录错误提示信息
if (session.getAttribute("loginMsg") != null) {
session.removeAttribute("loginMsg");
}
// 根据用户角色,跳转到不同页面
if (user.getPopedom() == 0) { // 管理员
// 返回后台管理页面逻辑视图名,跳转到后台管理页面
return "backend/management";
} else { // 普通用户
// 返回前端首页逻辑视图名,跳转到前端首页
return "frontend/index";
}
} else { // 登录失败
// 将登录错误信息写入会话
session.setAttribute("loginMsg", "温馨提示:用户名或密码错误~");
// 返回前端登录页面逻辑视图名,跳转到登录页面
return "frontend/login";
}
}
@RequestMapping("/logout") // 请求子路径(请求完整路径:/user/login)
public String logout(HttpSession session) {
// 删除会话里保存的用户名信息
session.removeAttribute("user");
// 结束会话(调用会话失效方法)
session.invalidate();
// 返回前端登录页面逻辑视图名,跳转到登录页面
return "frontend/login";
}
}
在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.hf.ssm.mapper.UserMapper">
<!--定义结果映射,因为表字段名与实体属性名不完全一致-->
<resultMap id="userMap" type="net.hf.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>
对应关系图
在resources里创建config子目录,然后在子目录里创建spring-config.xml
<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
https://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="net.hf.ssm"/>
<context:property-placeholder location="classpath:jdbc.properties"/>
<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>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mapper/UserMapper.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="net.hf.ssm.mapper"/>
bean>
beans>
说明:本案例没有对数据库进行更新操作,因此没有引入事务管理
如果项目里对数据库有更新操作,那么UserService应该添加@Transactional注解,而且Spring配置文件里还要添加事务管理
<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>
<aop:config>
<aop:pointcut id="mypt" expression="execution(public * net.hf.shop.service..*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="mypt"/>
aop:config>
在resources/config目录里创建spring-mvc-config.xml
<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/images/"/>
<mvc:annotation-driven/>
<mvc:view-controller path="user/login" view-name="frontend/login" />
<context:component-scan base-package="net.hf.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"/>
<context:component-scan base-package="net.hf.ssm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
context:component-scan>
beans>
因为在WEB-INF里尚未创建静态资源目录,处理静态资源的元素以及视图控制器的元素会报错
Web部署描述文件 - web.xml
<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>ssmlogindisplay-name>
<welcome-file-list>
<welcome-file>/WEB-INF/views/frontend/login.jspwelcome-file>
welcome-file-list>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:config/spring-config.xmlparam-value>
context-param>
<servlet>
<servlet-name>DispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:config/spring-mvc-config.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>DispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>Character Encodingfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>Character Encodingfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
在WEB-INF里创建images目录,用来存放图片资源 - xiao.jpg
在spring-mvc-config.xml文件里关于图像真实路径就没有报错了。
在WEB-INF里创建css子目录,然后在子目录里创建login.css
/* 样式 */
body {
margin: 0px;
text-align: center;
background: #cccccc;
}
在WEB-INF里创建js子目录,然后在子目录里创建check.js
/**
* 检验登录表单
*
* @returns {Boolean}
*/
function checkLoginForm() {
// 获取用户名文本框
var username = document.getElementById("username");
// 获取密码文本框
var password = document.getElementById("password");
// 非空校验
if (username.value == "") {
alert("用户名不能为空!");
// 让用户名文本框获得焦点
username.focus();
return false;
}
if (password.value == "") {
alert("密码不能为空!");
// 让密码文本框获得焦点
password.focus();
return false;
}
return true; // 表明可以提交数据到服务器端
}
在WEB-INF里创建views目录,在views里创建frontend与backend两个目录
在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非空,登录页面就会一个消息框,告知用户登录失败的消息:温馨提示:用户名或密码错误~
在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/xiao.jpg" width="300" height="250">
</body>
</html>
在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>
<h3>西蒙购物网后台管理</h3>
管理员:${user.username} —— <a href="user/logout">注销</a><br/>
<img src="images/xiao.jpg" width="300" height="250">
</body>
</html>