Spring MVC:RequestMapping类和方法

时间:2014-03-28 01:33:31

标签: java spring spring-mvc request-mapping

这可能吗?

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

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

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

}

访问localhost:8080/projectname/login时遇到404错误,但localhost:8080/projectname/login/error没有。

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

3 个答案:

答案 0 :(得分:26)

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

答案 1 :(得分:11)

你不需要&#34; /&#34;你还需要添加请求方法。

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

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

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

答案 2 :(得分:6)

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

根据您当前的设置,loginRoot()将处理

的请求
localhost:8080/projectname/login/

假设您的配置中没有其他任何内容阻止此操作。

相关问题