|
1 | 1 | package com.reajason.javaweb.boot.controller; |
2 | 2 |
|
| 3 | +import jakarta.servlet.http.HttpServletRequest; |
| 4 | +import jakarta.servlet.http.HttpServletResponse; |
| 5 | +import org.springframework.core.io.ClassPathResource; |
| 6 | +import org.springframework.http.MediaType; |
3 | 7 | import org.springframework.stereotype.Controller; |
| 8 | +import org.springframework.util.FileCopyUtils; |
4 | 9 | import org.springframework.web.bind.annotation.GetMapping; |
| 10 | +import org.springframework.web.bind.annotation.ResponseBody; |
| 11 | + |
| 12 | +import java.io.IOException; |
| 13 | +import java.io.InputStreamReader; |
| 14 | +import java.nio.charset.StandardCharsets; |
5 | 15 |
|
6 | 16 | /** |
7 | 17 | * @author ReaJason |
|
11 | 21 | public class ViewController { |
12 | 22 | @GetMapping("/") |
13 | 23 | public String index(){ |
14 | | - return "index"; |
| 24 | + return "redirect:/ui"; |
| 25 | + } |
| 26 | + |
| 27 | + @GetMapping({"/api/search", "/api/search.data"}) |
| 28 | + @ResponseBody |
| 29 | + public String handleSearch(HttpServletRequest request, HttpServletResponse response) { |
| 30 | + String fullPath = request.getRequestURI(); |
| 31 | + String relativePath = fullPath.substring(1); |
| 32 | + return renderFileData(relativePath, response); |
| 33 | + } |
| 34 | + |
| 35 | + @GetMapping({"/ui/docs/*.data", "/ui/*.data"}) |
| 36 | + @ResponseBody |
| 37 | + public String handleDataFile(HttpServletRequest request, HttpServletResponse response) throws IOException { |
| 38 | + String fullPath = request.getRequestURI(); |
| 39 | + String relativePath = fullPath.substring(4); |
| 40 | + return renderFileData(relativePath, response); |
| 41 | + } |
| 42 | + |
| 43 | + |
| 44 | + @GetMapping("/ui/**") |
| 45 | + public String handleHtmlView(HttpServletRequest request) { |
| 46 | + String fullPath = request.getRequestURI(); |
| 47 | + String viewPath = fullPath.substring(3); |
| 48 | + return viewPath + "/index"; |
| 49 | + } |
| 50 | + |
| 51 | + private String renderFileData(String relativePath, HttpServletResponse response) { |
| 52 | + try { |
| 53 | + String templatePath = "templates/" + relativePath; |
| 54 | + ClassPathResource resource = new ClassPathResource(templatePath); |
| 55 | + if (!resource.exists()) { |
| 56 | + response.setStatus(HttpServletResponse.SC_NOT_FOUND); |
| 57 | + return "File not found: " + relativePath; |
| 58 | + } |
| 59 | + response.setContentType(MediaType.TEXT_PLAIN_VALUE); |
| 60 | + response.setCharacterEncoding("UTF-8"); |
| 61 | + InputStreamReader reader = new InputStreamReader( |
| 62 | + resource.getInputStream(), |
| 63 | + StandardCharsets.UTF_8 |
| 64 | + ); |
| 65 | + return FileCopyUtils.copyToString(reader); |
| 66 | + } catch (IOException e) { |
| 67 | + response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); |
| 68 | + return "Error reading file: " + e.getMessage(); |
| 69 | + } |
15 | 70 | } |
16 | 71 | } |
0 commit comments