1
头图

This article participated in the " Sifu Technical Essay ", you are welcome to join.

I. Introduction

In the process of Java development, it is the most basic to realize the user's registration function. It is also a very common operation method for users to use their mobile phone number or email as a registered account. Whether it is registered by mobile phone number or email, the principle is the same, so this article will come. Share the functional realization of user registration account in the Java development process.

2. Preparations

1. Realize the background function of user registration and login through Java language;
2. The use environment includes JDK6, Eclipse, Oracle10G, Tomcat, etc.;

3. Specific implementation ideas and core steps

1, database design ① database table name and requirements:
Table name: users Primary key: id
Field name: id: user id, username: user name, password: password, group_id: user type id ② Create a data table, create primary and foreign keys, create a sequence, and add test data
2. Use Eclipse to create a web project UserDemo
3. Add Spring, Hibernate and other support to the project project, and correctly introduce and integrate into the project, and configure
4. Create data persistence classes and corresponding mapping files to establish a two-way one-to-many relationship between user types and users
5. Create new interfaces and implementation classes, and use spring database objects to implement corresponding database operations
6. Create service interface and implementation class, and implement corresponding business logic
7. Create an action class, introduce interfaces and accessors, and complete the configuration file
8. Create a new spring configuration file to implement the corresponding object declaration and configuration
9. Front-end interface construction and interface joint debugging
10. Test link: After successful debugging, export the corresponding database objects to sql files, and process the backup mechanism of user registration data, complete the test, and realize the function of user registration and login.

Fourth, the core code

1. The core code of the UserService.java file

 public interface UserService {
    /**
     * 用户注册
     *
     * @param userId
     * @param dto
     * @throws Exception
     */
    void userRegister(Long userId, UserRegisterDTO dto) throws Exception;
    /**
     * 忘记密码
     *
     * @param userId
     * @param dto
     * @throws Exception
     */
    void updatePassword(Long userId, UpdatePasswordDTO dto) throws Exception;
    /**
     * 通过邮箱发送验证码
     *
     * @param userId
     * @param email
     * @throws BusinessException
     */
    void sendVerificationCode(Long userId, String email) throws BusinessException;
    /**
     * 通过用户名密码获取用户
     *
     * @param loginName
     * @param loginPwd
     * @return
     * @throws BusinessException
     */
    User getUser(String loginName, String loginPwd) throws BusinessException;
}

2. The core code of the UserController.java file

 @RestController
@Slf4j
public class UserController extends BaseController {
    private final UserService userService;
    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }
    /**
     * 会员注册
     *
     * @param dto
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "会员注册", produces = "application/json")
    @ApiResponses({@ApiResponse(code = AjaxReturn.SUCCESS, message = "注冊成功", response = AjaxReturn.class)})
    @PostMapping(path = {"/user-save"})
    public AjaxReturn userRegister(@ModelAttribute UserRegisterDTO dto, HttpServletRequest request) throws Exception {
        log.info(dto.toString());
        Long userId = getAuthentication(request);
        if (StringUtils.isBlank(dto.getMobile()) && StringUtils.isBlank(dto.getEmail())) {
            throw new BusinessException("请输入手机号或邮箱");
        }
        if (StringUtils.isNotBlank(dto.getMobile()) && !StringUtils.isNumeric(dto.getMobile())) {
            throw new BusinessException("请输入正确的手机号");
        }
        if (StringUtils.isNotBlank(dto.getEmail()) && !StringUtils.isEmail(dto.getEmail())) {
            throw new BusinessException("请输入正确的邮箱");
        }
        if (StringUtils.isBlank(dto.getLoginPwd())) {
            throw new BusinessException("password must not be null");
        }
        // 密码MD5加密
        dto.setLoginPwd(DigestUtils.md5Hex(dto.getLoginPwd()));
        if (StringUtils.isBlank(dto.getVerificationCode())) {
            throw new BusinessException("verification code must not be null");
        }
        userService.userRegister(userId, dto);
        return AjaxReturn.builder().build();
    }
    /**
     * 忘记密码
     *
     * @param dto
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "忘记密码", produces = "application/json")
    @ApiResponses({@ApiResponse(code = AjaxReturn.SUCCESS, message = "更新密码成功", response = AjaxReturn.class)})
    @PostMapping(path = {"/user-password-forget"})
    public AjaxReturn updatePassword(@ModelAttribute UpdatePasswordDTO dto, HttpServletRequest request) throws Exception {
        Long userId = getAuthentication(request);
        if (StringUtils.isBlank(dto.getMobile()) && StringUtils.isBlank(dto.getEmail())) {
            throw new BusinessException("请输入手机号或邮箱");
        }
        if (StringUtils.isNotBlank(dto.getMobile()) && !StringUtils.isNumeric(dto.getMobile())) {
            throw new BusinessException("请输入正确的手机号");
        }
        if (StringUtils.isNotBlank(dto.getEmail()) && !StringUtils.isEmail(dto.getMobile())) {
            throw new BusinessException("请输入正确的邮箱");
        }
        if (StringUtils.isBlank(dto.getLoginPwd())) {
            throw new BusinessException("password must not be null");
        }
        // 密码MD5加密
        dto.setLoginPwd(DigestUtils.md5Hex(dto.getLoginPwd()));
        if (StringUtils.isBlank(dto.getVerificationCode())) {
            throw new BusinessException("verification code must not be null");
        }
        userService.updatePassword(userId, dto);
        return AjaxReturn.builder().build();
    }
    /**
     * 通过邮件发送验证码
     *
     * @param email
     * @param request
     * @return
     * @throws BusinessException
     */
    @ApiOperation(value = "通过邮件发送验证码", produces = "application/json")
    @ApiResponses({@ApiResponse(code = AjaxReturn.SUCCESS, message = "通过邮件发送验证码成功", response = AjaxReturn.class)})
    @PostMapping(path = {"/verification-code-send"})
    public AjaxReturn sendVerificationCode(@ApiParam(name = "email", value = "邮箱", required = true) @RequestParam String email, HttpServletRequest request) throws BusinessException {
        Long userId = getAuthentication(request);
        userService.sendVerificationCode(userId, email);
        return AjaxReturn.builder().build();
    }
}

3. LoginController file

Five, matters needing attention

1. Pay attention to code writing and naming conventions;
2. Annotate the key code to facilitate later maintenance;
3. Consider the neat placement of the controls and pay attention to the beautiful interface;
4. When operating the database, you need to pay attention to the necessary exception handling and establish a fault-tolerant mechanism.

at last

Through the process steps described above, a relatively comprehensive user registration and login function is simply realized. Although this function is very common, it is still difficult for newcomers to Java development. This proposition can be used as access to Java development. The above is the whole content of this article. If there is anything wrong, please bring it up.


三掌柜
37k 声望8.1k 粉丝

一分耕耘,不一定有一分收获,但十分耕耘,一定会有一分收获!