【问题标题】:Spring Boot disables GET request for static pages when POST is specifiedSpring Boot 在指定 POST 时禁用对静态页面的 GET 请求
【发布时间】:2016-09-22 08:28:48
【问题描述】:

我正在尝试使用 Spring Boot 创建一个帐户控制器。我有一个位于 static/login.html 下的登录页面的 html 文件。当我没有将 POST 请求映射到同一路径时,页面加载得非常好。

我有一个 AccountController 类:

@RestController
public class AccountController {

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Account login(@RequestBody Map<String, Object> body) {
        // code
    }
}

此控制器禁用对 html 页面的 GET 请求。尝试访问该页面时,我收到了;

There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported

所以我的问题本质上是,如何让 POST 和 GET 请求同时工作。如果有更好的文件结构可以用于静态内容,请提出建议。

【问题讨论】:

    标签: java html spring spring-mvc spring-boot


    【解决方案1】:

    这应该可以工作

    @RequestMapping(value = "/login", method = { RequestMethod.GET, RequestMethod.POST })
    public Account login(@RequestBody Map<String, Object> body) {
        // code
    }
    

    这样,控制器映射将可用于两种方法

    更新

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String serveLogin(... (if needed) ) {
        // code to serve your static content
        return "index.html"; 
    }
    
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Account login(@RequestBody Map<String, Object> body) {
    
        // code to handle your login form POST submit
    }
    

    【讨论】:

    • 不幸的是,您的建议没有将 GET 方法映射到静态内容。您的代码将 GET 和 POST 映射到相同的方法。我需要的是 GET 响应静态网页和 POST 映射到方法。
    • 我的错,完全误解了你的问题。同一路径 (/login) 可以有 2 个不同的映射,一个用于为静态内容提供服务的 GET 方法,一个用于处理表单提交的 POST 方法。请看更新
    • 感谢您的更新。我不明白的是 Spring 是否有某种方式来维护其自动静态内容服务(这不需要我进行任何配置)。因此,您能详细说明// code to server your static content 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 2016-04-06
    • 2011-03-03
    • 1970-01-01
    • 2022-01-05
    • 2021-03-06
    • 2014-05-31
    相关资源
    最近更新 更多