java - 如果找不到,@PathVariable 可以返回 null 吗?

标签 java spring-3 spring-annotations path-variables

如果路径变量不在 url 中,是否可以使 @PathVariable 返回 null?否则我需要做两个处理程序。一个用于/simple,另一个用于/simple/{game},但如果没有定义游戏,两者都做同样的事情我从列表中选择第一个但是如果有是定义的游戏参数然后我使用它。

@RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(@PathVariable("example") String example,
            HttpServletRequest request) {

这就是我尝试打开页面时得到的结果/simple:

Caused by: java.lang.IllegalStateException: Could not find @PathVariable [example] in @RequestMapping

最佳答案

正如其他人已经提到的那样,当您明确提到路径参数时,您不能期望它们为空。但是,您可以执行以下操作作为解决方法 -

@RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(@PathVariable Map<String, String> pathVariablesMap,
            HttpServletRequest request) {
    if (pathVariablesMap.containsKey("game")) {
        //corresponds to path "/simple/{game}"
    } else {
        //corresponds to path "/simple"
    }           
}

如果您使用 Spring 4.1 和 Java 8,您可以使用 @RequestParam 中支持的 java.util.Optional , @PathVariable , @RequestHeader@MatrixVariable在 Spring MVC 中

@RequestMapping(value = {"/simple", "/simple/{game}"}, method = RequestMethod.GET)
public ModelAndView gameHandler(@PathVariable Optional<String> game,
            HttpServletRequest request) {
    if (game.isPresent()) {
        //game.get()
        //corresponds to path "/simple/{game}"
    } else {
        //corresponds to path "/simple"
    }           
}

关于java - 如果找不到,@PathVariable 可以返回 null 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5493767/

相关文章:

Java JButton action执行卡住

serialization - 带有 ViewScoped 和 Spring 服务的 ManagedBean 中的 NotSerializableException

java - Spring Boot 注解配置的时序问题

java - 如何将 xml 符号转换为基于注释的符号 : Spring - Java

spring-mvc - 在Spring 3.1中可以<mvc :interceptors> be used in conjunction with @Configuration

使用 Active Directory 用户主体名称的 Java Kerberos 身份验证

java - 当字符串已经被初始化和分配时拒绝声明

java - 如何在 Android 中动态更改菜单项文本

spring - 如何配置 Spring @ControllerAdvice 将应用于哪些 Controller ?

comparison - EJB 3.1 或 Spring 3.. 什么时候选择哪一个?