为什么从Firefox发布到Spring Boot应用程序获得405方法不允许
我想弄清楚这个很奇怪的问题。为什么从Firefox发布到Spring Boot应用程序获得405方法不允许
我有一个使用Thymeleaf作为模板的Spring Boot应用程序,并且在我的页面上,我有HTTP POST,在Safari和Chrome浏览器上可以很好地工作,但不在Firefox上。
当我尝试从Firefox张贴到我的春节,引导与这样的控制器:
@Controller
public class LoginController {
@PostMapping("/login")
public String post(@RequestBody LoginForm loginForm) {
//process logging in, never makes it here when POSTing from Firefox
}
@GetMapping("/login")
public String get(Model model) {
//this generates the Thymeleaf template named login.html
return "login";
}
}
我曾在一些例子在网上看了如开关PostMapping到RequestMapping,但它仍然无法正常工作。
这是一种尝试POST前端Thymeleaf的模板:
<form action="#" th:action="@{/login}" method="post" th:object="${loginform}">
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email" th:field="*{username}" autofocus="true"/>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" th:field="*{password}"/>
</div>
<button type="submit" class="btn btn-primary">Log in</button><br/>
</form>
所以,实际生成的HTML页面上,它看起来像:
<form action="/login" method="post">
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email" autofocus="true" name="username" value="">
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password" value="">
</div>
<button type="submit" class="btn btn-primary">Log in</button><br>
<input type="hidden" name="_csrf" value="12345">
</form>
我还能尝试一下呢?谢谢!
您需要使用@RestController而不是@Controller注释您的控制器。
@RestController
public class LoginController {
@PostMapping("/login")
public String post(@RequestBody LoginForm loginForm) {
//process logging in, never makes it here when POSTing from Firefox
}
}
通常为REST,你会通过路径变量请求的实体,如:
@GetMapping("https://stackoverflow.com/users/{id}")
public ResponseEntity getUser(@PathVariable("id") Long id) {
// do something with user identified by its id
}
分析与Firefox您的问题,我建议打开与F-12和开发者视图将这些请求与Chrome中的工作请求进行比较。
嗨堆栈,如果我从@控制器更改为@ RestController,我的GET端点将fail.I更新与GET部分(和我使用Thymeleaf)的原始帖子。另外,奇怪的是为什么POST-ing在Chrome和Safari上运行正常,但不在Firefox上运行? – user1805458
为了更好的你可以改变@Controller到@RestController,也是在控制器级别添加@RequestMapping,下面添加例如,
@RestController
@Log4j2
@RequestMapping("/login")
public class LoginController {
@PostMapping("/login")
public String post(@RequestBody LoginForm loginForm) {
//process logging in, never makes it here when POSTing from Firefox
}
}
让我知道如果您有任何疑问。
嗨Balasubramanian,如果我将@ Controller更改为@ RestController,我的GET端点将失败。我正在使用GET部分更新原始帖子(并且使用Thymeleaf)。另外,奇怪的是为什么POST-ing在Chrome和Safari上运行正常,但不在Firefox上运行? – user1805458
你的代码错了。或者你字面意思是/登录/登录映射?哪个很丑? – Amiko
你可以分享如何调用这个控制器。分享该代码也可以了解问题。 – Balasubramanian
是的,我将用Thymeleaf HTML模板更新原始文章 – user1805458
您可以在运行时向我们显示http数据包或HTML文档中的表单元素吗? – herokingsley