springboot 在线简易文档管理器demo
时间: 2023-07-18 10:52:25 浏览: 83
好的,我可以为您提供一个简单的Spring Boot在线文档管理器Demo。
首先,您需要在pom.xml文件中添加以下依赖项:
```xml
<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-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>6.4.3</version>
</dependency>
<dependency>
<groupId>com.github.javafaker</groupId>
<artifactId>javafaker</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
```
然后,您需要创建一个名为Document的实体类,该类具有以下属性:
```java
@Entity
@Table(name = "documents")
public class Document {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank(message = "Please enter a title")
private String title;
private String description;
@Lob
private String content;
private String type;
@Transient
private MultipartFile file;
private String fileName;
private String fileType;
private long fileSize;
private String fileUrl;
@Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
@Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;
@ManyToOne(fetch = FetchType.LAZY)
private User createdBy;
@ManyToOne(fetch = FetchType.LAZY)
private User updatedBy;
}
```
然后,您需要创建一个名为DocumentRepository的JpaRepository接口,用于在数据库中保存和检索文档:
```java
@Repository
public interface DocumentRepository extends JpaRepository<Document, Long> {
List<Document> findByTitleContainingIgnoreCaseOrDescriptionContainingIgnoreCase(String title, String description);
List<Document> findByTypeIgnoreCase(String type);
List<Document> findByCreatedBy(User createdBy);
List<Document> findByUpdatedBy(User updatedBy);
Page<Document> findByCreatedBy(User createdBy, Pageable pageable);
Page<Document> findByUpdatedBy(User updatedBy, Pageable pageable);
Page<Document> findAll(Pageable pageable);
}
```
接下来,您需要创建一个名为DocumentService的服务类,用于实现业务逻辑:
```java
@Service
public class DocumentService {
private final DocumentRepository documentRepository;
@Autowired
public DocumentService(DocumentRepository documentRepository) {
this.documentRepository = documentRepository;
}
public Document save(Document document) {
document.setCreatedAt(new Date());
document.setUpdatedAt(new Date());
return documentRepository.save(document);
}
public List<Document> findAll() {
return documentRepository.findAll();
}
public Optional<Document> findById(Long id) {
return documentRepository.findById(id);
}
public void deleteById(Long id) {
documentRepository.deleteById(id);
}
public List<Document> search(String query) {
return documentRepository.findByTitleContainingIgnoreCaseOrDescriptionContainingIgnoreCase(query, query);
}
public List<Document> findByType(String type) {
return documentRepository.findByTypeIgnoreCase(type);
}
public List<Document> findByCreatedBy(User createdBy) {
return documentRepository.findByCreatedBy(createdBy);
}
public List<Document> findByUpdatedBy(User updatedBy) {
return documentRepository.findByUpdatedBy(updatedBy);
}
public Page<Document> findByCreatedBy(User createdBy, Pageable pageable) {
return documentRepository.findByCreatedBy(createdBy, pageable);
}
public Page<Document> findByUpdatedBy(User updatedBy, Pageable pageable) {
return documentRepository.findByUpdatedBy(updatedBy, pageable);
}
public Page<Document> findAll(Pageable pageable) {
return documentRepository.findAll(pageable);
}
}
```
然后,您需要创建一个名为DocumentController的控制器类,用于处理与文档相关的HTTP请求:
```java
@Controller
public class DocumentController {
private final DocumentService documentService;
@Autowired
public DocumentController(DocumentService documentService) {
this.documentService = documentService;
}
@GetMapping("/")
public String home(Model model) {
List<Document> documents = documentService.findAll();
model.addAttribute("documents", documents);
return "home";
}
@GetMapping("/document/new")
public String newDocument(Model model) {
model.addAttribute("document", new Document());
return "new_document";
}
@PostMapping("/document/save")
public String saveDocument(@Valid Document document, BindingResult bindingResult, Model model) throws IOException {
if (bindingResult.hasErrors()) {
return "new_document";
}
MultipartFile file = document.getFile();
if (!file.isEmpty()) {
String fileName = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
document.setFileName(fileName);
document.setFileType(file.getContentType());
document.setFileSize(file.getSize());
String fileUrl = "http://localhost:8080/document/download/" + document.getId();
document.setFileUrl(fileUrl);
String uploadDir = "document_files/";
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
try (InputStream inputStream = file.getInputStream()) {
Path filePath = uploadPath.resolve(fileName);
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new IOException("Could not save file: " + fileName, e);
}
}
documentService.save(document);
return "redirect:/";
}
@GetMapping("/document/edit/{id}")
public String editDocument(@PathVariable Long id, Model model) {
Optional<Document> optionalDocument = documentService.findById(id);
if (optionalDocument.isPresent()) {
model.addAttribute("document", optionalDocument.get());
return "edit_document";
} else {
return "redirect:/";
}
}
@PostMapping("/document/update")
public String updateDocument(@Valid Document document, BindingResult bindingResult, Model model) throws IOException {
if (bindingResult.hasErrors()) {
return "edit_document";
}
MultipartFile file = document.getFile();
if (!file.isEmpty()) {
String fileName = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
document.setFileName(fileName);
document.setFileType(file.getContentType());
document.setFileSize(file.getSize());
String fileUrl = "http://localhost:8080/document/download/" + document.getId();
document.setFileUrl(fileUrl);
String uploadDir = "document_files/";
Path uploadPath = Paths.get(uploadDir);
if (!Files.exists(uploadPath)) {
Files.createDirectories(uploadPath);
}
try (InputStream inputStream = file.getInputStream()) {
Path filePath = uploadPath.resolve(fileName);
Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new IOException("Could not save file: " + fileName, e);
}
}
document.setUpdatedAt(new Date());
documentService.save(document);
return "redirect:/";
}
@GetMapping("/document/delete/{id}")
public String deleteDocument(@PathVariable Long id) throws IOException {
Optional<Document> optionalDocument = documentService.findById(id);
if (optionalDocument.isPresent()) {
Document document = optionalDocument.get();
String fileName = document.getFileName();
String uploadDir = "document_files/";
Path uploadPath = Paths.get(uploadDir);
Path filePath = uploadPath.resolve(fileName);
Files.deleteIfExists(filePath);
documentService.deleteById(id);
}
return "redirect:/";
}
@GetMapping("/document/search")
public String searchDocuments(@RequestParam String query, Model model) {
List<Document> documents = documentService.search(query);
model.addAttribute("documents", documents);
return "home";
}
@GetMapping("/document/type/{type}")
public String getDocumentsByType(@PathVariable String type, Model model) {
List<Document> documents = documentService.findByType(type);
model.addAttribute("documents", documents);
return "home";
}
@GetMapping("/document/created-by/{id}")
public String getDocumentsCreatedBy(@PathVariable Long id, Model model, @RequestParam(defaultValue = "0") int page) {
User createdBy = new User();
createdBy.setId(id);
Page<Document> documents = documentService.findByCreatedBy(createdBy, PageRequest.of(page, 10, Sort.by("createdAt").descending()));
model.addAttribute("documents", documents.getContent());
model.addAttribute("currentPage", page);
model.addAttribute("totalPages", documents.getTotalPages());
return "home";
}
@GetMapping("/document/updated-by/{id}")
public String getDocumentsUpdatedBy(@PathVariable Long id, Model model, @RequestParam(defaultValue = "0") int page) {
User updatedBy = new User();
updatedBy.setId(id);
Page<Document> documents = documentService.findByUpdatedBy(updatedBy, PageRequest.of(page, 10, Sort.by("updatedAt").descending()));
model.addAttribute("documents", documents.getContent());
model.addAttribute("currentPage", page);
model.addAttribute("totalPages", documents.getTotalPages());
return "home";
}
@GetMapping("/document/download/{id}")
public ResponseEntity<Resource> downloadFile(@PathVariable Long id) throws IOException {
Optional<Document> optionalDocument = documentService.findById(id);
if (optionalDocument.isPresent()) {
Document document = optionalDocument.get();
String fileName = document.getFileName();
String fileUrl = document.getFileUrl();
String uploadDir = "document_files/";
Path uploadPath = Paths.get(uploadDir);
Path filePath = uploadPath.resolve(fileName);
Resource resource = new UrlResource(filePath.toUri());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} else {
throw new FileNotFoundException("File not found with id: " + id);
}
}
}
```
最后,您需要创建名为home.html、new_document.html和edit_document.html的Thymeleaf模板文件,以呈现文档列表、新建文档表单和编辑文档表单。
这就是一个简单的Spring Boot在线文档管理器Demo,您可以在此基础上进行扩展和优化。
阅读全文