0

我正在尝试在 Spring 中使用拦截器,我需要在所有控制器上实现一个拦截器,以便在调用它们时处理特定的逻辑。

网页.xml:

<servlet>
    <servlet-name>MyApp</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>MyApp</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>

应用程序上下文.xml:

<bean id="handlerMapping"
      class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="interceptors">
        <list>
            <ref bean="warningInterceptor"/>
        </list>
    </property>
    <property name="mappings">
        <value>*.do</value>
    </property>
</bean>

<bean id="warningInterceptor" class="security.WarningInterceptor">
    <property name="activeApp" value="${myWarning}"/>
</bean>

Java 类:WarningInterceptor

public class WarningInterceptor extends HandlerInterceptorAdapter {

private int activeApp;
public int getActiveApp() { return activeApp; }
public void setActiveApp(int activeApp) {this.activeApp = activeApp;}

public boolean preHandle(
        HttpServletRequest request,
        HttpServletResponse response,
        Object handler) throws Exception {

    if (getActiveApp() == 0) {
        return true;
    } else {
        response.sendRedirect("/myWarning.do");
        return false;
    }
}

当我启动 MyApp 时,我总是收到此错误:

org.springframework.beans.factory.BeanCreationException:在 ServletContext 资源 [/WEB-INF/applicationContext.xml] 中创建名称为“handlerMapping”的 bean 时出错:bean 初始化失败;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named '' is defined

4

2 回答 2

1

SimpleUrlHandlerMapping 的 mappings 属性应该将 URL 映射到处理程序,并且您只列出了一个 URL 模式。它应该是这样的:

 <property name="mappings">
    <props>
       <prop key="*.do">myAppController</prop>
     </props>
   </property>

编辑:这是一个更好的例子。这个使用值标签而不是道具(任何一种方式都有效)。

<bean class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
   <property name="mappings">
    <value>
       *.do=myAppController
    </value>
   </property>
</bean>

<bean id="myAppController" 
    class="com.example.MyAppController" />
于 2012-05-17T14:38:03.483 回答
0

您是否尝试过在拦截器中为 activeApp 变量添加 getter/setter 方法。(警告拦截器)

于 2012-05-17T13:56:22.260 回答