当前位置: 首页 > news >正文

拿自己爱人做网站做网站时网页中格式对不齐怎么办

拿自己爱人做网站,做网站时网页中格式对不齐怎么办,佛山响应式网站建设,微博html5版前提 近期在使用 Spring Boot,用户角色被分为管理者和普通用户;角色不同,权限也就存在不同。 在 Spring Boot 里实现不同用户拥有不同访问权限,可借助 Spring Security 框架达成。 实现 1. 添加必要依赖 首先要在 pom.xml 里…

前提

近期在使用 Spring Boot,用户角色被分为管理者和普通用户;角色不同,权限也就存在不同。

在 Spring Boot 里实现不同用户拥有不同访问权限,可借助 Spring Security 框架达成。

实现

1. 添加必要依赖

首先要在 pom.xml 里添加 Spring Security 和 JPA 的依赖。

<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency>
</dependencies>

2. 数据库表设计

创建三张表,分别是用户表、角色表以及用户角色关联表:

CREATE TABLE users (id INT PRIMARY KEY AUTO_INCREMENT,username VARCHAR(50) NOT NULL UNIQUE,password VARCHAR(100) NOT NULL,enabled BOOLEAN DEFAULT true
);CREATE TABLE roles (id INT PRIMARY KEY AUTO_INCREMENT,name VARCHAR(50) NOT NULL UNIQUE
);CREATE TABLE user_roles (user_id INT NOT NULL,role_id INT NOT NULL,PRIMARY KEY (user_id, role_id),FOREIGN KEY (user_id) REFERENCES users(id),FOREIGN KEY (role_id) REFERENCES roles(id)
);

3. 实体类设计

创建与数据库表对应的实体类:

// User.java
import javax.persistence.*;
import java.util.Set;@Entity
@Table(name = "users")
public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String username;private String password;private boolean enabled;@ManyToMany(fetch = FetchType.EAGER)@JoinTable(name = "user_roles",joinColumns = @JoinColumn(name = "user_id"),inverseJoinColumns = @JoinColumn(name = "role_id"))private Set<Role> roles;// getters and setters
}// Role.java
import javax.persistence.*;@Entity
@Table(name = "roles")
public class Role {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Long id;private String name;// getters and setters
}

4. 创建 Repository 接口

为 User 和 Role 分别创建 Repository 接口,用于数据访问:

// UserRepository.java
import org.springframework.data.jpa.repository.JpaRepository;public interface UserRepository extends JpaRepository<User, Long> {User findByUsername(String username);
}// RoleRepository.java
import org.springframework.data.jpa.repository.JpaRepository;public interface RoleRepository extends JpaRepository<Role, Long> {Role findByName(String name);
}

5. 实现 UserDetailsService

实现 Spring Security 的 UserDetailsService 接口,从数据库加载用户信息:

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;import java.util.ArrayList;
import java.util.List;
import java.util.Set;@Service
public class CustomUserDetailsService implements UserDetailsService {private final UserRepository userRepository;public CustomUserDetailsService(UserRepository userRepository) {this.userRepository = userRepository;}@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {User user = userRepository.findByUsername(username);if (user == null) {throw new UsernameNotFoundException("User not found with username: " + username);}return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),user.isEnabled(),true,true,true,getAuthorities(user.getRoles()));}private List<GrantedAuthority> getAuthorities(Set<Role> roles) {List<GrantedAuthority> authorities = new ArrayList<>();for (Role role : roles) {authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getName()));}return authorities;}
}

6. 配置 Spring Security

对 Spring Security 进行配置,设置不同 URL 的访问权限:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;@Configuration
@EnableWebSecurity
public class SecurityConfig {@Beanpublic PasswordEncoder passwordEncoder() {return new BCryptPasswordEncoder();}@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/public/**").permitAll().antMatchers("/admin/**").hasRole("ADMIN").antMatchers("/user/**").hasAnyRole("USER", "ADMIN").anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().permitAll();return http.build();}
}

7. 创建控制器

创建不同权限的控制器示例:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
public class HelloController {@GetMapping("/public/hello")public String publicHello() {return "Public Hello!";}@GetMapping("/user/hello")public String userHello() {return "User Hello!";}@GetMapping("/admin/hello")public String adminHello() {return "Admin Hello!";}
}

8. 测试用户数据

创建测试用户数据,以便进行测试:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;import java.util.Collections;
import java.util.HashSet;@Component
public class DataInitializer implements CommandLineRunner {@Autowiredprivate UserRepository userRepository;@Autowiredprivate RoleRepository roleRepository;@Autowiredprivate PasswordEncoder passwordEncoder;@Overridepublic void run(String... args) throws Exception {// 创建角色Role adminRole = roleRepository.findByName("ADMIN");if (adminRole == null) {adminRole = new Role();adminRole.setName("ADMIN");roleRepository.save(adminRole);}Role userRole = roleRepository.findByName("USER");if (userRole == null) {userRole = new Role();userRole.setName("USER");roleRepository.save(userRole);}// 创建管理员用户User adminUser = userRepository.findByUsername("admin");if (adminUser == null) {adminUser = new User();adminUser.setUsername("admin");adminUser.setPassword(passwordEncoder.encode("admin123"));adminUser.setEnabled(true);adminUser.setRoles(new HashSet<>(Collections.singletonList(adminRole)));userRepository.save(adminUser);}// 创建普通用户User normalUser = userRepository.findByUsername("user");if (normalUser == null) {normalUser = new User();normalUser.setUsername("user");normalUser.setPassword(passwordEncoder.encode("user123"));normalUser.setEnabled(true);normalUser.setRoles(new HashSet<>(Collections.singletonList(userRole)));userRepository.save(normalUser);}}
}

权限控制说明

  • @PreAuthorize 注解:能在方法级别进行权限控制。例如:
    @PreAuthorize("hasRole('ADMIN')")
    @GetMapping("/admin/hello")
    public String adminHello() {return "Admin Hello!";
    }
    
  • 角色继承:可以让 ADMIN 角色继承 USER 角色的权限,配置如下:
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/public/**").permitAll().antMatchers("/user/**").hasRole("USER").antMatchers("/admin/**").hasRole("ADMIN").anyRequest().authenticated().and().roleHierarchy(roleHierarchy());return http.build();
    }@Bean
    public RoleHierarchy roleHierarchy() {RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();roleHierarchy.setHierarchy("ROLE_ADMIN > ROLE_USER");return roleHierarchy;
    }
    
http://www.dtcms.com/a/552670.html

相关文章:

  • 网站开发免责说明医疗网站建设行情
  • 网页设计公司建设网站网络营销基本含义
  • 白山网站建设公司无锡做网站 选众诺
  • 如何注册公司网站免费注册网站建设中图片
  • 网站建设的实践体会深圳网站定制价格表
  • 金融行业网站模板台州网站制作价格
  • 做网站界面尺寸是多少seo基础篇
  • 一个电商网站的网页制作建一个网站问谁
  • 冀州网站建设代理汕头网站建设推荐
  • 珠海医疗网站建设宣传海报用什么软件做
  • 做我的世界壁纸的网站五棵松网站建设
  • 东庄水利枢纽建设公司网站html5软件官方下载
  • 如何自建网站wordpress单栏主题 极简
  • 做网站的公司哪家最好手机网站和微信网站有哪些
  • 门户网站系统建设方案怎么建设国字形网站
  • 做网站用什么电脑配置东莞网站推广需要多少钱
  • 济南如何挑选网站建设公司设计图制作软件app手机
  • 手机网站底部电话代码兴义住房和城乡建设局网站
  • 做a 免费网站有哪些微信朋友圈营销方案
  • 建站优化系统查高铁建设进度官方网站
  • 初中做网站用什么软件男生做男生网站在那看
  • 北京网站设计联系方式做网站费用怎么付
  • 网站制作的重要性wordpress文章排版编辑器
  • 腾讯云网站建设教学视频网页快速开发平台
  • qq在线网站代码生成找网上公司做网站
  • 有做网站网站的么毕业设计网站可以做什么
  • 网站建设需要什么内容昆明网站排名优化费用
  • 个人信息网站建设方案书框架栏目漏惹网站做
  • 网站安装模板网站建设分为多少模块
  • 提高网站公信力 单仁我也来做外国网站购物