Announcement Announcement Module
Collapse
No announcement yet.
Regarding interceptor Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Regarding interceptor

    Hi,
    i m new to spring. i understand the interceptor in the following manner.
    if i put the interceptor on views(controller). then every time any request to view will be intercepted by the interceptor. for example if i have a checkValidUserIntercepter. and while requesting any view in my application, first this interceptor will check the valid user. and if user is invalid then it will redirect it to login page.

    Can anyone correct me if i m wrong.
    it will be very much helping to me if anyone can give me an simple example for that.

    Regards,

    Shahzad

  • #2
    Yes, you have the right idea. IN your myapp-servlet.xml file, you would have something like this

    Code:
    	<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    		<property name="interceptors">
    			<list>
    				<ref bean="loginInterceptor"/>
    			</list>
    		</property>
    		<property name="mappings">
    			<props>
    				<prop key="/test.htm">testController</prop>
    			</props>
    		</property>
    	</bean>
    
      	<bean id="loginInterceptor" class="myapp.web.LoginInterceptor">
    		<property name="loginUrl" value="/login.htm"/>
    	</bean>
    Add any mappings you require (and note that it is a good idea to create a separate SimpleUrlHandlerMapping for the /login.htm, so you can route to it from the interceptor without being intercepted again!).

    In your LoginInterceptor's preHandle method, you might have something like this below (here it just tests for the existence of a User object in the session - without a login this would be missing). This routes to your login URL (for which you have a setLoginUrl method in the interceptor, so Spring can inject it).

    Code:
    		User user = (User) WebUtils.getSessionAttribute(request, "user");
    		if (user == null) {
    			RedirectView redirectView = new RedirectView(getLoginUrl());
    			redirectView.setContextRelative(true);
    			ModelAndView modelAndView=new ModelAndView(redirectView);
    			throw new ModelAndViewDefiningException(modelAndView);
                    }
    A slightly simpler version would just return a ModelAndView with the login JSP, avoiding the redirect (but you may actually need to go via a controller, which is why you'd do it the way shown). There are further tweaks for recording and passing through the original 'target' URL the user entered, so that having logged in, they are ten taken to the place they originally intended.

    Hope this helps.

    Comment

    Working...
    X