当前位置:网站首页>SSM (3) - user registration and login (complete)
SSM (3) - user registration and login (complete)
2022-06-09 01:12:00 【Archer__ thirteen】
One . Create databases and tables
Create a database ssm, Create a database under this database user surface
CREATE TABLE `ssm`.`user` (
`id` INT NOT NULL AUTO_INCREMENT,
`username` VARCHAR(45) UNIQUE,
`password` VARCHAR(45),
`email` VARCHAR(45),
PRIMARY KEY (`id`));Two . To write JavaBean object
package com.server.pojo;
public class User {
private Integer id;
private String username;
private String password;
private String email;
public User() {
}
public User(Integer id, String username, String password, String email) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer 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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
'}';
}
}3、 ... and . Dao layer
1. establish Mapper Interface
package com.server.mapper;
import com.server.pojo.User;
import org.apache.ibatis.annotations.Param;
public interface UserMapper {
// Add user information
void insertUser(User user);
// Query user information according to user name
User queryUserByName(@Param("username") String username);
// Query user information according to user name and password
User queryUserByNameAndPassword(@Param("username") String username, @Param("password") String password);
}2. establish Mapper Interface mapping file
Mapping files and mapper Interface 、 The method in the interface corresponds to , And write... In the mapping file sql sentence ( Equivalent to Mapper Methods in interfaces ).
notes : A table Corresponding An entity class Corresponding One mapper Interface Corresponding A mapping file
① stay resources Create one in the directory mapper Catalog ( The directory name needs to be consistent with the storage Mapper The package name of the interface is the same , It is used to store each Mapper The mapping file corresponding to the interface ), Here is com/server/mapper
② stay resources In the catalog mapper Create a mapping file under the directory :UserMapper.xml( The name of the mapping file needs to be the same as Mapper The interface has the same name )
③ In the mapping file namespace Want to be with Mapper The full class name of the interface shall be consistent , Here for : com.server.mapper.UserMapper
④ In the mapping file SQL Of the statement id Want to be with mapper The method names in the interface are the same
⑤ The return value type of the query function in the mapping file is the type corresponding to the database table JavaBean object
<?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.server.mapper.UserMapper"> <!-- by mapper The full class name of the interface -->
<insert id="insertUser">
insert into user values(#{id},#{username},#{password},#{email})
</insert>
<select id="queryUserByName" resultType="User">
select * from user where username=#{username} <!-- {} Use in @Param Value in annotation -->
</select>
<select id="queryUserByNameAndPassword" resultType="User">
select * from user where username=#{username} and password=#{password} <!-- {} Use in @Param Value in annotation -->
</select>
</mapper>Four . Service layer
1. stay service Write under the package UserService Interface
package com.server.service;
import com.server.pojo.User;
public interface UserService {
// User registration , If the user name already exists , You need to re register a new user name ( User name cannot be duplicate )
public void register(User user);
// The user login , If login fails, it will return null
public User login(String username, String password);
// Determine if the user name exists , return true Indicates that the user name already exists , return false Indicates that the user name is available
public User queryUsername(String username);
}2. stay service.impl Write under the package UserServiceImpl Class to achieve UserService Interface
package com.server.service.impl;
import com.server.mapper.UserMapper;
import com.server.pojo.User;
import com.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void register(User user) {
userMapper.insertUser(user);
}
@Override
public User login(String username, String password) {
return userMapper.queryUserByNameAndPassword(username, password);
}
@Override
public User queryUsername(String username) {
return userMapper.queryUserByName(username);
}
}5、 ... and . Web layer —— Write the controller method
package com.server.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/")
public String index(){
return "index";
}
}
package com.server.controller;
import com.server.common.Constants;
import com.server.common.ReturnObject;
import com.server.pojo.User;
import com.server.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.ResponseBody;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/loginPage")
public String goToLoginPage(){
return "user/login";
}
@RequestMapping("/registerPage")
public String goToRegisterPage(){
return "user/register";
}
@RequestMapping("/login")
@ResponseBody // add to @ResponseBody Annotations automatically convert the returned data into json
public Object loginUser(String username, String password, String isRemPwd, HttpSession session, HttpServletResponse response){ // The formal parameter name and the requested parameter name need to be the same
User user = userService.login(username, password); // Query the user
ReturnObject returnObject = new ReturnObject(); // Generate response information according to query results
if(user == null){
// Login failed
returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
returnObject.setMessage(" Wrong user name or password ");
}else {
// Login successful
returnObject.setCode(Constants.RETURN_OBJECT_CODE_SUCCESS);
session.setAttribute(Constants.SESSION_USER, user);
// If you need to remember the password , Then add cookie
if("true".equals(isRemPwd)){
Cookie cookieUsername = new Cookie("username", username);
cookieUsername.setMaxAge(7*24*60*60); //cookie preservation 7 God
response.addCookie(cookieUsername);
Cookie cookiePassword = new Cookie("password", password);
cookieUsername.setMaxAge(7*24*60*60); //cookie preservation 7 God
response.addCookie(cookiePassword);
}else{
// If you don't need to remember the password , The previously created cookie Delete
Cookie cookieUsername = new Cookie("username", null);
cookieUsername.setMaxAge(0); // Delete cookie
response.addCookie(cookieUsername);
Cookie cookiePassword = new Cookie("password", null);
cookieUsername.setMaxAge(0); // Delete cookie
response.addCookie(cookiePassword);
}
}
return returnObject;
}
@RequestMapping("/register")
@ResponseBody
public Object registerUser(String username, String password, String email, HttpSession session ){
User user = new User(null, username, password, email);
ReturnObject returnObject = new ReturnObject(); // Generate response information according to query results
if(userService.queryUsername(username) != null){
// User name already exists , Can't register
returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
returnObject.setMessage(" User name already exists ");
}else {
// You can register
userService.register(user); // register
returnObject.setCode(Constants.RETURN_OBJECT_CODE_SUCCESS);
session.setAttribute(Constants.SESSION_USER, user);
}
return returnObject;
}
@RequestMapping("/logout")
public String logout(HttpServletResponse response, HttpSession session){
// Empty cookie
Cookie cookieUsername = new Cookie("username", null);
cookieUsername.setMaxAge(0); // Delete cookie
response.addCookie(cookieUsername);
Cookie cookiePassword = new Cookie("password", null);
cookieUsername.setMaxAge(0); // Delete cookie
response.addCookie(cookiePassword);
// The destruction session
session.invalidate();
return "redirect:/"; // Redirect to home page
}
}The above needs to be customized common Under bag Constants class ( Constant class ) and ReturnObject class ( Response object class )
package com.server.common;
public class Constants {
public static final String RETURN_OBJECT_CODE_SUCCESS = "1"; // success
public static final String RETURN_OBJECT_CODE_FAIL = "0"; // Failure
public static final String SESSION_USER = "sessionUser";
}package com.server.common;
public class ReturnObject {
private String code;
private String message;
public ReturnObject() {
}
public ReturnObject(String code, String message) {
this.code = code;
this.message = message;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public String toString() {
return "ReturnObject{" +
"code='" + code + '\'' +
", message='" + message + '\'' +
'}';
}
}6、 ... and . Write page
1. stay WEB-INF Create one in the directory pages Catalog , stay pages Under directory index.jsp page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title> home page </title>
<% // Get the path of the current project
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
%>
<base href="<%=basePath%>">
</head>
<body>
<%-- If the user is not logged in yet , Show login and registration menu --%>
<c:if test="${empty sessionScope.sessionUser}">
<a href="loginPage"><input type="button" value=" Sign in "/></a>
<a href="registerPage"><input type="button" value=" register "/></a>
</c:if>
<%-- If the user is already logged in , Show welcome users and logout --%>
<c:if test="${not empty sessionScope.sessionUser}">
welcome ${sessionScope.sessionUser.username}
<a href="logout"><input type="button" value=" sign out "/></a>
</c:if>
</body>
</html>2. stay pages Create a directory user Catalog , stay user Create under directory login.jsp and register.jsp page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title> The user login </title>
<% // Get the path of the current project
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
%>
<base href="<%=basePath%>">
<script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <!-- introduce jquery -->
<script type="text/javascript">
$(function(){
// Add a keyboard press event to the browser window
$(window).keydown(function (e){
// If you press enter , Then submit the login request
if(e.keyCode == 13){
$("#loginBtn").click();
}
});
// Add click event
$("#loginBtn").click(function(){
// Get request parameters
var loginUsername = $.trim($("#loginUsername").val()); //( Remove the spaces that the user accidentally enters )
var loginPassword = $.trim($("#loginPassword").val());
var isRemPwd = $("#isRemPwd").prop("checked");
// Form validation
// Verify user name : Must consist of letters or numbers or underscores , And the length is 1-12 position
var usernamePatt = /^\w{1,12}$/;
if(!usernamePatt.test(loginUsername)){
$("#msg").text(" Illegal user name ");
return;
}
// Verify user password : Must consist of letters or numbers or underscores , And the length is 6-12 position
var passwordPatt = /^\w{6,12}$/;
if(!passwordPatt.test(loginPassword)){
$("#msg").text(" The password is illegal ");
return;
}
// Send a request
$.ajax({
url:'login',
data:{
username:loginUsername, // Need and Controller The formal parameter of the method in has the same name
password:loginPassword,
isRemPwd:isRemPwd
},
type:'post',
dataType:'json',
success:function (data){
if(data.code=="1"){
// Login successful , Jump to home page
window.location.href="";
}else{
// Login failed , No jump ( Display error message )
$("#msg").text(data.message);
}
}
});
});
});
</script>
</head>
<body>
<span id="msg"></span> <br/>
<form>
user name :<input type="text" id="loginUsername" value="${cookie.username.value}"> <br/>
password :<input type="password" id="loginPassword" value="${cookie.password.value}"> <br/>
<c:if test="${not empty cookie.username and not empty cookie.password}">
<input type="checkbox" id="isRemPwd" checked> Remember the password <br/>
</c:if>
<c:if test="${empty cookie.username or empty cookie.password}">
<input type="checkbox" id="isRemPwd"> Remember the password <br/>
</c:if>
<button type="button" id="loginBtn"> Sign in </button>
</form>
</body>
</html><%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> User registration </title>
<% // Get the path of the current project
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath()+"/";
%>
<base href="<%=basePath%>">
<script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <!-- introduce jquery -->
<script type="text/javascript">
$(function(){
// Add a keyboard press event to the browser window
$(window).keydown(function (e){
// If you press enter , Then submit the login request
if(e.keyCode == 13){
$("#registerBtn").click();
}
});
// Add click event
$("#registerBtn").click(function(){
// Get request parameters
var registerUsername = $.trim($("#registerUsername").val()); //( Remove the spaces that the user accidentally enters )
var registerPassword = $.trim($("#registerPassword").val());
var comfirmPassword = $.trim($("#comfirmPassword").val());
var email = $.trim($("#email").val());
// Form validation
// Verify user name : Must consist of letters or numbers or underscores , And the length is 1-12 position
var usernamePatt = /^\w{1,12}$/;
if(!usernamePatt.test(registerUsername)){
$("#msg").text(" Illegal user name ");
return;
}
// Verify user password : Must consist of letters or numbers or underscores , And the length is 6-12 position
var passwordPatt = /^\w{6,12}$/;
if(!passwordPatt.test(registerPassword)){
$("#msg").text(" The password is illegal ");
return;
}
// Verify the password : Must be the same as the password
if(comfirmPassword != registerPassword){
$("#msg").text(" Password inconsistency ");
return;
}
// Send a request
$.ajax({
url:'register',
data:{
username:registerUsername, // Need and Controller The formal parameter of the method in has the same name
password:registerPassword,
email:email
},
type:'post',
dataType:'json',
success:function (data){
if(data.code=="1"){
// Registered successfully , Go to the login page
window.location.href="loginPage";
}else{
// Registration failed , No jump ( Display error message )
$("#msg").text(data.message);
}
}
});
});
});
</script>
</head>
<body>
<span id="msg"></span> <br/>
<form action="register" method="post">
user name :<input type="text" id="registerUsername"> <br/>
User password :<input type="password" id="registerPassword"> <br/>
Confirm the password :<input type="password" id="comfirmPassword"> <br/>
email :<input type="text" id="email"> <br/>
<button type="button" id="registerBtn"> register </button>
</form>
</body>
</html>Ten . Final catalog form

边栏推荐
- Introduction to opencv video processing
- A complete set of meta universe elements covering software and hardware, crossing virtual and reality, has been born
- It took me two days to make a somatosensory game console
- Mongodb usage details_ 2_ Indexing and aggregation
- Vector underlying implementation (common methods)
- Take a data catalog architecture upgrade as an example to talk about the performance optimization of the business system
- Goeasy applet instant messaging source v1.1.0/ based on websocket communication service provided by goeasy
- Go language basic data type
- svg画的机器人表情包动画代码
- Hong Kong Securities Regulatory Commission reminds NFT risk
猜你喜欢

实现多线程的方法到底有1种还是2种还是4种?

Goeasy applet instant messaging source v1.1.0/ based on websocket communication service provided by goeasy

thanos监控多个kubernetes集群

腾讯云申请免费SSL证书

GoEasy小程序即时通讯源码 v1.1.0/基于GoEasy提供的websocket通讯服务

Introduction to OpenCV image processing

Detailed explanation of initial order of pointer

关于并发和并行,Go和Erlang之父都弄错了?

Flat login form page

网页滑竿拖拽选择值slider插件
随机推荐
实现多线程的方法到底有1种还是2种还是4种?
从刚入测试界到薪资翻倍:聊聊我的测试进阶历程,值得借鉴
opencv图像处理入门
Detailed explanation of initial order of pointer
Go language basic data type
Vector底层实现(常用方法)
Go language goto keyword
What enterprises want is digitalization or transformation?
一次SQL查询优化原理分析:900W+数据,从17s到300ms
Svg web animation Halloween night
Thanos monitors multiple kubernetes clusters
【牛客网SQL篇】SQL必知必会
Ceiling of tumor heterogeneity research (stereoscopic space, single cell, multiomics)
毕业设计:人脸识别项目
STM32(X) SD卡协议详解
Keda's extension to HPA
What is the correct way to start a thread?
Standard ideas for the study of tumor heterogeneity (multiomics + multipoint sampling)
A sharp tool to expose data inconsistency -- a real-time verification system
Ansible自动化运维 —— 筑梦之路