Saturday, 8 April 2017

How to write Interceptor in Spring MVC or Spring Web


1. Provide the below ones in the dispatcher-servlet.xml containing in your project

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:tx="http://www.springframework.org/schema/tx"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:security="http://www.springframework.org/schema/security"
 xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
  http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd">

 <security:global-method-security pre-post-annotations="enabled" />

 <context:component-scan base-package="com" />

 <context:property-placeholder location="file:///${configs}//*.properties" file-encoding="UTF-8" />

 <tx:annotation-driven transaction-manager="transactionManager" />

 <bean id="localeResolver"  class="org.springframework.web.servlet.i18n.SessionLocaleResolver">
  <property name="defaultLocale" value="en" />
 </bean>

 <bean id="localeChangeInterceptor"  class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
  <property name="paramName" value="language" />
 </bean>


 <mvc:interceptors>
  <mvc:interceptor>
   <mvc:mapping path="/**" />
   <mvc:exclude-mapping path="/css/**" />
   <mvc:exclude-mapping path="/js/**" />
   <mvc:exclude-mapping path="/bootstrap/**" />
   <mvc:exclude-mapping path="/img/**" />
   <mvc:exclude-mapping path="/fonts/**" />
   <bean class="com.UserInterceptor" />
  </mvc:interceptor>

  <ref bean="localeChangeInterceptor"/>
 </mvc:interceptors>

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

  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>

 <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     <property name="maxUploadSize" value="100000"/>
 </bean>
</beans>

2.Create a interceptor class as like below

import java.security.Principal;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.core.HttpHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.dto.UserVO;
import com.service.AuthorizationService;

public final class UserInterceptor implements HandlerInterceptor {


 public static class ACCEPTED_URLS_NO_CODE {
  public static final String ROOT = "/";
  public static final String SET_EFFECTIVE_CODE = "/set-effective-code/";
  public static final String ERROR = "/error/";


  public static boolean accept(String path) {
   return ( ROOT.equals(path) || SET_EFFECTIVE_CODE.equals(path) || ERROR.equals(path) );
  }
 }

 private static final Logger LOGGER = LoggerFactory.getLogger(UserInterceptor.class);
 private static final char PROXY_PRINCIPAL_DELIMITER = ',';

 @Value("${principal.proxy}")
 private boolean proxyPrincipal;

 @Autowired
 private AuthorizationService authorizationService;

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

  HttpSession session = request.getSession();
  Principal p = request.getUserPrincipal();
  if (p == null) {
   LOGGER.error("Principal is missing!");
   throw new Exception("Principal is missing!");
  }

  String userName = p.getName();
  if (proxyPrincipal) {
   int index = userName.indexOf(PROXY_PRINCIPAL_DELIMITER) + 1;
   userName = userName.substring(index, userName.indexOf(PROXY_PRINCIPAL_DELIMITER, index));
  }

  UserVO userData = (UserVO) session.getAttribute("currentUser");

  if (userData == null || !userData.getUserName().equals(userName)) {
   userData = authorizationService.getUser(userName);
   session.setAttribute("currentUser", userData);
  }

  if (userData.getTravellerCode() == null) {
   String selectedCode = "T1";

   if (selectedCode != null) {
    userData.selectTravellerCode(selectedCode);
   } else if (!ACCEPTED_URLS_NO_CODE.accept(request.getServletPath()) ) {
        response.addHeader(HttpHeaders.LOCATION, request.getContextPath() + ACCEPTED_URLS_NO_CODE.ROOT);
response.setStatus(HttpServletResponse.SC_FOUND);
    return false;
   }
  }
  return true;
 }

 @Override
 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
 }

 @Override
 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
 }
}

No comments:

Post a Comment