java - root=这样带值的url,带key不带值的参数如何处理?

标签 java spring-mvc url-parameters

我遇到了和标题一样的问题。我知道spring mvc中有一个@RequesetParam,它有一个参数required=false。但尝试使用时却失败了。

实际上我发现@RequestParam没有用。根据我的尝试,总是没问题的。使用 @RequestParam(value="root", required=true),其中 URL 包含/不包含 value=除空白之外的某些值。 所以,我不知道 required=true 到底是什么。然后,无论 required=falserequired=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/

相关文章:

java - 集合层次结构应该是 Collection (Read Only) -> ModulatedCollection

java - 从java文件中删除注释并维护文件结构

java - 在二维数组中交替打印行和列

java - Spring MVC - 从 JSP 提交对象

java - 无法使用从其他 JSP 页面引入的参数

caching - SilverStripe 中可以执行哪些不同类型的 "flush",它们有何不同?

java - 如何保护应用程序免受虚拟机时间跟踪丢失问题的影响?

java - 如何修改现有的 Spring MVC 应用程序以绕过 Spring Security?

hibernate - Spring PagingAndSortingRepository - 按名称查找

url - 博客文章的 rss 提要分页网址是什么样的?