- 创建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>
- 创建实体类
然后,需要创建几个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注解来映射到数据库表中。
- 创建控制器
接下来,需要创建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");
- 创建服务层
现在,需要创建服务接口和实现类来处理业务逻辑。代码:
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);
}
}
- 创建安全配置
@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