首页 > 解决方案 > 无法在 Spring MVC 中重定向(使用“:redirect/”)

问题描述

我正在尝试发布图片。我有一个要上传的表格(连同包含所有上传图片的表格)

<!DOCTYPE html>
<html lang="en" xmlns:th="https://thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="/main.css">
    <title>SpringImageApp</title>
</head>
<body>
    <div>
        <h3 th:if="${#vars['flash.message']}" th:text="${#vars['flash-message']}" class="flash"></h3>
        <h3 th:text="${page.number + 1} + ' of ' + ${page.totalPages}" />
            <table>
                <thead>
                <th>Id</th><th>Name</th><th>Image</th>
                </thead>
                <body>
                <tr th:each="image : ${page.content}">
                    <td th:text="${image.id}"/>
                    <td th:text="${image.name}"/>
                    <td th:text="@{'/images/' + ${image.name} + ' /raw '}"/>
                </tr>
                </body>
            </table>
            <form method="post" enctype="multipart/form-data" action="/images">
                <p><input type="file" name="file"></p>
                <p><input type="submit" value="Upload"></p>

            </form>
    </div>
</body>
</html> 

下面是我的控制器文件

private static final String BASE_PATH="images"
@RequestMapping(method = RequestMethod.POST,value = BASE_PATH )
    @ResponseBody
    public String createFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes){

        try{
            imageService.createImage(file);
            redirectAttributes.addFlashAttribute("flash.message","Successfully uploaded" + file.getOriginalFilename());

        }catch(IOException e){

            redirectAttributes.addFlashAttribute("flash.message","Failure  uploaded" + file.getOriginalFilename());


        }
        return "redirect:/";

    } 

在我上传图片之前,一切正常。它重定向到localhost:8080/images显示字符串redirect:/而不是根目录的 URL。我制作了另一个类似的应用程序(没有 thymeleaf 模板 enfine),它运行良好。我的控制器、服务或模板引擎有问题吗?

标签: spring-mvcspring-bootredirect

解决方案


你需要从你的类中删除@RestController,并且你需要使用@Controller 而不是@RestController。你需要从你的类方法中删除 @ResponseBody 。因为@RestController 和@ResponseBody 将用于将响应序列化为JSON。


推荐阅读