spring-mvc - 无法在 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),它运行良好。我的控制器、服务或模板引擎有问题吗?
解决方案
你需要从你的类中删除@RestController,并且你需要使用@Controller 而不是@RestController。你需要从你的类方法中删除 @ResponseBody 。因为@RestController 和@ResponseBody 将用于将响应序列化为JSON。
推荐阅读
- git - 使用来自 AWS EC2 中的存储库的 ssh 进行 Git 克隆?
- symfony - 问题 Symfony/Doctrine:一对多 - 主键上的自引用
- python - python脚本同时运行的问题
- arrays - 在最大堆中找到最小元素的最佳算法是什么?
- c# - 这些类之间的通信实现
- arrays - React 显示一个具有不同值的对象数组,有没有更好的 .map 替代品?
- reactjs - 使用 API 中的 react-select 填充我的选项数据?
- python - 并行导出快照
- javascript - 在 JavaScript 中更改 Twilio 客户端 CallSid
- python - PyQt5 QScrollArea 不滚动,而是调整项目大小