Backend management system based on springboot, including user management, role management, login and exit and other functions

The following is a sample code for a simple backend management website based on Spring Boot, including user management, role management, login and exit and other functions.

  1. Create Spring Boot project

First, create a new Spring Boot project. Spring Initializer (https://start.spring.io/) can be used to generate the initial structure of the project. Make sure to select appropriate dependencies such as Spring Web and Spring Security.

  1. Configuration database

Configure database connection information in the application.properties file, for example:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver

  1. Create entity classes and database tables

Create User and Role entity classes to represent users and roles. At the same time, create the corresponding table in the database.

User.java:

@Entity @Table(name = "users") public class User implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false, unique = true)
private String username;

@Column(nullable = false)
private String password;

// getters and setters

}

Role.java:

@Entity @Table(name = "roles") public class Role implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(nullable = false, unique = true)
private String name;

// getters and setters

}

  1. Create data access layer

Create UserRepository and RoleRepository interfaces for accessing user and role data in the database.

UserRepository.java:

@Repository public interface UserRepository extends JpaRepository<User, Long> {

User findByUsername(String username);

}

RoleRepository.java:

@Repository public interface RoleRepository extends JpaRepository<Role, Long> {

Role findByName(String name);

}

  1. Create service layer

Create UserService and RoleService interfaces and their implementation classes to handle the business logic of users and roles.

UserService.java:

public interface UserService {

User findByUsername(String username);

}

UserServiceImpl.java:

@Service public class UserServiceImpl implements UserService {

@Autowired
private UserRepository userRepository;

@Override
public User findByUsername(String username) {
    return userRepository.findByUsername(username);
}

}

RoleService.java:

public interface RoleService {

Role findByName(String name);

}

RoleServiceImpl.java:

@Service public class RoleServiceImpl implements RoleService {

@Autowired
private RoleRepository roleRepository;

@Override
public Role findByName(String name) {
    return roleRepository.findByName(name);
}

}

  1. Create controller

Create UserController and RoleController classes to handle HTTP requests for users and roles.

UserController.java:

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

@Autowired
private UserService userService;

@GetMapping("/{username}")
public User getUserByUsername(@PathVariable String username) {
    return userService.findByUsername(username);
}

}

RoleController.java:

@RestController @RequestMapping("/roles") public class RoleController {

@Autowired
private RoleService roleService;

@GetMapping("/{name}")
public Role getRoleByName(@PathVariable String name) {
    return roleService.findByName(name);
}

}

  1. Create security configuration

Create a SecurityConfig class to configure Spring Security, including login and logout functions.

SecurityConfig.java:

@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
private UserService userService;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers("/login", "/logout").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login")
            .defaultSuccessUrl("/home")
            .permitAll()
            .and()
        .logout()
            .logoutUrl("/logout")
            .logoutSuccessUrl("/login")
            .permitAll();
}

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userService);
}

}

  1. Create page

Create pages such as login.html and home.html for user login and background management functions. These pages can be rendered using Thymeleaf or other front-end technologies.

login.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title></head>
<body><h1>Login</h1>
<form action="/login" method="post"><label for="username">Username:</label> <input type="text" id="username"
                                                                                   name="username" required><br> <label
        for="password">Password:</label> <input type="password" id="password" name="password" required><br> <input
        type="submit" value="Login"></form>
</body>
</html>

home.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Home</title></head>
<body><h1>Welcome, [[${username}]]!</h1> <a href="/logout">Logout</a></body>
</html>
  1. Start application

Run the application, visit http://localhost:8080/login to log in, and then visit http://localhost:8080/home for background management.

This is just a simple example that can be extended and customized to suit your specific needs. For example, you can add more functions, permission controls, page styles, etc.

Guess you like

Origin blog.csdn.net/m0_37649480/article/details/135359762