【问题标题】:What's the difference between "http://localhost/app/hello" and "http://localhost/app/hello/"?“http://localhost/app/hello”和“http://localhost/app/hello/”有什么区别?
【发布时间】:2018-01-02 15:52:38
【问题描述】:

我已经写了一个基于 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/”有什么区别?

【问题讨论】:

  • 嗯,不同之处在于您将/ 的末尾映射到函数service()@RequestMapping(value="/",method=RequestMethod.GET),而末尾没有/ 的URL 被映射为空。如果你调用一个 url,其余的 api 没有分配给你,自然会得到 404。

标签: java spring spring-mvc tomcat server


【解决方案1】:

查看您的控制器代码

@RequestMapping("/hello")
public class JsonController

你的控制器有 url 映射 -> "/hello"

而action(service) url映射为“/”

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

现在每当我们为控制器提供映射时,控制器的每个操作都需要控制器 URL 路径作为前缀(如果 URL 映射在控制器中定义),正如您提到的 控制器 映射与 "/hello" 和操作 service"/" 的 url 映射 因此,当您需要访问 service 操作时 -> 您需要控制器的基本路径(如果控制器中定义了请求 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

【讨论】:

    【解决方案2】:

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

    ma​​pperContextRootRedirectEnabled

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

    ma​​pperDirectoryRedirectEnabled

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

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

    【讨论】:

      猜你喜欢
      • 2020-12-18
      • 1970-01-01
      • 2011-09-28
      • 2016-11-28
      • 2021-05-08
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      • 2011-11-15
      相关资源
      最近更新 更多