Spring MVC在项目中拦截用户请求,它的核心Servlet即DispatcherServlet承担中介或是前台这样的职责,将用户请求通过HandlerMapping去匹配Controller,Controller就是具体对应请求所执行的操作。Spring MVC相当于SSH框架中Struts。
MVC开始是存在于桌面程序中的,M是指业务模型,V是指用户界面,C则是控制器,使用MVC的目的是将M和V的实现代码分离,从而使同一个程序可以使用不同的表现形式。比如一批统计数据可以分别用柱状图、饼图来表示。C存在的目的则是确保M和V的同步,一旦M改变,V应该同步更新。
模型-视图-控制器(MVC)是Xerox PARC在二十世纪八十年代为编程语言Smalltalk-80发明的一种软件设计模式,已被广泛使用。后来被推荐为Oracle旗下Sun公司Java EE平台的设计模式,并且受到越来越多的使用ColdFusion和PHP的开发者的欢迎。模型-视图-控制器模式是一个有用的工具箱,它有很多好处,但也有一些缺点。
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) NOT NULL,
`password` varchar(20) DEFAULT NULL,
`telephone` varchar(11) DEFAULT NULL,
`register_time` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
`popedom` int(11) DEFAULT NULL COMMENT '0:管理员;1:普通用户',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
INSERT INTO `t_user` VALUES ('1', 'admin', '12345', '15734345678', '2021-09-02 08:40:35', '0');
INSERT INTO `t_user` VALUES ('2', 'alice', '11111', '13956567889', '2021-10-20 09:51:43', '1');
INSERT INTO `t_user` VALUES ('3', 'brown', '22222', '13956678907', '2022-03-21 09:52:36', '1');
INSERT INTO `t_user` VALUES ('4', 'linda', '33333', '15890905678', '2022-05-25 09:52:56', '1');
<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.huawei.ssmgroupId>
<artifactId>SSMLoginartifactId>
<version>1.0-SNAPSHOTversion>
<properties>
<spring.version>5.3.20spring.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.2.10version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.5.10version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>2.0.7version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.13.2version>
<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.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.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/ssmdb?useSSL=false
jdbc.username = root
jdbc.password = 903213
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 +
'}';
}
}
package net.huawei.ssm.mapper;
import net.huawei.ssm.bean.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
@Mapper // 交给Spring容器管理
public interface UserMapper {
User login(@Param("username") String username, @Param("password") String password);
}
package net.huawei.ssm.service;
import net.huawei.ssm.bean.User;
import net.huawei.ssm.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service // 交给Spring容器管理
public class UserService {
@Autowired // 自动装配
private UserMapper userMapper;
public User login(String username, String password) {
return userMapper.login(username, password);
}
}
package net.huawei.ssm.controller;
import net.huawei.ssm.bean.User;
import net.huawei.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;
@Controller // 交给Spring容器管理
@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");
}
System.out.println(user);
// 判断用户角色,跳转到不同页面
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"; // 逻辑视图名
}
}
DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="net.huawei.ssm.mapper.UserMapper">
<resultMap id="userMap" type="net.huawei.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>
/* 样式 */
body {
margin: 0px;
text-align: center;
background: #cccccc;
}
/**
* 检验登录表单
*
* @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; // 表明可以提交数据到服务器端
}
<%@ 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>
<%@ 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.png" width="300" height="250">
</body>
</html>
<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
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="net.huawei.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/*Mapper.xml"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="net.huawei.ssm.mapper"/>
bean>
beans>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<mvc:resources mapping="/css/**" location="/WEB-INF/css/"/>
<mvc:resources mapping="/images/**" location="/WEB-INF/images/"/>
<mvc:resources mapping="/js/**" location="/WEB-INF/js/"/>
<mvc:annotation-driven />
<context:component-scan base-package="net.huawei.ssm.controller"/>
<context:component-scan base-package="net.huawei.ssm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/>
context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
bean>
<mvc:view-controller path="user/login" view-name="frontend/login"/>
beans>
<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>simonshopdisplay-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>