【问题标题】:Spring MVC front-end choosing a form action targetSpring MVC 前端选择表单动作目标
【发布时间】:2013-01-15 04:21:24
【问题描述】:

我的 Web 应用程序有许多表单,其中最简单的是登录表单(我使用的是 thymeleaf):

    <form method="post" action = "#" th:action = "@{/account/login}">
        Username: <input name="username" type="text" /> <br /> 
        Password: <input name="password" type="password" /> <br /> 
                  <input name="login" type="submit" value="Login" />
    </form>

我的控制器处理方法是:

@RequestMapping(value = "/account/login", method = RequestMethod.POST, params = "login")
public String login(@RequestParam("username") String username, 
        @RequestParam("password") String password,
        Model model) {

    // do some logging in           
    return "/account/profile";
}

我的问题是因为我正在向/account/login 发送 POST,这就是浏览器地址栏中显示的内容。我真的希望它显示/account/profile。我应该改为对/account/profile 进行 POST,即使从概念上讲它是不正确的。

另一种解决方案是在 /account/login 上执行 POST,成功后,在 /account/profile 上重定向并执行 GET。

假设我也有这样的处理方法:

@RequestMapping(value = "/account/login", method = RequestMethod.GET)
public String loginPage() {
    return "/account/login";
}

还有哪些其他解决方案可能适合类似 REST 的 url 映射的概念?

【问题讨论】:

    标签: java html user-interface spring-mvc


    【解决方案1】:

    我认为 POST 之后的重定向最适合您的需求:

    @RequestMapping(value = "/account/login", method = RequestMethod.GET)
    public String loginPage() {
        return "redirect:/account/profile";
    }
    

    这种方法的优点(与当前的方法相比——在操作中返回视图)是,如果用户按“F5”,表单将不会被重新发布。这已成为一种模式:redirect after post

    如果您想知道如何在重定向后显示错误,Spring 3.1 support it

    P/s:实际上,处理链接与用户浏览器地址栏上显示的内容无关。如果只关心 URL,可以使用“url-rewriting”库,如Turkey URLRewriter

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 2016-01-12
      • 2023-04-05
      • 1970-01-01
      • 2010-10-16
      • 1970-01-01
      相关资源
      最近更新 更多