Spring MVC:RequestMapping 同时对类和方法进行映射

2022-09-02 00:43:40

这可能吗?

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

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

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

}

我在访问时收到404错误,但没有在.localhost:8080/projectname/loginlocalhost:8080/projectname/login/error

这是我的网络.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>

答案 1

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


答案 2

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

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

请考虑使用弹簧 mvc 测试来简化测试这些方案的过程:

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


推荐