Java Spring MVC:RequestMapping 类和方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22702568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:21:57  来源:igfitidea点击:

Spring MVC: RequestMapping both class and method

javaspringspring-mvcrequest-mapping

提问by Orvyl

Is this possible?

这可能吗?

@Controller
@RequestMapping("/login")
public class LoginController {

    @RequestMapping("/")
    public String loginRoot() {
        return "login";
    }

    @RequestMapping(value="/error", method=RequestMethod.GET)
    public String loginError() {
        return "login-error";
    }

}

I got a 404 error when accessing localhost:8080/projectname/loginbut not in localhost:8080/projectname/login/error.

访问时出现 404 错误,localhost:8080/projectname/login但在localhost:8080/projectname/login/error.

Here's my web.xml project name

这是我的 web.xml 项目名称

<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>

<servlet>
    <description></description>
    <servlet-name>projectname</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>projectname</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

采纳答案by chrylis -cautiouslyoptimistic-

You don't need the /in the method's mapping. Just map it to "".

您不需要/方法的映射中的 。只需将其映射到"".

回答by Sotirios Delimanolis

Yes that is possible. The path in @RequestMappingon the method is relative to the path on the class annotation.

是的,这是可能的。在路径@RequestMapping上的方法是相对于在类注释的路径。

With your current setup, loginRoot()will handle requests to

使用您当前的设置,loginRoot()将处理请求

localhost:8080/projectname/login/

Assuming you don't have anything else in your configuration preventing this.

假设您的配置中没有其他任何内容可以防止这种情况发生。

回答by Binz

You don't need to "/" and you need to also add the request method.

您不需要“/”,您还需要添加请求方法。

@RequestMapping(method = RequestMethod.GET)
public String loginRoot() {
    return "login";
}

Consider using spring mvc tests to make the process of testing these scenarios easier:

考虑使用 spring mvc 测试来简化这些场景的测试过程:

https://spring.io/blog/2012/11/12/spring-framework-3-2-rc1-spring-mvc-test-framework

https://spring.io/blog/2012/11/12/spring-framework-3-2-rc1-spring-mvc-test-framework