下面详细讲解基于Spring Boot搭建Web系统架构的步骤:
1. 准备工作
在开始构建基于Spring Boot的Web系统之前,需要完成一些准备工作。这些包括:
* 安装Java JDK
* 安装Eclipse或IntelliJ IDEA等IDE
* 安装Maven或Gradle等构建工具
安装完成后,我们就可以开始构建Web系统了。
2. 创建Spring Boot项目
使用IDE创建一个新的Spring Boot项目,可以在IDE中选择Spring Boot工程模板,也可以使用Maven或Gradle创建一个新的Spring Boot项目。
3. 添加相关依赖
为了构建一个完整的Web应用程序,我们需要添加以下依赖:
* Spring Boot Web
* Thymeleaf或Freemarker模板引擎
* Spring Data JPA(如果需要使用数据库)
Maven用户可以在项目的“pom.xml”文件中添加所需的依赖。
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Thymeleaf Template Engine -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
</dependencies>
4. 创建Controller层
创建一个Controller类用于处理Web请求和响应。使用Spring MVC时,可以使用@Controller注释来标记一个类作为Controller。例如:
@Controller
public class HomeController {
@RequestMapping("/")
public String index() {
return "index";
}
}
5. 创建模板
我们需要为Web应用程序创建一个模板。在这里,我们将创建一个基于Thymeleaf的模板。我们可以在“src/main/resources/templates”文件夹中创建一个名为“index.html”的文件来作为我们的首页模板。
<!doctype html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<h1 th:text="'Hello, world!'"></h1>
</body>
</html>
6. 启动应用程序
启动我们的Spring Boot应用程序。可以使用Maven或Gradle的Spring Boot插件来启动应用程序,或者直接运行“main”方法来启动。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
示例1:构建一个简单的TodoList应用程序
1. 创建Todo模型
@Entity
public class Todo {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private String taskName;
private Boolean isComplete;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public Boolean getIsComplete() {
return isComplete;
}
public void setIsComplete(Boolean isComplete) {
this.isComplete = isComplete;
}
}
2. 创建TodosRepository
public interface TodosRepository extends CrudRepository<Todo, Long> {
}
3. 创建TodosController
@Controller
public class TodosController {
@Autowired
TodosRepository todosRepository;
@GetMapping("/todos")
public String todosList(Model model) {
Iterable<Todo> todos = todosRepository.findAll();
model.addAttribute("todos", todos);
return "todos";
}
@GetMapping("/todo/{id}")
public String todoDetail(@PathVariable("id") Long id, Model model) {
Optional<Todo> todo = todosRepository.findById(id);
if (todo.isPresent()) {
model.addAttribute("todo", todo.get());
return "todo";
} else {
return "redirect:/todos";
}
}
@PostMapping("/todo/add")
public String addTodo(@RequestParam("taskName") String taskName) {
Todo newTodo = new Todo();
newTodo.setTaskName(taskName);
newTodo.setIsComplete(false);
todosRepository.save(newTodo);
return "redirect:/todos";
}
}
4. 创建模板
4.1 todos.html模板
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Todos</title>
</head>
<body>
<div>
<h1>Todos</h1>
<form action="#" method="POST">
<input type="text" name="taskName" />
<input type="submit" value="Add" />
</form>
<ul>
<li th:each="todo : ${todos}">
<a th:href="@{/todo/{id}(id=${todo.getId()})}" th:text="${todo.getTaskName()}"></a>
</li>
</ul>
</div>
</body>
</html>
4.2 todo.html模板
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Todos</title>
</head>
<body>
<div>
<h1 th:text="${todo.getTaskName()}"></h1>
</div>
</body>
</html>
示例2:使用Spring Security实现用户登录和授权
1. 添加相关依赖
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Thymeleaf Template Engine -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
<!-- Spring Boot Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2. 创建User模型
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
private String username;
@NotNull
private String password;
@NotNull
private String email;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
3. 创建UserRepository
public interface UserRepository extends CrudRepository<User, Long> {
User findByUsername(String username);
}
4. 配置Spring Security
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home", "/register").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login").permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
@Bean
public PasswordEncoder getPasswordEncoder() {
return new BCryptPasswordEncoder();
}
}
5. 创建UserDetailsService
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username);
if (user == null) {
throw new UsernameNotFoundException(username);
}
List<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), authorities);
}
}
6. 创建UserController
@Controller
public class UserController {
@Autowired
UserRepository userRepository;
@GetMapping("/register")
public String register() {
return "register";
}
@PostMapping("/register")
public String register(User user) {
user.setPassword(new BCryptPasswordEncoder().encode(user.getPassword()));
userRepository.save(user);
return "redirect:/login";
}
@GetMapping("/login")
public String login() {
return "login";
}
@GetMapping("/home")
public String home() {
return "home";
}
}
7. 创建模板
7.1 register.html模板
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Register</title>
</head>
<body>
<div>
<h1>Register</h1>
<form action="#" method="POST">
<table>
<tbody>
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" /></td>
</tr>
</tbody>
</table>
<input type="submit" value="Register" />
</form>
</div>
</body>
</html>
7.2 login.html模板
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<div>
<h1>Login</h1>
<form th:action="@{/login}" method="POST">
<table>
<tbody>
<tr>
<td>Username</td>
<td><input type="text" name="username" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
</tbody>
</table>
<input type="submit" value="Login" />
</form>
</div>
</body>
</html>
7.3 home.html模板
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<div>
<h1 th:text="${#authentication.name}"></h1>
</div>
</body>
</html>
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:基于springboot搭建的web系统架构的方法步骤 - Python技术站