文章目录
零、本节学习目标 一、采用MVC架构 二、用户登录运行效果 三、基于XML配置方式整合SSM框架实现用户登录 (一)创建数据库与表 1、创建数据库 2、创建用户表 3、在用户表里插入记录
(二)创建Maven项目 (三)项目添加相关依赖 (四)创建日志属性文件 (五)创建数据库属性文件 (六)给项目添加Web功能 (七)配置Tomcat服务器 (八)创建用户实体类 更新到此 (九)创建用户映射器接口 - UserMapper (十)创建用户服务类 - UserService (十一)创建用户控制器 - UserController (十二)创建用户映射器配置文件 - UserMapper.xml (十三)创建Spring配置文件 - spring-config.xml (十四)创建Spring MVC配置文件 - spring-mvc-config.xml (十五)编辑Web部署描述文件 - web.xml (十六)准备图片资源 (十七)创建样式文件 - login.css (十八)创建脚本文件 - check.js (十九)创建页面 1、创建目录结构 2、创建登录页面 - login.jsp 3、创建网站首页 - index.jsp 4、创建后台管理页面 - management.jsp
(二十)启动服务器,查看效果
四、课后作业 任务1、完成用户注册功能 任务2、实现二维码制作功能
零、本节学习目标
理解MVC架构 掌握基于配置文件方式整合SSM框架 利用SSM框架实现用户登录功能
一、采用MVC架构
M(Model):模型层 V(View):视图层 C(Controller):控制层 MVC开始是存在于桌面程序中的,M是指业务模型,V是指用户界面,C则是控制器,使用MVC的目的是将M和V的实现代码分离,从而使同一个程序可以使用不同的表现形式。比如一批统计数据可以分别用柱状图、饼图来表示。C存在的目的则是确保M和V的同步,一旦M改变,V应该同步更新。 模型-视图-控制器(MVC)是Xerox PARC在二十世纪八十年代为编程语言Smalltalk-80发明的一种软件设计模式,已被广泛使用。后来被推荐为Oracle旗下Sun公司Java EE平台的设计模式,并且受到越来越多的使用ColdFusion和PHP的开发者的欢迎。模型-视图-控制器模式是一个有用的工具箱,它有很多好处,但也有一些缺点。
展现层
⟹
\Longrightarrow
⟹ 控制层
⟹
\Longrightarrow
⟹ 业务层
⟹
\Longrightarrow
⟹ 映射层
⟹
\Longrightarrow
⟹ 数据库
二、用户登录运行效果
从首页跳转到登录页面
三、基于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
单击【Finish】按钮
(三)项目添加相关依赖
在pom.xml
文件里添加相关依赖
<?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> 5.3.25</ spring.version>
</ properties>
< dependencies>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-core</ artifactId>
< version> ${spring.version}</ version>
</ dependency>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-beans</ 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-test</ artifactId>
< version> ${spring.version}</ version>
</ dependency>
< 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>
< 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>
< 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> javax.servlet</ groupId>
< artifactId> jstl</ artifactId>
< version> 1.2</ version>
</ dependency>
< 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 & useUnicode= true & characterEncoding= utf8
jdbc. username = root
jdbc. password = 903213
(六)给项目添加Web功能
打开项目结构窗口,切换到Modules
添加Web功能 单击【Create Artifact】按钮 修改Artifact名称 - SSMLogin
将项目依赖添加到输出目录 单击【Put into /WEB-INF/lib】命令 单击【OK】按钮
(七)配置Tomcat服务器
单击工具栏上的【Add Configuration…】,打开【运行/调试配置】窗口 添加本地的Tomcat服务器 选择Local
单击【Configure…】按钮 单击【OK】按钮 修改名称,启动的浏览器 单击【Fix】按钮 切换到【Server】选项卡 单击【OK】按钮
(八)创建用户实体类
创建net.huawei.ssm.bean
包,在包里创建User
类
package net. huawei. 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 +
'}' ;
}
}
更新到此
(九)创建用户映射器接口 - UserMapper
创建net.hw.shop.mapper包,在包里创建UserMapper接口
package net. hw. shop. mapper ;
import net. hw. shop. bean. User ;
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) ;
}
(十)创建用户服务类 - UserService
在net.hw.shop包里创建service子包,然后在子包里创建UserService类
package net. hw. shop. service ;
import net. hw. shop. bean. User ;
import net. hw. shop. 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) ;
}
}
(十一)创建用户控制器 - UserController
在net.hw.shop包里创建controller子包,然后在子包里创建UserController类
package net. hw. shop. controller ;
import net. hw. service. UserService ;
import net. hw. shop. bean. User ;
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 ;
@Controller
@RequestMapping ( "/user" )
public class UserController {
@Autowired
private UserService userService;
@RequestMapping ( "/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 ( "username" , username) ;
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" )
public String logout ( HttpSession session) {
session. removeAttribute ( "username" ) ;
session. invalidate ( ) ;
return "frontend/login" ;
}
}
(十二)创建用户映射器配置文件 - UserMapper.xml
在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.hw.shop.mapper.UserMapper" >
< resultMap id = " userMap" type = " net.hw.shop.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>
(十三)创建Spring配置文件 - spring-config.xml
在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"
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.hw.shop" />
< 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.hw.shop.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.hw.shop.service..*.*(..))" />
< aop: advisor advice-ref = " txAdvice" pointcut-ref = " mypt" />
</ aop: config>
(十四)创建Spring MVC配置文件 - spring-mvc-config.xml
在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/images/" />
< mvc: annotation-driven/>
< mvc: view-controller path = " user/login" view-name = " frontend/login" />
< context: component-scan base-package = " net.hw.shop.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.hw.shop" >
< context: exclude-filter type = " annotation" expression = " org.springframework.stereotype.Service" />
</ context: component-scan>
</ beans>
(十五)编辑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>
< listener>
< listener-class> org.springframework.web.context.ContextLoaderListener</ listener-class>
</ listener>
< context-param>
< param-name> contextConfigLocation</ param-name>
< param-value> classpath:config/spring-config.xml</ param-value>
</ context-param>
< 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> /*</ url-pattern>
</ filter-mapping>
</ web-app>
(十六)准备图片资源
在WEB-INF里创建images目录,用来存放图片资源
(十七)创建样式文件 - login.css
在WEB-INF里创建css子目录,然后在子目录里创建login.css
body {
margin : 0px;
text-align : center;
background : #cccccc;
}
(十八)创建脚本文件 - check.js
在WEB-INF里创建js子目录,然后在子目录里创建check.js
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 ;
}
(十九)创建页面
1、创建目录结构
2、创建登录页面 - login.jsp
在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>
3、创建网站首页 - index.jsp
在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>
< h3> 欢迎访问西蒙购物网</ h3>
登录用户:${username} —— < a href = " user/logout" > 注销</ a> < br/>
< img src = " images/bear.jpg" width = " 300" height = " 250" >
</ body>
</ html>
4、创建后台管理页面 - management.jsp
在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>
管理员:${username} —— < a href = " user/logout" > 注销</ a> < br/>
< img src = " images/bear.jpg" width = " 300" height = " 250" >
</ body>
</ html>
(二十)启动服务器,查看效果
四、课后作业
任务1、完成用户注册功能
在用户登录页面添加跳转到用户注册页面的超链接 用户注册要进行用户名和密码的非空校验 用户注册失败,弹出警告框提示用户 用户注册成功,就跳转到用户登录页面 用新注册的用户进行登录测试
任务2、实现二维码制作功能
二维码制作页面:文本框输入字符串,还有提交按钮 单击提交按钮,跳转到目标页面,显示生成的二维码
参考案例