繁体   English   中英

Spring Boot-请求映射将不接受尾部斜杠或多个目录

[英]Spring Boot - Request Mapping won't accept trailing slash or multiple directories

在控制器中使用RequestMapping时,我可以将html文件映射到“ /”,另一个映射到“ / users”。 但是,尝试映射到“ / users /”或“ / users / test”将不起作用。 在控制台中,它将说端点已映射,但是在尝试访问它时,我会看到404错误页面。

package com.bridge.Bitter.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class BitterController {

    //works
    @RequestMapping(value="/")
    public String getMainPage(){
        return "main.html";
    }

    //works
    @RequestMapping(value="/users")
    public String getUsersPage(){
        return "users.html";
    }

    //doesn't work, Whitelabel error page
    @RequestMapping(value="/users/")
    public String getUsersSlashPage(){
        return "users.html";
    }
    //doesn't work, Whitelabel error page
    @RequestMapping(value="/users/test")
    public String getUsersTestPage(){
        return "users.html";
    }

}

我的application.properties仅包含“ spring.data.rest.basePath = / api”。

如果我从@Controller更改为@Rest Controller,则会发生以下情况:

package com.bridge.Bitter.controllers;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@RestController
public class BitterController {

    //works
    @RequestMapping(value="/")
    public String getMainPage(){
        return "main.html";
    }

    //returns a webpage with the text "users.html" on it instead of serving the html
    @RequestMapping(value="/users")
    public String getUsersPage(){
        return "users.html";
    }

    //returns a webpage with the text "users.html" on it instead of serving the html
    @RequestMapping(value="/users/")
    public String getUsersSlashPage(){
        return "users.html";
    }
    //returns a webpage with the text "users.html" on it instead of serving the html
    @RequestMapping(value="/users/test")
    public String getUsersTestPage(){
        return "users.html";
    }

}

将函数从返回字符串更改为返回

new ModelAndView("user.html")

适用于/ users,但是/ users /和/ users / test会出现404错误。

您尝试两次映射相同的路径。 / users与/ users /相同,因此Spring无法解析哪个控制器方法应处理请求。

您可以尝试以下操作:

package com.bridge.Bitter.controllers;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class BitterController {

    @RequestMapping("/")
    public String getMainPage(){
        return "main.html";
    }

    @RequestMapping("/users")
    public String getUsersPage(){
        return "users.html";
    }

    @RequestMapping("/users/test")
    public String getUsersTestPage(){
        return "users.html";
    }
}

另一方面,当您使用@RestController注解时 ,总是返回JSON格式的响应文本,这就是为什么总是得到相同结果的原因。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM