首页 > 其他分享 >4月20日

4月20日

时间:2023-04-24 16:02:03浏览次数:37  
标签:20 boot private User Override public user

  1. 创建Maven项目

首先,需要创建一个Maven项目并导入所需的依赖库:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.20</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.12.4</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.25</version>
    </dependency>

    <dependency>
        <groupId>org.flywaydb</groupId>
        <artifactId>flyway-core</artifactId>
        <version>7.15.0</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>

</dependencies>
  1. 创建实体类

然后,需要创建几个Java实体类来表示用户、用户资料和事件信息。代码:

@Entity
@Table(name = "users")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
public class User implements UserDetails {

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

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

    @Column(nullable = false)
    private String password;

    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Event> events = new ArrayList<>();

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
    private Profile profile;
    
    private boolean accountNonExpired;

    private boolean accountNonLocked;

    private boolean credentialsNonExpired;

    private boolean enabled;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Collections.emptyList();
    }

}
@Entity
@Table(name = "profiles")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
public class Profile {

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

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;

    @Column(nullable = true)
    private String avatar;

    @Column(nullable = true)
    private String bio;
}
@Entity
@Table(name = "events")
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder(toBuilder = true)
public class Event {

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

    @Column(nullable = false)
    private String title;

    @Column(nullable = false)
    private String description;

    @Column(nullable = false)
    private LocalDateTime startTime;

    @Column(nullable = false)
    private LocalDateTime endTime;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;
}

这些实体类使用JPA注解来映射到数据库表中。

  1. 创建控制器

接下来,需要创建Spring MVC控制器来处理URL请求。代码:

@Controller
@AllArgsConstructor
public class OfficeController {

    private final UserService userService;
    private final ProfileService profileService;
    private final EventService eventService;

    @GetMapping("/")
    public ModelAndView home() {
        return new ModelAndView("home");
    }

    @GetMapping("/login")
    public ModelAndView loginPage() {
        return new ModelAndView("login");
   
  1. 创建服务层

现在,需要创建服务接口和实现类来处理业务逻辑。代码:

public interface UserService {
    User findByUsername(String username);
    void save(User user);
}
public interface ProfileService {
    Profile findByUser(User user);
    void save(Profile profile);
}
public interface EventService {
    List<Event> findAllByUser(User user);
    Optional<Event> findById(Long id);
    void save(Event event);
}

然后,需要创建服务实现类并使用JPA Repository进行数据访问。代码:

 
@Service
@AllArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Override
    public User findByUsername(String username) {
        return userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found"));
    }

    @Override
    public void save(User user) {
        userRepository.save(user);
    }
}
@Service
@AllArgsConstructor
public class ProfileServiceImpl implements ProfileService {

    private final ProfileRepository profileRepository;

    @Override
    public Profile findByUser(User user) {
        return profileRepository.findByUser(user).orElseGet(Profile::new);
    }

    @Override
    public void save(Profile profile) {
        profileRepository.save(profile);
    }
}
@Service
@AllArgsConstructor
public class EventServiceImpl implements EventService {

    private final EventRepository eventRepository;

    @Override
    public List<Event> findAllByUser(User user) {
        return eventRepository.findAllByUserOrderByStartTime(user);
    }

    @Override
    public Optional<Event> findById(Long id) {
        return eventRepository.findById(id);
    }

    @Override
    public void save(Event event) {
        eventRepository.save(event);
    }
}
  1. 创建安全配置
@Configuration
@EnableWebSecurity
@AllArgsConstructor
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    private final UserService userService;

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

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

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

 

标签:20,boot,private,User,Override,public,user
From: https://www.cnblogs.com/2574999647wyx/p/17349766.html

相关文章

  • 联合省选2023 D2T1 过河卒
    我们可以先\(dp\),设\(f_{i,j,k,l}\)和\(g_{i,j,k,l}\)表示当前三个棋子分别在点\(i,j,k\),目前轮到\(l\)走,谁胜利,最终会走多少步。然后我们发现,变成一个有向图博弈。并且\(l\)是由\(i,j,k\)的奇偶性唯一确定的。就可以在图上直接做了。首先我们发现,我们其实可以把初始......
  • 2023五一数学建模ABC题思路解析
    0赛题思路(赛题出来以后第一时间分享)1竞赛信息数学建模竞赛是一项模拟面对实际问题寻求解决方案的活动,是一次近似于“真刀真枪”的创新探索性实践训练。在丰富并活跃学生课外生活活动的同时,数学建模竞赛有助于训练学生的想象力、洞察力和创造力,有助于培养学生团结合作组织......
  • 2023届宝鸡质检[3]文数参考答案
    备忘试题图片参考答案......
  • 【2023-04-23】人可重生
    23:00要热爱读书,它会使你生活轻松;它会友爱地帮助你了解纷繁复杂的思想、情感和事件;它会教导你尊重别人和你自己;它以热爱世界、热爱人类的情感来鼓舞智慧和心灵。                                    ......
  • [2022编思1062]找出最少动作数
    [2022编思1062]找出最少动作数题面有一个栈,这个栈有\(m\)个状态,每个状态记为\(S_i\)每个状态里面有\(n\)种数字,数字\(i\)有\(a_i\)个。考虑从全空,依次经历\(S_1...S_m\),让操作数最小化。sov是一个神奇的区间DP。考虑对于某个区间\(S_i...S_j\),从开始塞进去不用动的数字有\(......
  • BIP2087E: Broker BrokerDemo was unable to process the internal configuration mes
    今天部署的时候,.出现下面这个错误,BIP4041E:执行组'默认'发现一个无效的配置信息。BIP2210E:无效的配置信息:属性名称'allowQueryWSDL'不为目标对象的有效'Main.TestMessageFlows。' Beginrunningtask[Deploying[BrokerDemo.bar]toexecutiongroup[default]]BIP2087E:Broker......
  • openEuler Developer Day 2023 电力行业技术创新及应用论坛成功举办
    开放原子开源基金会旗下openEuler社区发起的顶级开发者峰会——openEulerDeveloperDay2023于4月20日-21日在上海召开。麒麟信安作为openEuler项目群白金捐赠人,联合主办本次盛会,并与华为共同承办2023电力行业技术创新及应用论坛。120余位电力行业用户代表、专家、openEuler社......
  • agc020 vp记录
    a,b是签到题。[AGC020C]MedianSum一个集合由N个整数组成,请求出它的非空子集和的中位数。(\(N<=2000\)\(A_i<=2000\)) 发现所有的子集和是关于所有数的和对称的。即有\(X\)则有\(\sum{A_i}-X\),于是通过背包优化的bitset算出所有能拼出的数,从$\frac{\sum{A_i}}{2}$......
  • HDCTF2023-Misc-wp
    感谢Byxs20师傅的博客指导:https://byxs20.github.io/posts/21790.html[HDCTF2023]ExtremeMisc放进010editor里,发现有zip压缩包,foremost提取出来打开压缩包里面的文件需要密码直接爆破出来密码是haida得到一个Reserve.piz,放进010editor中,发现是个zip文件,但是每两位的hex值......
  • FIT2094 数据库设计
    FIT2094DatabasesNormalisationandLogicalDatabaseDesign-CleanUpInc(CUI)FACULTYOFINFORMATIONTECHNOLOGYGiventheprovidedcasestudyfromassignment1A,andadditionalforms/documentsrelatedtothecasestudy,studentswillbeaskedtotrans......