Tomcat服务器没有映射我的真实域名。

huangapple go评论72阅读模式
英文:

tomcat server doesn't mapped my real domain name

问题

Spring Boot 应用中的多部分文件获取在生产环境中不起作用

我有一个使用Thymeleaf的Spring Boot MVC Web应用程序。在本地PC上一切正常工作,但在生产环境(远程服务器)尝试查看和下载文件时,URL前缀仍然是"localhost:8080/file-url/view"而不是"example.az/file-url/view"。我的应用程序服务器是Tomcat 9.0.71版本在Linux服务器上。

以下是代码片段

Controller类

@Controller
public class FileBBController {

    private final CategoryBBService categoryBBService;

    public FileBBController(CategoryBBService categoryBBService) {
        this.categoryBBService = categoryBBService;
    }

    @GetMapping("/files/bb/new")
    public String newFile() {
        return "legislation/bb/upload_form";
    }

    @PostMapping(value = "/files/bb/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file, Model model) {
        String message;
        try {
            categoryBBService.storeFile(file);
            message = "Fayl bazaya müvəfəqiyyətlə yükləndi: " + file.getOriginalFilename();
            model.addAttribute("message", message);
            Thread.sleep(4000);
        } catch (Exception e) {
            message = "Diqqət bir fayl seçməlisiniz!";
            model.addAttribute("message", message);
        }
        return "redirect:/bb/files";
    }

    // 其他控制器方法...
}

Service类

@Service
public class CategoryBBService {

    // 服务类代码...
}

Entity类

@Entity
@Table(name = "category_bb")
public class CategoryBB extends FileDB {

    // 实体类代码...
}

FileDB抽象类

@MappedSuperclass
public abstract class FileDB implements Serializable {
    // 抽象类代码...
}

ResponseFile类

public class ResponseFile {
    // 响应文件类代码...
}

files.html

<!-- HTML模板代码... -->

当我点击"Fayla bax (查看文件)"和"Faylı yüklə (下载文件)"按钮时,它的前缀是"http://localhost:8080/files/c9376e46-55cb-4cf5-beab-ba886bb23c5f/bb/view/"之类的。您能帮助我解决这个问题吗?

英文:

Spring boot application multipart get file doesn't working in production environment

I have a spring boot mvc web application with thymeleaf. So everything is working normally in local pc but in production environment (remote server) trying to view and download the file the url prefix is sticking localhost:8080/file-url/view not example.az/file-url/view. My appication server is tomcat 9.0.71 version in linux server.

So here is the code snippet

Controller class

@Controller
public class FileBBController {

    private final CategoryBBService categoryBBService;

    public FileBBController(CategoryBBService categoryBBService) {
        this.categoryBBService = categoryBBService;
    }

    @GetMapping(&quot;/files/bb/new&quot;)
    public String newFile() {
        return &quot;legislation/bb/upload_form&quot;;
    }

    @PostMapping(value = &quot;/files/bb/upload&quot;)
    public String uploadFile(@RequestParam(&quot;file&quot;) MultipartFile file, Model model) {
        String message;
        try {
            categoryBBService.storeFile(file);
            message = &quot;Fayl bazaya m&#252;vəfəqiyyətlə y&#252;kləndi: &quot; + file.getOriginalFilename();
            model.addAttribute(&quot;message&quot;, message);
            Thread.sleep(4000);
        } catch (Exception e) {
            message = &quot;Diqqət bir fayl se&#231;məlisiniz!&quot;;
            model.addAttribute(&quot;message&quot;, message);
        }
        return &quot;redirect:/bb/files&quot;;
    }

    @GetMapping(&quot;/bb/files&quot;)
    public String getFiles(Model model) {
        String keyword = null;
        return getOnePage(1, model, &quot;createdAt&quot;, &quot;desc&quot;, keyword);
    }

    @GetMapping(&quot;/files/{id}&quot;)
    public ResponseEntity&lt;Resource&gt; getFile(@PathVariable String id) {
        CategoryBB fileDB = categoryBBService.getFile(id);

        return ResponseEntity.ok().contentType(MediaType.APPLICATION_PDF)
                .header(org.springframework.http.HttpHeaders.CONTENT_DISPOSITION,
                        &quot;attachment; filename=\&quot;&quot; + fileDB.getName() + &quot;\&quot;&quot;)
                .body(new ByteArrayResource(fileDB.getData()));
    }

    @GetMapping(&quot;/bb/files/page/{pageNo}&quot;)
    public String getOnePage(@PathVariable(&quot;pageNo&quot;) int currentPage, Model model,
                             @RequestParam(value = &quot;sortField&quot;, required = false) String sortField,
                             @RequestParam(value = &quot;sortDir&quot;, required = false) String sortDir,
                             @RequestParam(value = &quot;keyword&quot;, required = false) String keyword
    ) {
        Page&lt;ResponseFile&gt; page = categoryBBService.findPaginated(currentPage, PAGE_SIZE, sortField, sortDir, keyword).map(dbFile -&gt; {
            String fileDownloadUri = ServletUriComponentsBuilder.
                    fromCurrentContextPath()
                    .path(&quot;/files/&quot;)
                    .path(dbFile.getId())
                    .toUriString();
            System.out.println(fileDownloadUri);
            return new ResponseFile(dbFile.getName(),
                    fileDownloadUri,
                    dbFile.getType(),
                    FileUtils.byteCountToDisplaySize(dbFile.getData().length),
                    dbFile.getCreatedAt());
        });
        List&lt;ResponseFile&gt; files = page.getContent();
        model.addAttribute(&quot;currentPage&quot;, currentPage);
        model.addAttribute(&quot;totalPages&quot;, page.getTotalPages());
        model.addAttribute(&quot;totalElements&quot;, page.getTotalElements());
        model.addAttribute(&quot;sortField&quot;, sortField);
        model.addAttribute(&quot;sortDir&quot;, sortDir);
        model.addAttribute(&quot;reverseSortDir&quot;, sortDir.equals(&quot;asc&quot;) ? &quot;desc&quot; : &quot;asc&quot;);
        model.addAttribute(&quot;keyword&quot;, keyword);
        model.addAttribute(&quot;files&quot;, files);

        return &quot;legislation/bb/files&quot;;
    }

    @RequestMapping(value = &quot;/files/{id}/bb/delete&quot;, method = RequestMethod.GET)
    public String deleteFile(@PathVariable(&quot;id&quot;) String id) {
        categoryBBService.deleteFileById(id);
        return &quot;redirect:/bb/files&quot;;
    }

    @GetMapping(&quot;/files/{id}/bb/view&quot;)
    public void viewFile(@PathVariable String id, HttpServletResponse resp) throws IOException {
        CategoryBB file = categoryBBService.getFile(id);
        byte[] byteArray = file.getData();
        resp.setContentLength(byteArray.length);
        try (OutputStream os = resp.getOutputStream()) {
            os.write(byteArray, 0, byteArray.length);
        }
    }

}

Service class

@Service
public class CategoryBBService {

    private final CategoryBBRepository categoryBBRepository;

    public CategoryBBService(CategoryBBRepository categoryBBRepository) {
        this.categoryBBRepository = categoryBBRepository;
    }

    public void storeFile(MultipartFile file) throws IOException {

        String fileName = StringUtils.getFilename(file.getOriginalFilename());
        if (StringUtils.endsWithIgnoreCase(fileName, &quot;.pdf&quot;)) {
            CategoryBB fileDB = new CategoryBB(fileName, file.getContentType(), file.getBytes());
            categoryBBRepository.save(fileDB);
        } else {
            throw new RuntimeException(&quot;Wrong file type uploaded&quot;);
        }
    }

    public CategoryBB getFile(String id) {
        return categoryBBRepository.findById(id).orElse(null);
    }

    public Page&lt;CategoryBB&gt; findPaginated(int pageNo, int pageSize,
                                          String sortField,
                                          String sortDirection,
                                          String keyword) {
        Sort sort = SortUtil.sorting(sortDirection, sortField);
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        if (keyword != null) {
            return categoryBBRepository.findAll(keyword, pageable);
        }
        return categoryBBRepository.findAll(pageable);
    }

    public void deleteFileById(String id) {
        categoryBBRepository.deleteById(id);
    }

}

Entity class

@Entity
@Table(name = &quot;category_bb&quot;)
public class CategoryBB extends FileDB {

    public CategoryBB() {
    }

    public CategoryBB(String name, String type, byte[] data) {
        super(name, type, data);
    }

}

Super class for Entity

@MappedSuperclass
public abstract class FileDB implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(generator = &quot;uuid&quot;)
    @GenericGenerator(name = &quot;uuid&quot;, strategy = &quot;uuid2&quot;)
    private String id;
    private String name;
    private String type;

    @Column(name = &quot;file_url&quot;)
    private String fileUrl;
    @Lob
    private byte[] data;

    @CreationTimestamp
    @Column(name = &quot;created_at&quot;)
    private LocalDateTime createdAt;

    public FileDB() {
    }

    public FileDB(String name, String type, byte[] data) {
        this.name = name;
        this.type = type;
        this.data = data;
    }

    public FileDB(String name, String type, String fileUrl, byte[] data) {
        this.name = name;
        this.type = type;
        this.fileUrl = fileUrl;
        this.data = data;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public byte[] getData() {
        return data;
    }

    public void setData(byte[] data) {
        this.data = data;
    }

    public LocalDateTime getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(LocalDateTime createdAt) {
        this.createdAt = createdAt;
    }

    public String getFileUrl() {
        return fileUrl;
    }

    public void setFileUrl(String fileUrl) {
        this.fileUrl = fileUrl;
    }

ResponseFile class

public class ResponseFile {
    private String name;
    private String url;
    private String type;
    private String size;

    public ResponseFile() {
    }

    public ResponseFile(String name, String url, String type, String size, LocalDateTime createdAt) {
        this.name = name;
        this.url = url;
        this.type = type;
        this.size = size;
        this.createdAt = createdAt;
    }

    private LocalDateTime createdAt;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public LocalDateTime getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(LocalDateTime createdAt) {
        this.createdAt = createdAt;
    }

}

files.html

&lt;div th:if=&quot;${files.size() &gt; 0}&quot; class=&quot;table-responsive&quot;&gt;
        &lt;table class=&quot;table table-hover table-bordered border-primary&quot;&gt;
            &lt;thead class=&quot;thead-light table-secondary&quot;&gt;
            &lt;tr class=&quot;text-center&quot;&gt;
                &lt;th scope=&quot;col&quot;&gt;№&lt;/th&gt;
                &lt;th scope=&quot;col&quot;&gt;Faylın adı&lt;/th&gt;
                &lt;th scope=&quot;col&quot;&gt;Faylı y&#252;klə&lt;/th&gt;
                &lt;th scope=&quot;col&quot;&gt;Fayla bax&lt;/th&gt;
                &lt;th scope=&quot;col&quot;&gt;&#214;l&#231;&#252;s&#252;&lt;/th&gt;
                &lt;th sec:authorize=&quot;hasRole(&#39;ADMIN&#39;)&quot; scope=&quot;col&quot;&gt;Actions&lt;/th&gt;
                &lt;th scope=&quot;col&quot;&gt;
                    &lt;a style=&quot;text-decoration: none; color: black&quot;
                       th:href=&quot;@{&#39;/bb/files/page/&#39; + ${currentPage} + &#39;?sortField=createdAt&amp;sortDir=&#39; + ${reverseSortDir} + ${keyword != null ? &#39;&amp;keyword=&#39; + keyword : &#39;&#39;}}&quot;&gt;
                        Tarix
                    &lt;/a&gt;
                &lt;/th&gt;
            &lt;/tr&gt;
            &lt;/thead&gt;
            &lt;tbody class=&quot;table-group-divider&quot;&gt;
            &lt;tr th:each=&quot;file, fileStat : ${files}&quot;&gt;
                &lt;td class=&quot;text-center&quot; th:text=&quot;${fileStat.count}&quot;&gt;&lt;/td&gt;
                &lt;td th:text=&quot;${file.name}&quot;&gt;&lt;/td&gt;

                &lt;td class=&quot;text-center&quot;&gt;&lt;a th:href=&quot;@{${file.url}}&quot;&gt;&lt;i class=&quot;fa-solid fa-cloud-arrow-down fa-lg&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;/td&gt;
                &lt;td class=&quot;text-center&quot;&gt;&lt;a target=&quot;_blank&quot; th:href=&quot;@{${file.url} + &#39;/bb/view/&#39;}&quot;&gt;&lt;i class=&quot;fa fa-thin fa-eye fa-lg&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;/td&gt;

                &lt;td th:text=&quot;${file.size}&quot;&gt;&lt;/td&gt;
                &lt;td th:text=&quot;${#temporals.format(file.createdAt, &#39;dd-MM-yyyy, HH:mm&#39;)}&quot;&gt;&lt;/td&gt;
                &lt;td sec:authorize=&quot;hasRole(&#39;ADMIN&#39;)&quot; class=&quot;text-center&quot;&gt;
                    &lt;a th:href=&quot;@{${file.url} + &#39;/bb/delete/&#39;}&quot; th:fileName=&quot;${file.name}&quot; style=&quot;border: none; background: none&quot;
                      id=&quot;btnDelete&quot; class=&quot;btn-delete&quot; data-bs-toggle=&quot;modal&quot; data-bs-target=&quot;#exampleModal&quot;&gt;
                        &lt;i class=&quot;fa-solid fa-trash fa-xl&quot; style=&quot;color: red&quot;&gt;&lt;/i&gt;
                    &lt;/a&gt;
                &lt;/td&gt;
            &lt;/tr&gt;
            &lt;/tbody&gt;
        &lt;/table&gt;
    &lt;/div&gt;

When I click the buttton "Fayla bax (view file)" and "Faylı yüklə(download file)" it's prefix comming "http://localhost:8080/files/c9376e46-55cb-4cf5-beab-ba886bb23c5f/bb/view/" something like that. Would you help me solve this issue ?

enter image description here

enter image description here

答案1

得分: 0

基于评论:
如果您仅使用Spring Boot应用程序而没有任何反向代理(如Apache、Nginx),请尝试配置Spring的属性 server.forward-headers-strategynativeframework,这应该解决该问题。

英文:

based on comments:
If you are using just spring-boot application without any reverse proxy (such as apache, nginx) try to configure spring's property server.forward-headers-strategy to either native or framework and it should resolve the issue.

huangapple
  • 本文由 发表于 2023年2月24日 15:01:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定