Thursday, September 13, 2012

Intercepting requests (annotation based request mapping)

       Spring Interceptors has the ability to pre-handle and post-handle the web requests. Each interceptor class should extend the HandlerInterceptorAdapter class. Here we will create a Login Interceptor by extending the HandlerInterceptorAdapter class. You can override any of the three callback methods preHandle(), postHandle() and afterCompletion(). As the names indicate the preHandle() method will be called before handling the request, the postHandle() method will be called after handling the request and the afterCompletion() method will be called after rendering the view.

First create "LoginInterceptor" java class:
package com.handysofts.mvcinterceptor.mvc;

import com.handysofts.mvcinterceptor.beans.UserBean

import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.ModelAndViewDefiningException;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

/**
 * @author Vasif Mustafayev
 * @since 2012.09.13
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

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

  UserBean userBean = (UserBean) WebUtils.getSessionAttribute(request, "userBean");
  if (userBean == null) {
   ModelAndView modelAndView = new ModelAndView("public-main");
   throw new ModelAndViewDefiningException(modelAndView);
  }
  else {
   return true;
  }
 }

}

Here before request mapped to controller will checked for session. When  user logged in then we add "userBean" object to session and here we check it , so if "userBean" object is null then user will see login page.
Now we need register this interceptor on xml file. Open your project <dispatchername>-servlet.xml file and add following lines:
    <mvc:interceptors>
     <mvc:interceptor>
         <mvc:mapping path="/dashboard/**"/>
         <bean class="com.handysofts.mvcinterceptor.mvc.LoginInterceptor"></bean>
     </mvc:interceptor>
    </mvc:interceptors>

Now, all requests which begins with "/dashboard" will go throw interceptor [like as proxy :) ], but other links will go directly to controller. For example if u have controller as @RequestMapping ("/dashboard/main") then this request will go throw interceptor (it will check session for "userBean" object if there is object with that name then request will go to our controller ,else it will go to "public-main" page)
Example2: If u have a controller as 
@RequestMapping ("/public/main") then this request will go to controller directly.
So, why spring is the best framework ;-)

No comments:

Post a Comment