Marta
Marta

Reputation: 291

Interceptors in Spring 2.5

I'm triying to use interceptors in Spring, I need to implement an interceptor on all my Controllers to handle specific logic when their are called.

web.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>

applicationContext.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 class: 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;
    }
}

When I start MyApp I'm always getting this error:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'handlerMapping' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named '' is defined

Upvotes: 0

Views: 2064

Answers (2)

acvcu
acvcu

Reputation: 2506

The mappings property of SimpleUrlHandlerMapping should map URLs to handlers, and you only have a URL pattern listed. It should be something like this:

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

EDIT: Here's a better example. This one uses the value tag instead of prop (either way works).

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

<bean id="myAppController" 
    class="com.example.MyAppController" />

Upvotes: 1

Eshan Sudharaka
Eshan Sudharaka

Reputation: 607

Have you tried with adding a getter/setter methods for activeApp variable in your interceptor. (WarningInterceptor)

Upvotes: 0

Related Questions