springboot创建一个带有图片简易博客,请给出代码
时间: 2024-12-24 12:19:19 浏览: 30
Spring Boot创建一个简单的带图片的博客应用通常需要几个步骤,包括配置Web、数据访问层、持久化数据库以及处理文件上传。这里是一个简化的示例,我们将使用Thymeleaf模板引擎展示文章和图片,假设我们已经有一个User和Post实体,并且数据库表已存在。
首先,设置主配置类`Application.java`:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@SpringBootApplication
@EnableWebMvc
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
其次,创建一个基本的BlogController处理HTTP请求:
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class BlogController {
@Autowired
private PostService postService; // 假设有个PostService负责操作数据库
@GetMapping("/")
public String home(Model model) {
List<Post> posts = postService.findAll();
model.addAttribute("posts", posts);
return "home"; // Thymeleaf页面模板名称
}
@PostMapping("/upload")
public String uploadImage(@RequestParam("file") MultipartFile file) {
if (file.isEmpty()) {
return "redirect:/";
}
try {
byte[] bytes = file.getBytes();
// 将字节数组保存到服务器的某个目录下
String filePath = saveFile(bytes, "blog/images/" + file.getOriginalFilename());
// 更新数据库记录,关联新上传的图片路径
postService.updateImage(file.getOriginalFilename(), filePath);
return "redirect:/";
} catch (Exception e) {
return "error";
}
}
private String saveFile(byte[] bytes, String fileName) {
// 实现将字节数组存储到服务器文件系统的代码
// 这里省略实际的文件系统操作,你可以选择存入本地磁盘或云存储如Amazon S3等
return fileName;
}
}
```
然后,在Thymeleaf的`home.html`模板中显示文章列表和图片:
```html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Blog</title>
</head>
<body>
<h1>Welcome to My Simple Blog</h1>
<ul>
<li th:each="post : ${posts}">
<h2 th:text="${post.title}"></h2>
<img th:src="@{/images/' + ${post.imagePath} + '}" alt="Post Image" />
<p th:text="${post.content}"></p>
</li>
</ul>
<form action="#" th:action="@{/upload}" method="post" enctype="multipart/form-data">
<input type="file" name="file" accept="image/*" required />
<button type="submit">Upload Image</button>
</form>
</body>
</html>
```
注意这只是一个基础框架,实际项目中还需要处理更多细节,比如错误处理、验证、用户认证等。另外,你需要设置对应的依赖,例如Spring Web、Spring Data JPA(或Hibernate)、Thymeleaf等。
阅读全文
相关推荐


















