SSM框架整合-SpringMVC案例测试-用户登录
- 一、项目文件结构
- 1、项目整体结构如下图所示:
- 2、java源代码部分结构如下:
- 代码编写步骤:
- 步骤(1):导入POM依赖(在POM.xml文件的标签中插入以下内容)
- 步骤(2):在项目的WEB-INF/web.xml文件中注册SpringMVC的前端控制器DispatcherServlet及Spring容器的配置文件
- 步骤(3):创建Spring和SpringMVC的配置文件
- 步骤(4):在SpringMVC配置文件springmvc.xml中开启注解扫描功能及视图解析器;
- 步骤(5):创建用户的实体对象com.lky.entity.User
- 步骤(6):创建MyBatis的数据库访问接口com.lky.mapper.UserMapper
- 步骤(7):在MySql中创建一个user表,相关的查询 语句代码如下:
- 步骤(8):创建MyBatis的数据库访问接口映射文件UserMapper.xml
- 步骤(9):创建用户注册、登录的业务层接口UserService及实现类UserServiceImpl
- 步骤(10):在Spring配置文件中配置数据源和MyBatis的相关配置
- 步骤(11):完成登录页面视图(index.jsp)的设计和代码编写
- 步骤(12):完成注册页面视图(register.jsp)、登录成功页面(loginsuccess.jsp)的设计和代码编写,注册页面的主要代码如下
- 步骤(13):创建并完成UserController类中用户登录和注册的逻辑代码的编写
- 步骤(14):测试。部署项目,并记启动服务器,显示index.jsp登录页面运行结果
一、项目文件结构
1、项目整体结构如下图所示:
2、java源代码部分结构如下:
代码编写步骤:
步骤(1):导入POM依赖(在POM.xml文件的标签中插入以下内容)
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<!-- 作用域使用provided -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- 作用域使用provided -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
步骤(2):在项目的WEB-INF/web.xml文件中注册SpringMVC的前端控制器DispatcherServlet及Spring容器的配置文件
<?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">
<!-- 指定Spring的配置文件位置,其中classpath:代表该文件位于maven项目的resource文件夹中 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
<!-- 注册ServletConfig的监听器,监听服务器的启动 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置spring mvc的前端控制器 -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<!-- 配置初始化参数,用于读取springmvc的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc.xml</param-value>
</init-param>
<!-- 配置servlet的对象的创建时间点:应用加载时创建。取值只能是非0正整数,表示启动顺序 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
步骤(3):创建Spring和SpringMVC的配置文件
按照步骤(2)的Web.xml文件中具体的配置位置及文件名创建对应的配置文件,
例如:以下为spring配置文件位置“classpath:”代表spring.xml位于maven项目的resource文件夹中
<!-- 指定Spring的配置文件位置,其中classpath:代表该文件位于maven项目的resource文件夹中 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>
springmvc配置文件位置同上,过程略。
步骤(4):在SpringMVC配置文件springmvc.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/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/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 配置创建spring容器要扫描的包-->
<context:component-scan base-package="com.lky" use-default-filters="false"> <!-- 制定扫包规则 ,只扫描使用@Controller注解的JAVA类 -->
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
步骤(5):创建用户的实体对象com.lky.entity.User
package com.lky.entity;
public class User {
private int id;
private String username;
private String password;
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;}
}
步骤(6):创建MyBatis的数据库访问接口com.lky.mapper.UserMapper
public interface UserMapper {
// 查询指定用户名和密码的User
User getUser(@Param("username") String username, @Param("password") String password);
// 保存指定用户名和密码的user
void saveUser(@Param("username") String username, @Param("password") String password);
}
步骤(7):在MySql中创建一个user表,相关的查询 语句代码如下:
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
步骤(8):创建MyBatis的数据库访问接口映射文件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="com.lky.mapper.UserMapper">
<select id="getUser" resultType="com.lky.entity.User">
select * from user where username=#{username} and password=#{password}
</select>
<insert id="saveUser">
INSERT INTO user (username,password) VALUES (#{username}, #{password})
</insert>
</mapper>
步骤(9):创建用户注册、登录的业务层接口UserService及实现类UserServiceImpl
//业务层接口
package com.lky.service;
import com.lky.entity.User;
public interface UserService {
User getUser(String username, String password);
void insertUser(String username, String password);
}
//业务层实现类
package com.lky.service.impl;
@Service
public class UserServiceImpl implements UserService {
@Autowired
SqlSession sqlSession;
@Override
@Transactional(readOnly = true)
public User getUser(String username, String password) {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUser(username, password);
System.out.println(user);
return user;
}
@Override
@Transactional(propagation = Propagation.REQUIRED)
public void insertUser(String username, String password) {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
mapper.saveUser(username, password);
}
}
步骤(10):在Spring配置文件中配置数据源和MyBatis的相关配置
<?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"
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">
<!-- Spring容器作为父级容器要排除Controller标注的类,控制层的类交给SpringMVC的容器管理 -->
<context:component-scan base-package="com.lky">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test"/>
<property name="user" value="root"/>
<property name="password" value="123"/>
</bean>
<!-- 配置事务通知 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 扫描Spring容器中标注@Transaction注解的方法或类并加上事务 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
<!-- mybatis 和 spring进行整合的配置,有了以下的配置mybatis-config.xml就不需要了-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:com/lky/mapper/*.xml"/>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
</beans>
步骤(11):完成登录页面视图(index.jsp)的设计和代码编写
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页面</title>
</head>
<style type="text/css">
body {
margin: 0;
padding: 0;
}
.login {
height: 600px;
}
.box {
position: relative;
top: 50%;
margin-top: -190px;
background: #5998ff;
height: 300px;
}
.title {
text-align: center;
position: relative;
top: 15%;
margin-top: -50px;
font-size: 30px;
font-weight: 700px;
}
.innerBox {
position: relative;
background: white;
box-shadow: 0px 0px 5px gray;
width: 300px;
left: 50%;
margin-left: 50px;
height: 300px;
border-radius: 5px;
}
table {
position: relative;
top: 20px;
height: 160px;
width: 300px;
left: 50%;
margin-left: -150px;
padding: 20px;
}
table tr th {
font-size: 30px;
height: 40px;
}
table tr td {
height: 50px;
}
input {
width: 100%;
height: 30px;
}
</style>
<body>
<div class="login">
<div class="title">XXX管理系统登录页面</div>
<div class="box">
<div class="innerBox">
<form action="/login/doLogin" method="post">
<table>
<thead><tr><th colspan="2" >用户登录</th></tr></thead>
<tr><td align="right">用户:</td><td><input type="text" name="username"></td></tr>
<tr><td align="right">密码:</td><td><input type="password" name="password"></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="登录"></td></tr>
</table>
</form>
<div class="error" style="padding-left: 25px;color: red">${error}</div>
</div>
</div>
</div>
</body>
</html>
步骤(12):完成注册页面视图(register.jsp)、登录成功页面(loginsuccess.jsp)的设计和代码编写,注册页面的主要代码如下
<body>
<div class="login">
<div class="title">XXX管理系统注册页面</div>
<div class="box">
<div class="innerBox">
<form action="/login/doRegister" method="post">
<table>
<thead><tr><th colspan="2" >用户注册</th></tr></thead>
<tr><td align="right">用户:</td><td><input type="text" name="username"></td></tr>
<tr><td align="right">密码:</td><td><input type="password" name="password"></td></tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="注册">
</td>
</tr>
</table>
</form>
<div class="error" style="padding-left: 25px;color: red">${error}</div>
</div>
</div>
</div>
</body>
登录成功loginsuccess.jsp页面视图代码如下:
<%@ page isELIgnored="false" contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页面</title>
</head>
<body>
欢迎${username}回来
</body>
</html>
步骤(13):创建并完成UserController类中用户登录和注册的逻辑代码的编写
package com.lky.controller;
import com.lky.entity.User;
import com.lky.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpSession;
import java.util.Map;
@Controller
@RequestMapping("login")
public class UserController {
@Autowired
UserService userService;
@RequestMapping("/dologin")
public String login(String username, String password, Map<String, Object> map, HttpSession session) {
if (username == null || "".equals(username)) {
map.put("error","用户名为空");
return "index";
}
if (password == null || "".equals(password)) {
map.put("error","密码为空");
return "index";
}
User user = userService.getUser(username, password);
if (user == null){
map.put("error", "用户名或密码错误");
return "index";
}
session.setAttribute("username", username);
return "redirect:../loginsuccess.jsp";
}
@RequestMapping("/register")
public String register() {
return "register";
}
@RequestMapping("/doRegister")
public String doRegister(String username, String password, Map<String, Object> map, HttpSession session) {
if (username == null || "".equals(username)) {
map.put("error","用户名为空");
return "register";
}
if (password == null || "".equals(password)) {
map.put("error","密码为空");
return "register";
}
userService.insertUser(username, password);
return "redirect:../index.jsp";
}
}