当前位置:网站首页>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 ~
边栏推荐
- export default 导出的对象,不能解构问题,和module.exports的区别
- 【opencv】train&test HOG+SVM
- 测试员8年工资变动,令网友羡慕不已:你一个月顶我一年工资
- How can programmers better plan their career development?
- UDS bootloader of s32kxxx bootloader
- Intelligent operation and maintenance practice: banking business process and single transaction tracking
- How to reflect and solve the problem of bird flight? Why are planes afraid of birds?
- 2022 pinduoduo details / pinduoduo product details / pinduoduo SKU details
- Kuberntes cloud native combat high availability deployment architecture
- Output results of convolution operation with multiple tensors and multiple convolution kernels
猜你喜欢

Output results of convolution operation with multiple tensors and multiple convolution kernels

2023 Lexus ES products have been announced, which makes great progress this time

export default 导出的对象,不能解构问题,和module.exports的区别

Excel PivotTable

Otaku wallpaper Daquan wechat applet source code - with dynamic wallpaper to support a variety of traffic owners

excel查找与引用函数

使用 ES 实现疫情地图或者外卖点餐功能(含代码及数据)

Friends circle community program source code sharing

Talents come from afar, and Wangcheng district has consolidated the intellectual base of "strengthening the provincial capital"

【八大排序④】归并排序、不基于比较的排序(计数排序、基数排序、桶排序)
随机推荐
【js通过url下载文件】
Node——Egg 实现上传文件接口
Global and Chinese markets for context and location-based services 2022-2028: Research Report on technology, participants, trends, market size and share
九州云与英特尔联合发布智慧校园私有云框架,赋能教育新基建
You probably haven't noticed the very important testing strategy in your work
Evolution of Himalayan self-developed gateway architecture
S32Kxxx bootloader之UDS bootloader
【八大排序①】插入排序(直接插入排序、希尔排序)
js 公共库 cdn 推荐
【微信授权登录】uniapp开发小程序,实现获取微信授权登录功能
Picture puzzle wechat applet source code_ Support multi template production and traffic master
Which securities company is safer to open a stock account
2022 safety officer-b certificate examination practice questions simulated examination platform operation
RFID让固定资产盘点更快更准
工作中非常重要的测试策略,你大概没注意过吧
JS common library CDN recommendation
Leetcode skimming: stack and queue 04 (delete all adjacent duplicates in the string)
Comprehensive broadcast of global and Chinese markets 2022-2028: Research Report on technology, participants, trends, market size and share
Xinniuniu blind box wechat applet source code_ Support flow realization, with complete material pictures
Some understandings of graph convolution neural network r-gcn considering relations and some explanations of DGL official code