繁体   English   中英

“ http:// localhost / app / hello”和“ http:// localhost / app / hello /”之间有什么区别?

[英]What's the difference between “http://localhost/app/hello” and “http://localhost/app/hello/”?

我已经写了一个基于Spring MVC的控制器。

@Controller
@RequestMapping("/hello")
public class JsonController {

    @RequestMapping(value="/",method=RequestMethod.GET)
    @ResponseBody
    public Person service(){
        Person person=new Person();
        person.setId(3);
        person.setName("666");
        return person;
}

当我访问“ http:// localhost / app / hello ”时,我得到404; 当我访问“ http:// localhost / app / hello / ”时,我得到202 OK。 http:// localhost / app / hello ”和“ http:// localhost / app / hello / ”有什么区别?

看你的控制器代码

@RequestMapping("/hello")
public class JsonController

您的控制器具有url映射->“ / hello”

并且操作(服务)URL映射为“ /”

@RequestMapping(value="/",method=RequestMethod.GET)
    @ResponseBody
    public Person service()

现在,每当我们为控制器提供映射时,控制器的每个操作都需要将控制器URL路径作为前缀(如果URL映射是在控制器中定义的),就像您提到的控制器映射使用“ / hello”和动作服务 URL映射使用“ /”,因此当您需要访问服务操作时->您需要控制器的基本路径(如果在控制器中定义了请求URL映射)+操作URL映射

-> "/hello" + "/"   => "/hello/"

因此,在访问URL“ http:// localhost / app / hello / ”的情况下,它很容易找到service操作并返回响应

现在,当您尝试访问URL“ http:// localhost / app / hello ”时,URL映射会搜索此映射并在您的控制器映射中找到它(因为在您的情况下已定义),但是没有为此定义任何操作,为什么正在获取404。

您可以将其定义为默认操作,例如:

@RequestMapping(method=RequestMethod.GET)
    public Person defaultAction() { 
----your code
}

所以现在如果您点击“ http:// localhost / app / hello ”,这将返回有效响应,而不是404

我想这与您的tomcat重定向配置有关。 尝试在context.xml中包含以下属性

mapperContextRootRedirectEnabled

描述:如果启用,则如有必要,映射器(而不是默认Servlet)将重定向对Web应用程序上下文根的请求(添加斜杠)。 这更有效,但具有确认上下文路径存在的副作用。 如果未指定,则使用默认值true。

mapperDirectoryRedirectEnabled

描述:如果启用,则如有必要,映射器(而不是默认Servlet)将重定向对Web应用程序目录的请求(添加斜杠)。 这效率更高,但具有确认目录存在的副作用。 如果未指定,则使用默认值false。

参考: https : //tomcat.apache.org/tomcat-7.0-doc/config/context.html#Context_Parameters

暂无
暂无

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

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