如何快速构建一个简单的Spring Boot项目?

🏆本文收录于「滚雪球学SpringBoot」专栏(全网一个名),手把手带你零基础入门Spring Boot,从入门到就业,助你早日登顶实现财富自由🚀;同时,欢迎大家关注&&收藏&&订阅!持续更新中,up!up!up!!
环境说明:Windows 10 + IntelliJ IDEA 2021.3.2 + Jdk 1.8
🚀 前言
在本篇文章中,我们将基于前述内容,构建一个 简单的 Spring Boot CRUD 应用,并实现一个 用户管理系统。该系统将包含用户的增删改查(CRUD)功能,同时集成 Spring Security 进行权限控制,确保不同角色的用户有不同的权限。
项目目标:
- 前端:使用 Thymeleaf 渲染页面,进行用户的展示与交互。
- 后端:通过 Spring Boot 提供 REST API,处理用户数据和请求。
- 数据库:使用 H2 数据库(可以换成 MySQL 或 PostgreSQL)来存储用户数据。
- 权限控制:结合 Spring Security 实现角色和权限管理。
项目功能:
- 用户管理:实现用户的增删改查功能。
- 登录和权限控制:使用 Spring Security 进行基本认证与角色管理。
- 前端展示:使用 Thymeleaf 渲染用户列表和用户信息编辑页面。
📜 目录
- 环境准备
- 1.1 创建 Spring Boot 项目
- 1.2 配置依赖
- 数据库设计与接口实现
- 2.1 创建用户实体类
- 2.2 创建用户Repository与Service
- 用户管理功能实现
- 3.1 用户的增删改查接口
- 3.2 前端界面设计(Thymeleaf)
- Spring Security 权限控制
- 4.1 配置 Spring Security
- 4.2 角色与权限控制
- 项目测试与优化
- 总结
1. 环境准备
1.1 创建 Spring Boot 项目
首先,创建一个新的 Spring Boot 项目。你可以使用 Spring Initializr()来生成项目骨架,选择以下依赖:
- Spring Web
- Spring Data JPA
- Spring Security
- Thymeleaf
- H2 Database(或者你可以使用其他数据库,如 MySQL)
1.2 配置依赖
如果你手动创建项目,以下是 pom.xml
的必要依赖:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
</dependencies>
2. 数据库设计与接口实现
2.1 创建用户实体类
我们首先定义一个 User
实体类来存储用户信息。
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String username;
@NotNull
private String password;
private String role;
// Getters and Setters
}
2.2 创建用户 Repository 与 Service
接下来,我们创建 UserRepository
接口,继承 JpaRepository
,实现与数据库的交互。
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
}
然后,我们创建一个 UserService
服务类,负责处理用户业务逻辑。
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User createUser(User user) {
return userRepository.save(user);
}
public List<User> getAllUsers() {
return userRepository.findAll();
}
public Optional<User> getUserById(Long id) {
return userRepository.findById(id);
}
public User updateUser(Long id, User user) {
user.setId(id);
return userRepository.save(user);
}
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}
3. 用户管理功能实现
3.1 用户的增删改查接口
接下来,我们为用户管理实现控制器,提供 CRUD 接口。
@Controller
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public String getAllUsers(Model model) {
model.addAttribute("users", userService.getAllUsers());
return "user_list";
}
@GetMapping("/add")
public String showCreateForm(Model model) {
model.addAttribute("user", new User());
return "user_form";
}
@PostMapping("/add")
public String createUser(@ModelAttribute User user) {
userService.createUser(user);
return "redirect:/users";
}
@GetMapping("/edit/{id}")
public String showEditForm(@PathVariable Long id, Model model) {
model.addAttribute("user", userService.getUserById(id).orElseThrow(() -> new RuntimeException("User not found")));
return "user_form";
}
@PostMapping("/edit/{id}")
public String editUser(@PathVariable Long id, @ModelAttribute User user) {
userService.updateUser(id, user);
return "redirect:/users";
}
@GetMapping("/delete/{id}")
public String deleteUser(@PathVariable Long id) {
userService.deleteUser(id);
return "redirect:/users";
}
}
3.2 前端界面设计(Thymeleaf)
我们使用 Thymeleaf 来渲染前端页面。
user_list.html
:用户列表页面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User Management</title>
</head>
<body>
<h1>User List</h1>
<a href="/users/add">Add User</a>
<table>
<thead>
<tr>
<th>Username</th>
<th>Role</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<td th:text="${user.username}"></td>
<td th:text="${user.role}"></td>
<td>
<a th:href="@{'/users/edit/' + ${user.id}}">Edit</a>
<a th:href="@{'/users/delete/' + ${user.id}}">Delete</a>
</td>
</tr>
</tbody>
</table>
</body>
</html>
user_form.html
:用户表单页面
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>User Form</title>
</head>
<body>
<h1 th:text="${user.id == null ? 'Add User' : 'Edit User'}"></h1>
<form th:action="@{'/users' + (user.id == null ? '/add' : '/edit/' + ${user.id})}" method="post">
<label for="username">Username</label>
<input type="text" id="username" name="username" th:value="${user.username}" required/><br>
<label for="role">Role</label>
<input type="text" id="role" name="role" th:value="${user.role}" required/><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
4. Spring Security 权限控制
4.1 配置 Spring Security
使用 Spring Security 来进行用户权限控制,我们配置一个简单的安全控制,允许普通用户和管理员访问不同的页面。
示例:Spring Security 配置
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login", "/register").permitAll()
.antMatchers("/users").hasRole("ADMIN")
.antMatchers("/users/*").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin").password(passwordEncoder().encode("admin")).roles("ADMIN")
.and()
.withUser("user").password(passwordEncoder().encode("user")).roles("USER");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
4.2 角色与权限控制
在上面的 Spring Security 配置中,我们为 admin
用户分配了 ADMIN
角色,user
用户分配了 USER
角色,只有 ADMIN
角色才能访问 /users
和相关的 URL。
5. 项目测试与优化
确保你的应用在不同角色下能正常工作,进行集成测试,确保数据库交互、权限控制等都能顺利运行。
📘 总结:
通过本教程,我们成功构建了一个基于 Spring Boot 的简单 用户管理系统。我们实现了用户的增删改查(CRUD)功能,并使用 Spring Security 进行了角色和权限控制。希望这个项目能够为你提供构建实际应用的思路,并帮助你深入理解 Spring Boot 的开发流程。
🧧福利赠与你🧧
无论你是计算机专业的学生,还是对编程有兴趣的小伙伴,都建议直接毫无顾忌的学习此专栏「滚雪球学SpringBoot」专栏(全网一个名),bug菌郑重承诺,凡是学习此专栏的同学,均能获取到所需的知识和技能,全网最快速入门SpringBoot,就像滚雪球一样,越滚越大, 无边无际,指数级提升。
最后,如果这篇文章对你有所帮助,帮忙给作者来个一键三连,关注、点赞、收藏,您的支持就是我坚持写作最大的动力。
同时欢迎大家关注公众号:「猿圈奇妙屋」 ,以便学习更多同类型的技术文章,免费白嫖最新BAT互联网公司面试题、4000G pdf电子书籍、简历模板、技术文章Markdown文档等海量资料。
✨️ Who am I?
我是bug菌,CSDN | 掘金 | InfoQ | 51CTO | 华为云 | 阿里云 | 腾讯云 等社区博客专家,C站博客之星Top30,华为云多年度十佳博主/价值贡献奖,掘金多年度人气作者Top40,掘金等各大社区平台签约作者,51CTO年度博主Top12,掘金/InfoQ/51CTO等社区优质创作者;全网粉丝合计 30w+;更多精彩福利点击这里;硬核微信公众号「猿圈奇妙屋」,欢迎你的加入!免费白嫖最新BAT互联网公司面试真题、4000G PDF电子书籍、简历模板等海量资料,你想要的我都有,关键是你不来拿。

-End-
- 点赞
- 收藏
- 关注作者
评论(0)