Exercise 22: Creating Interceptors - jkneal/spring-angular-train GitHub Wiki
Goals
Learn how to create controller interceptors
Instructions
-
In
edu.train, create a new controller interceptor named 'UserSessionInterceptor' -
In the method
preHandle, add the following code. After you are done remove this code fromedu.train.shop.ShopController#getAllProducts
if (request.getParameter("user") != null) {
request.setAttribute("userSession", new UserSession(request.getParameter("user")));
}
return true;
-
Now in the method
postHandle, check if the view name on themodelAndView(argument) is 'shop/add-product'. If so then also check if thecanAddProductsmethod 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' onmodelAndView. Make sure to also check if modelAndView or the user session object are null. If either one are, return without doing the above check. -
In
edu.train, add a class named 'TrainWebConfig' that extendsorg.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
- Start the training application and go to the app home page
- Click on the link 'Ex 22'. Verify the shop page is displayed with the message "Welcome thmeks"
- 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."