Exercise 22: Creating Interceptors - jkneal/spring-angular-train GitHub Wiki

Goals

Learn how to create controller interceptors

Instructions

  1. In edu.train, create a new controller interceptor named 'UserSessionInterceptor'

  2. In the method preHandle, add the following code. After you are done remove this code from edu.train.shop.ShopController#getAllProducts

  if (request.getParameter("user") != null) {
    request.setAttribute("userSession", new UserSession(request.getParameter("user")));
  }
  return true;
  1. Now in the method postHandle, check if the view name on the modelAndView (argument) is 'shop/add-product'. If so then also check if the canAddProducts method of the user session is not true (retrieve from the request attribute). If both conditions are met, then set the view name to 'access-error' on modelAndView. Make sure to also check if modelAndView or the user session object are null. If either one are, return without doing the above check.

  2. In edu.train, add a class named 'TrainWebConfig' that extends org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter. Add this as a Spring configuration class. Finally register the interceptor created in step 1 (to intercept all controllers)

VERIFICATION

  1. Start the training application and go to the app home page
  2. Click on the link 'Ex 22'. Verify the shop page is displayed with the message "Welcome thmeks"
  3. Now go back to the menu and click on the link 'Ex 22 No Access'. Verify you see a page with the message "Sorry. You do not have access to the requested page."