当前位置:网站首页>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 ~
边栏推荐
- How to open an account for individual stock speculation? Is it safe?
- gradle
- 程序员该如何更好的规划自己的职业发展?
- 【opencv】train&test HOG+SVM
- Friends circle community program source code sharing
- New version of free mobile phone, PC, tablet, notebook four terminal Website thumbnail display diagram online one click to generate website source code
- 2022拼多多详情/拼多多商品详情/拼多多sku详情
- RFID makes the inventory of fixed assets faster and more accurate
- AIX存储管理之逻辑卷的创建及属性的查看和修改
- js 公共库 cdn 推荐
猜你喜欢

2022 operation of simulated examination platform for melting welding and thermal cutting work license

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

【八大排序④】归并排序、不基于比较的排序(计数排序、基数排序、桶排序)

Mysql database driver (JDBC Driver) jar package download

【底部弹出-选择器】uniapp Picker组件——底部弹起的滚动选择器

Review notes of compilation principles

Intelligent operation and maintenance practice: banking business process and single transaction tracking

"C zero foundation introduction hundred knowledge hundred examples" (73) anonymous function -- lambda expression

Schrodinger's Japanese learning applet source code

Entrepreneurship is a little risky. Read the data and do a business analysis
随机推荐
Global and Chinese markets for context and location-based services 2022-2028: Research Report on technology, participants, trends, market size and share
Node——添加压缩文件
How do Lenovo computers connect Bluetooth headsets?
If the browser is accidentally closed, how does react cache the forms filled out by users?
Export default the exported object cannot be deconstructed, and module Differences between exports
Viewing and modifying volume group attributes of Aix storage management (II)
Geek DIY open source solution sharing - digital amplitude frequency equalization power amplifier design (practical embedded electronic design works, comprehensive practice of software and hardware)
[CTF] bjdctf 2020 Bar _ Bacystack2
Bilstm CRF code implementation
Use es to realize epidemic map or take out order function (including code and data)
2023 Lexus ES products have been announced, which makes great progress this time
Slf4j print abnormal stack information
[bottom pop-up selector] uniapp picker component - scroll selector popped up at the bottom
export default 导出的对象,不能解构问题,和module.exports的区别
使用 ES 实现疫情地图或者外卖点餐功能(含代码及数据)
[leetcode] number of maximum consecutive ones
JS common library CDN recommendation
【CTF】bjdctf_2020_babystack2
XMind思维导图
Friends circle community program source code sharing