Spring MVC 中的@RequestParam 处理可选参数 [英] @RequestParam in Spring MVC handling optional parameters

查看:61
本文介绍了Spring MVC 中的@RequestParam 处理可选参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Spring 控制器是否可以处理这两种请求?

Is it possible for a Spring controller to handle both kind of requests?

1) http://localhost:8080/submit/id/ID123432?logout=true

2) http://localhost:8080/submit/id/ID123432?name=sam&password=543432

如果我定义一个这样的控制器:

If I define a single controller of the kind:

 @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 请求不被接受.

the HTTP request with "logout" is not accepted.

如果我定义了两个控制器来分别处理每个请求,Spring 会抱怨已经存在‘控制器’bean 方法......映射".

If I define two controllers to handle each request separately, Spring complains with the exception "There is already 'Controller' bean method ... mapped".

推荐答案

You need to give required = false for name and password request参数也一样.那是因为,当您只提供 logout 参数时,它实际上需要 namepassword 并且它们仍然是强制性的.

You need to give required = false for name and password request parameters as well. That's because, when you provide just the logout parameter, it actually expects for name and password as well as they are still mandatory.

当您只提供 namepassword 时它起作用了,因为 logout 由于 required = false<而不是强制性参数 已经为 logout 提供.

It worked when you just gave name and password because logout wasn't a mandatory parameter thanks to required = false already given for logout.

这篇关于Spring MVC 中的@RequestParam 处理可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆