英文:
Redirect not working with Thymeleaf in Spring Boot app
问题
@Controller
public class RootController {
@RequestMapping("/")
public String root() {
return "login";
}
@RequestMapping(path = "/joinChart", method = RequestMethod.GET)
public String joinChart(@RequestParam(defaultValue = "") String username) {
return "redirect:chat?username=" + username;
}
}
英文:
I'am trying to create a simple app on Spring Boot:
Controller:
@Controller
public class RootController {
@RequestMapping ("/")
public String root() {
return "login";
}
@RequestMapping(path = "/joinChart", method = RequestMethod.GET)
public String joinChart(@RequestParam (defaultValue = "") String username) {
return "redirect:chat?username=" + username;
}
}
root-method is working well. But when I try to redirect on login-page, it return 404-ERROR.
答案1
得分: 1
在你的root()
处理方法中,当你执行以下代码:
return "login";
实际上你只是返回了一个视图名称(通常由JstlView
处理,但在这里由ThymeleafView
处理,因为你正在使用Thymeleaf),但Spring MVC的Web基础设施(与你的Servlet Web容器一起)将尝试查找和渲染。
在你的joinChart
处理方法中,当你执行以下代码:
return "redirect:chat?username=" + username;
实际上你正在返回一个_redirect_视图名称,服务器将以303响应和Location
头部渲染它。客户端将被指示发送一个新的请求到/chat
。如果你没有请求映射,显然服务器将返回404。
你需要为/chat
添加一个请求映射:
@RequestMapping("/chat")
public String chat() {
return "chat";
}
英文:
When you do
return "login";
in your root()
handler method, you're actually just returning a view name (typically handled by a JstlView
but here handled by ThymeleafView
since you're using Thymeleaf), but that Spring MVC's web infrastructure (with your Servlet web container) will try to find and render.
When you do
return "redirect:chat?username=" + username;
in your joinChart
handler method, you're actually returning a redirect view name that the server will render as a 303 response with a Location
header. The client will be instructed to send a new request to /chat
. If you don't have a request mapping for that, obviously the server will return a 404.
You need to add a request mapping for /chat
@RequestMapping ("/chat")
public String chat() {
return "chat";
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论