菜鸟的博客

纵有疾风起,人生不言弃。

导航

注册

  • 在UserController中声明一个(/register),接口中包括两个功能://用户名是否已被占用 //注册

​ public Result register(String username,String password){}

  • 在UserService(接口)中,实现两个方法:

​ public User findByUsername(String username){}//根据用户名查询用户

​ public void register(String username,String password){}//注册

  • 在UserMapper中,声明两个方法分别执行SQL

UserController:

~~~java
package com.di.bigevent.controller;

import com.di.bigevent.pojo.Result;
import com.di.bigevent.pojo.User;
import com.di.bigevent.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")//注册接口
    public Result register(String username,String password){

        User u = userService.findByUserName(username);

        if(u==null){
            userService.register(username,password);
            return  Result.success();
        }else{
            return Result.error("用户名已被占用");
        }


    }
}
UserService:

package com.di.bigevent.service;

import com.di.bigevent.pojo.User;

public interface UserService {
    void register(String username, String password);

    User findByUserName(String username);
}

UserServiceImpl:

package com.di.bigevent.service.impl;

import com.di.bigevent.mapper.UserMapper;
import com.di.bigevent.pojo.User;
import com.di.bigevent.service.UserService;
import com.di.bigevent.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceIml implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public User findByUserName(String username) {

        User u = userMapper.findByUserName(username);
        return u;
    }
    @Override
    public void register(String username, String password) {

        //用MD5工具类对密码进行加密,并存储到数据库
        String md5String = Md5Util.getMD5String(password);
        userMapper.add(username,md5String);
    }


}
UserMapper:
package com.di.bigevent.mapper;

import com.di.bigevent.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Service;

@Mapper
public interface UserMapper {
    @Select("select * from user where username=#{username}")
    User findByUserName(String username);


    @Insert("insert into user(username,password,create_time,update_time)" +
            " values(#{username},#{password},now(),now())")
    void add(String username, String password);
}

posted on 2024-02-29 14:49  hhmzd233  阅读(9)  评论(0编辑  收藏  举报