我遇到了和标题一样的问题。我知道spring mvc中有一个@RequesetParam,它有一个参数required=false。但尝试使用时却失败了。
实际上我发现@RequestParam
没有用。根据我的尝试,总是没问题的。使用 @RequestParam(value="root", required=true)
,其中 URL 包含/不包含 value=除空白之外的某些值
。
所以,我不知道 required=true
到底是什么。然后,无论 required=false
或 required=true
是什么,它都会抛出带有 URL 参数的异常,例如 ...&root=
。
我的HandlerMapping和AdapterMapping是RequestMappingHandlerMapping和RequestMappingHandlerAdapter
spring mvc的版本是3.2.4
请告诉我 spring mvc 发生了什么?
提前致谢:)
最佳答案
根据文档:
public abstract boolean required
Whether the parameter is required. Default is true, leading to an exception thrown in case of the parameter missing in the request. Switch this to false if you prefer a null in case of the parameter missing.
Alternatively, provide a defaultValue, which implicitly sets this flag to false.
因此,如果请求中缺少参数,您可以决定是否应该抛出异常!
根据你的问题,你很惊讶为什么没有抛出异常,这是因为这两个 URL 具有不同的含义:
http://my-domain.ir:8080/your-project-name/main.html?p=something&root=
http://my-domain.ir:8080/your-project-name/main.html?p=something
在第一种情况下,值root存在,但它没有任何值但是在第二种情况下它丢失,您的情况满足第一个条件,并且这个是因为没有异常抛出。
//if you use the code below, in your case the root will get no value exactly like you define String root =""
@RequestParam("root") String root
我建议您始终在 Spring 中使用 @ModelAttribute 并按照您希望的 JSR303 标准验证/不验证您的 Bean 类变量并接收使用该 bean 类的 GETTER/SETTER 方法获取参数值。
关于java - root=这样带值的url,带key不带值的参数如何处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22241357/