当前位置:网站首页>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 ~
边栏推荐
- 2022拼多多详情/拼多多商品详情/拼多多sku详情
- AIX存储管理之总结篇
- Use es to realize epidemic map or take out order function (including code and data)
- cookie、session、tooken
- 【八大排序②】选择排序(选择排序,堆排序)
- If the browser is accidentally closed, how does react cache the forms filled out by users?
- 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
- 【CTF】bjdctf_2020_babystack2
- cookie、session、tooken
猜你喜欢

Source code of Qiwei automatic card issuing system

gradle

Use es to realize epidemic map or take out order function (including code and data)

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

excel数据透视表

SSO single sign on implementation.
![[eight sorting ③] quick sorting (dynamic graph deduction Hoare method, digging method, front and back pointer method)](/img/c2/7ebc67e9b886e3baf3c98489bf9bce.png)
[eight sorting ③] quick sorting (dynamic graph deduction Hoare method, digging method, front and back pointer method)

What skills does an excellent software tester need to master?

Mysql database driver (JDBC Driver) jar package download

Leetcode skimming: stack and queue 01 (realizing queue with stack)
随机推荐
The 8-year salary change of testers makes netizens envy it: you pay me one year's salary per month
Entrepreneurship is a little risky. Read the data and do a business analysis
Global and Chinese markets of beverage seasoning systems 2022-2028: Research Report on technology, participants, trends, market size and share
King combat power query renamed toolbox applet source code - with traffic main incentive advertisement
【八大排序④】归并排序、不基于比较的排序(计数排序、基数排序、桶排序)
股票开户哪个证券公司比较安全
【会议资源】2022年第三届自动化科学与工程国际会议(JCASE 2022)
Node——Egg 创建本地文件访问接口
[eight sorts ④] merge sort, sort not based on comparison (count sort, cardinal sort, bucket sort)
Common loss function of deep learning
What is ThreadLocal memory leak and how to solve it
Promise and modular programming
【底部弹出-选择器】uniapp Picker组件——底部弹起的滚动选择器
Deb file installation
Global and Chinese markets for context and location-based services 2022-2028: Research Report on technology, participants, trends, market size and share
2022 low voltage electrician examination questions and answers
Comprehensive broadcast of global and Chinese markets 2022-2028: Research Report on technology, participants, trends, market size and share
2022 safety officer-b certificate examination practice questions simulated examination platform operation
How to open an account for individual stock speculation? Is it safe?
Otaku wallpaper Daquan wechat applet source code - with dynamic wallpaper to support a variety of traffic owners