重定向在Spring Boot应用程序中使用Thymeleaf不起作用。

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

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.

重定向在Spring Boot应用程序中使用Thymeleaf不起作用。

答案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";
}

huangapple
  • 本文由 发表于 2020年4月9日 03:44:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/61108827.html
匿名

发表评论

匿名网友

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

确定