简体   繁体   中英

Is there a way to return HTML page from Restful Controller in Spring Boot?

I am currently making a file upload within my spring boot project. I am using rest controller for my controller as that is what is written within the tutorial that I am using https://www.callicoder.com/spring-boot-file-upload-download-jpa-hibernate-mysql-database-example/

However, I found out that apparently rest controller unable to display HTML page based on what is written here: How to return a html page from a restful controller in spring boot?

Is there a way for displaying my HTML page while retaining the rest controller?

this is my controller

@RestController
public class RekonsiliasiController {

    private static final Logger logger = LoggerFactory.getLogger(RekonsiliasiController.class);

    @Autowired
    private DBFileStorageService dbFileStorageService;

    @RequestMapping("/rekonsiliasi")
    public String index() {
        System.err.println("MASUK PAK EKO OI");
        return "rekonsiliasi";
    }

    @PostMapping("/uploadFile")
    public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) {
        DBFile dbFile = dbFileStorageService.storeFile(file);

        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/downloadFile/")
                .path(dbFile.getId())
                .toUriString();

        return new UploadFileResponse(dbFile.getFileName(), fileDownloadUri,
                file.getContentType(), file.getSize());
    }

    @GetMapping("/downloadFile/{fileId}")
    public ResponseEntity<ByteArrayResource> downloadFile(@PathVariable String fileId) {
        // Load file from database
        DBFile dbFile = dbFileStorageService.getFile(fileId);

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(dbFile.getFileType()))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + dbFile.getFileName() + "\"")
                .body(new ByteArrayResource(dbFile.getData()));
    }

}

and this is my rekonsiliasi.html

 <form method="POST" action="/uploadFile" enctype="multipart/form-data">
                                          <input type="file" name="file" /><br/><br/>
                                          <input type="submit" value="Submit" />
                                      </form>

This is what I get currently, a blank page with a simple text

在此处输入图像描述

UPDATE

I tried to divide between the index and the file upload to the following.

RekonsiliasiController.java

@Controller
public class RekonsiliasiController {

    @RequestMapping("/rekonsiliasi")
    public String index() {
        System.err.println("MASUK PAK EKO OI");
        return "rekonsiliasi";
    }

FileController.java

@RestController
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private DBFileStorageService dbFileStorageService;

    @PostMapping("/uploadFile")
    public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) {
        System.err.println("CEK");
        DBFile dbFile = dbFileStorageService.storeFile(file);

        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/downloadFile/")
                .path(dbFile.getId())
                .toUriString();

        return new UploadFileResponse(dbFile.getFileName(), fileDownloadUri,
                file.getContentType(), file.getSize());
    }


    @GetMapping("/downloadFile/{fileId}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileId) {
        // Load file from database
        DBFile dbFile = dbFileStorageService.getFile(fileId);

        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(dbFile.getFileType()))
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + dbFile.getFileName() + "\"")
                .body(new ByteArrayResource(dbFile.getData()));
    }

}

Now the HTML is showing perfectly fine but when I upload the file I got 403 Error. Before I tried to find the problem for this part, I'd like to know whether if there are some ways for displaying my HTML page while retaining the rest controller?

EDIT Delete the 'uploadMultipleFiles' method in FileController.Java and it still gets me 403 error

First of all, in your code in the controller method uploadMultipleFiles , you are actually calling the controller method uploadFile directly by treating it just like another method which is not ideal. The fact that you need to recursively call another controller endpoint means that it is a design flaw in itself. So, try to remove this bit of code by providing the logic in service layer to handle this scenario.

Secondly, splitting the view controller and the rest controller into two separate classes is the right approach. The @RestController annotation is designed to serve json response by default that is why we have the @Controller annotation which serves both model and view . The response code 403 that you receive has nothing to do with this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM