Spring 控制器是否可以同时处理这两种请求?
http://localhost:8080/submit/id/ID123432?logout=true
http://localhost:8080/submit/id/ID123432?name=sam&password=543432
如果我定义一个这样的控制器:
@RequestMapping (value = "/submit/id/{id}", method = RequestMethod.GET,
produces="text/xml")
public String showLoginWindow(@PathVariable("id") String id,
@RequestParam(value = "logout", required = false) String logout,
@RequestParam("name") String username,
@RequestParam("password") String password,
@ModelAttribute("submitModel") SubmitModel model,
BindingResult errors) throws LoginException {...}
不接受带有“注销”的 HTTP 请求。
如果我定义两个控制器来分别处理每个请求,Spring 会抱怨异常“已经有’Controller’ bean 方法……映射”。
原文由 luksmir 发布,翻译遵循 CC BY-SA 4.0 许可协议
在 Java 8 和 Spring 5 之前(但也适用于 Java 8+ 和 Spring 5+)
您还需要为
required = false
name
和password
提供请求参数。这是因为,当您仅提供logout
参数时,它实际上期望name
和password
因为它们仍然是“隐含的”。It worked when you just gave
name
andpassword
becauselogout
wasn’t a mandatory parameter thanks torequired = false
already given forlogout
。Java 8 和 Spring 5(及更高版本)的更新
从 Java 8 开始,您现在可以使用 Optional 类来使参数成为可选的。