其他分享
首页 > 其他分享> > spring – 使用ControllerClassNameHandlerMapping找到不明确的映射

spring – 使用ControllerClassNameHandlerMapping找到不明确的映射

作者:互联网

如何在方法之上将请求映射到没有显式注释的方法?例如,以下请求:

http://somedomain:8080/SampleSpring/access/loginFailed

应该映射到

“AccessController”的“loginFailed”方法,不需要对方法的显式注释,如:

@RequestMapping("/access/loginFailed")

这是我的弹簧配置:

<context:component-scan base-package="com.robikcodes.samplespring"/>
<mvc:annotation-driven/>

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping">
        <property name="basePackage" value="com.robikcodes.samplespring.controller"/>
        <property name="caseSensitive" value="true"/>
        <property name="defaultHandler">
            <bean class="org.springframework.web.servlet.mvc.UrlFilenameViewController"/>
        </property>
</bean>   

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/views/"/>
            <property name="suffix" value=".jsp"/>
</bean>

这是我的控制器:

@Controller
public class AccessController{

    @RequestMapping(method = RequestMethod.GET)
    public void login(ModelMap m) {}

    @RequestMapping(method = RequestMethod.GET)
    public String loginFailed(ModelMap m) {
        m.addAttribute("error", "true");
        return "access/login";
    }

    @RequestMapping(method = RequestMethod.GET)
    public String logout(ModelMap m) {
        m.addAttribute("logoutStatus","true");
        return "access/login";
    }
}

我收到以下错误(似乎只有登录方法被正确映射):

org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Ambiguous mapping found. Cannot map 'accessController' bean method 
public java.lang.String com.robikcodes.samplespring.controller.AccessController.logout(org.springframework.ui.ModelMap)
to {[],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}: There is already 'accessController' bean method
public void com.robikcodes.samplespring.controller.AccessController.login(org.springframework.ui.ModelMap) mapped.

解决方法:

您使用ControllerClassNameHandlerMapping时假设不正确;来自Java doc:

Implementation of HandlerMapping that follows a simple convention for
generating URL path mappings from the class names of registered
Controller beans as well as @Controller annotated beans.

该文档并未说明它也遵循方法名称.比较控制器的“处理程序映射”的主要参考是放在方法上的@RequestMapping注释.因此,使用您的控制器Spring将它们读取为:

{methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}

对于AccessController中具有以下@RequestMapping的所有已定义方法:

@RequestMapping(method = RequestMethod.GET)

这就是你看到模棱两可的例外的原因.

据我了解,最干净的解决方案是使用@RequestMapping的value属性来定义不同的请求URI.实际上并不建议尝试将请求URI映射到方法名称的解决方案.

标签:spring-4,spring,spring-mvc,annotations
来源: https://codeday.me/bug/20190831/1774013.html