Back end development: spring boot implements registration and login functions

This implementation of the registration and login function requires the basic operation of the database, and is the front and back-end separation development. Generally speaking, it is to design the database first, then write the API interface of the server according to the database, then come to the client or the mobile terminal to design the interface of login and registration, receive the data provided by the server and display it on the interface. This paper mainly designs the back-end API interface. The data interaction design of the front-end framework will be carried out later.

1, Database design

According to the requirements of general login and registration, the user table structure of the database is as follows:

2, Design of API interface of server

1. First, the model class of user table is generated by persistent mapping

(1) , find the Persistence column, select the item, right-click and click the bottom option.

(2) , select the location of the model class, select all fields in the user table, and click OK.

(3) , find the generated model class Users, and add the primary key generator. Add the following code under annotation @ Id:

//Specify generator name
@GeneratedValue(generator = "uuid2" )
@GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator" )

2. Create a DAO layer and a new interface class UsersDao. The code is as follows:

package edu.ynmd.cms.dao;
import edu.ynmd.cms.model.Users;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;

public interface UsersDao extends JpaRepository<Users,String> {

    @Query("select u from Users u where u.username=:username and u.pass=:pass")
    List<Users> getUsersByUsernameAndPass(@Param("username")String username, @Param("pass") String pass);
    
}

3. Write server

(1) . add, delete, query and modify the definition of the method in ManageService.

    //User table
    Users saveUser(Users users);
    boolean deleteUser(String id);
    Users getUser(String id);
    Users getUserByUserNameAndPass(String username,String pass);

(2) , MangeServiceImpl.

//*****************************User table addition, deletion, query and modification start*********************************
    @Override
    public Users saveUser(Users users) {
        try {
            return usersDao.save(users);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public boolean deleteUser(String id) {
        try {
            usersDao.deleteById(id);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    @Override
    public Users getUser(String id) {
        Optional<Users> temp=usersDao.findById(id);
        return temp.isPresent()?temp.get():null;
    }

    @Override
    public Users getUserByUserNameAndPass(String username, String pass) {
        List<Users> ul=usersDao.getUsersByUsernameAndPass(username,pass);
        if(ul.size()>0){
            return ul.get(0);
        }
        return null;
    }

4. Go to PublicAction and write API interface

//User login method
    @PostMapping("/login")
    @ResponseBody
    public HashMap<String,String> login(
            @RequestBody Account account) throws IOException {
        Users u=manageService.getUserByUserNameAndPass(account.username,account.password); //Get user name and password of user table
        if(u!=null){
            String jwt= JwtUtil.generateToken(u.getRoleid(),u.getUsersid());  //Get user role and user ID

            return new HashMap<String,String>(){{
                put("msg","ok");
                put("token",jwt);
                put("role",u.getRoleid());
                // put("role","admin");
            }};
        }
        else {
            return new HashMap<String,String>(){{
                put("msg","error");
                put("token","error");
            }};
        }
    }

    public static class Account{
        public String username;
        public String password;
    }

    //User registration
    @PostMapping("saveUser")
    @ResponseBody
    public HashMap saveUser(@RequestBody Users users) throws Exception{
        HashMap m=new HashMap();

        try {
            users.setRoleid("member");

            manageService.saveUser(users);
            m.put("msg","ok");
        } catch (Exception e) {
            e.printStackTrace();

            m.put("msg","error");
        }


        return m;
    }

Finally, start the project for testing.

3, Using postman for registration and login testing

1. postman registration test

2. View the contents of the database, and you can see that you have just registered successfully

3. postman login test

4. Enter a wrong password to test whether you can log in

So far, the API interface of the server has been implemented. Later, I will write an article about the data interaction between the client and the mobile terminal and the API interface. Please wait!

Tags: Programming Database Mobile Hibernate Java

Posted on Mon, 18 May 2020 21:08:01 -0400 by shlumph