当前位置:网站首页>Develop a simple login logic based on SSM
Develop a simple login logic based on SSM
2022-07-02 00:56:00 【Professional bug development】
Preface
We have learned before SSM Whole MyBatis-plus Integration of , In this section, we will use the integrated project to develop a simple login logic .
Learning content
New projects
stay IDEA Create a new normal maven project ;

Improve our engineering structure as follows , The subcontracting functions are shown in the figure ;

Introduce project dependencies , To configure MyBatis-Plus;
Refer to the previous article : Learn together Java——SSM Integration and MyBatis-Plus UseCreate a new user data table ;

Write project code
- New entity class -User;
package com.five.study.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
/** * Description: * * @Author: kk( major bug Development ) * DateTime: 2022-02-15 16:58 */
@TableName("user")
public class User {
@TableId(type= IdType.AUTO)
private Long userId;
private String username;
private String password;
private Integer salt;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
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 Integer getSalt() {
return salt;
}
public void setSalt(Integer salt) {
this.salt = salt;
}
}
- newly build mapper Interface ;
package com.five.study.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.five.study.entity.User;
/** * Description: * * @Author: kk( major bug Development ) * DateTime: 2022-02-15 17:03 */
public interface UserMapper extends BaseMapper<User> {
}
- newly build user.xml file ;
<?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.five.study.mapper.UserMapper">
</mapper>
- To write Service Interface ;
package com.five.study.service;
import com.five.study.entity.User;
/** * Description: * * @Author: kk( major bug Development ) * DateTime: 2022-02-15 17:08 */
public interface UserService {
/** * User registration , Create a new user * * @param username user name * @param password password * @param nickname nickname * @return New user object */
public User createUser(String username, String password, String nickname);
/** * Login check * * @param username user name * @param password password * @return Login object */
public User checkLogin(String username, String password);
}
- newly build MD5 Encryption utility class ;
package com.five.study.utils;
import org.apache.commons.codec.digest.DigestUtils;
/** * Description: * * @Author: kk( major bug Development ) * DateTime: 2022-02-12 17:28 */
public class MD5Utils {
public static String md5Digest(String source , Integer salt){
char[] ca = source.toCharArray();
// Obfuscate source data
for(int i = 0 ; i < ca.length ; i++){
ca[i] = (char) (ca[i] + salt);
}
String target = new String(ca);
String md5 = DigestUtils.md5Hex(target);
return md5;
}
}
- To write Service Implementation class ;
package com.five.study.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.five.study.entity.User;
import com.five.study.mapper.UserMapper;
import com.five.study.service.UserService;
import com.five.study.service.exception.BussinessException;
import com.five.study.utils.MD5Utils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Random;
/** * Description: * * @Author: kk( major bug Development ) * DateTime: 2022-02-15 17:09 */
@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
@Resource
private UserMapper userMapper;
/** * User registration , Create a new user * * @param username user name * @param password password * @param nickname nickname * @return New user object */
public User createUser(String username, String password, String nickname) {
QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
queryWrapper.eq("username", username);
List<User> userList = userMapper.selectList(queryWrapper);
// Determine whether the user name already exists
if(userList.size() > 0){
throw new BussinessException("M01"," User name already exists ");
}
User user = new User();
user.setUsername(username);
int salt = new Random().nextInt(1000) + 1000; // Salt value
String md5 = MD5Utils.md5Digest(password, salt);
user.setPassword(md5);
user.setSalt(salt);
userMapper.insert(user);
return user;
}
/** * Login check * * @param username user name * @param password password * @return Login object */
public User checkLogin(String username, String password){
QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
queryWrapper.eq("username", username);
User user = userMapper.selectOne(queryWrapper);
if(user == null){
throw new BussinessException("M02", " The user doesn't exist ");
}
String md5 = MD5Utils.md5Digest(password, user.getSalt());
if(!md5.equals(user.getPassword())){
throw new BussinessException("M03", " Wrong password ");
}
return user;
}
}
- To write Service Test class ;
package com.five.study.service.impl;
import com.five.study.service.UserService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import static org.junit.Assert.*;
/** * Description: * * @Author: kk( major bug Development ) * DateTime: 2022-02-15 17:23 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:applicationContext.xml"})
public class UserServiceImplTest {
@Resource
private UserService userService;
@Test
public void createUser() {
userService.createUser("admin", "123456");
}
@Test
public void checkLogin() {
userService.checkLogin("admin", "123456");
}
}
test result :

7. Write controller Controller;
package com.five.study.controller;
import com.five.study.entity.User;
import com.five.study.service.UserService;
import com.five.study.service.exception.BussinessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
/** * Description: * * @Author: kk( major bug Development ) * DateTime: 2022-02-15 17:39 */
@Controller
public class UserController {
@Resource
private UserService userService;
/** *@Description: Register a new user controller *@Param: *@return: */
@PostMapping("/registe")
@ResponseBody
public Map registe(String username, String password) {
Map result = new HashMap();
try {
userService.createUser(username, password);
result.put("code", "0");
result.put("msg", "success");
} catch (BussinessException ex) {
ex.printStackTrace();
result.put("code", ex.getCode());
result.put("msg", ex.getMsg());
}
return result;
}
/** *@Description: Log in to verify the controller *@Param: *@return: */
@PostMapping("/check_login")
@ResponseBody
public Map checkLogin(String username, String password) {
Map result = new HashMap();
try {
User user = userService.checkLogin(username, password);
result.put("code", "0");
result.put("msg", "success");
} catch (BussinessException ex) {
ex.printStackTrace();
result.put("code", ex.getCode());
result.put("msg", ex.getMsg());
}
return result;
}
}
To configure tomcat The server ;
See article : Learn together Java——IDEA Rapid development of web applicationUse APIPost test ;


summary
Because I have just started using SSM Development , So the arrangement may not be in place , If you find a problem , Welcome to comment area ~
边栏推荐
- [opencv450] hog+svm and hog+cascade for pedestrian detection
- Comprehensive broadcast of global and Chinese markets 2022-2028: Research Report on technology, participants, trends, market size and share
- Geek DIY open source solution sharing - digital amplitude frequency equalization power amplifier design (practical embedded electronic design works, comprehensive practice of software and hardware)
- 449 original code, complement code, inverse code
- cookie、session、tooken
- [eight sorting ③] quick sorting (dynamic graph deduction Hoare method, digging method, front and back pointer method)
- excel数据透视表
- From 20s to 500ms, I used these three methods
- Leetcode skimming: stack and queue 05 (inverse Polish expression evaluation)
- UVM tutorial
猜你喜欢

JS -- image to base code, base to file object

Upgraded wechat tool applet source code for mobile phone detection - supports a variety of main traffic modes

XMIND mind map

Leetcode skimming: binary tree 02 (middle order traversal of binary tree)

2022 high altitude installation, maintenance and removal of test question simulation test platform operation

Slf4j print abnormal stack information
![[eight sorts ①] insert sort (direct insert sort, Hill sort)](/img/8d/2c45a8fb582dabedcd2658cd7c54bc.png)
[eight sorts ①] insert sort (direct insert sort, Hill sort)

How to type spaces in latex

Evolution of Himalayan self-developed gateway architecture

The new version of graphic network PDF will be released soon
随机推荐
UVM tutorial
AIX存储管理之卷组属性的查看和修改(二)
Schrodinger's Japanese learning applet source code
cookie、session、tooken
Zak's latest "neural information transmission", with slides and videos
Cookie, session, tooken
Bc35 & bc95 onenet mqtt (old)
XMind思维导图
2022 safety officer-b certificate examination practice questions simulated examination platform operation
Review notes of compilation principles
excel数据透视表
Accelerator systems initiative is an independent non-profit organization
Source code of Qiwei automatic card issuing system
Geek DIY open source solution sharing - digital amplitude frequency equalization power amplifier design (practical embedded electronic design works, comprehensive practice of software and hardware)
Otaku wallpaper Daquan wechat applet source code - with dynamic wallpaper to support a variety of traffic owners
The new version of graphic network PDF will be released soon
Kuberntes cloud native combat high availability deployment architecture
JS common library CDN recommendation
2022 high altitude installation, maintenance and removal of test question simulation test platform operation
什么是商业养老保险?商业养老保险安全靠谱吗?