简体   繁体   中英

How to use Spring MVC handler interceptors in Controller?

I am working on Spring MVC controller project. I have a JSP page which contains certain forms and people will type certain entries in it and then press submit button.

As soon as I hit this url on the browser, it will show the JSP page -

http://localhost:8080/testweb/testOperation

Now what I am supposed to do is - I will intercept the IP Address from the request header as soon as the above url is hit and if that IP Address is in my access list, then only I will show my actual jsp page otherwise I will show an error JSP page.

And I was reading about Spring MVC Handler Interceptors here but not sure how would I implement this in my example as this is my first time with Spring MVC so confuse little bit.

Now below is my code base - As soon as I hit this url on the browser -

http://localhost:8080/testweb/testOperation

It automatically goes to below method and then it shows me my testOperation jsp page on the browser and it works fine.

@RequestMapping(value = "testOperation", method = RequestMethod.GET)
public Map<String, String> testOperation() {
    final Map<String, String> model = new LinkedHashMap<String, String>();
    return model;
}

How would I do this using Spring MVC Handler Interceptors if possible at all?

Is this possible to do somehow?

Below is the code I use to extract IP Address from the header -

   String ipAddress = request.getHeader("X-FORWARDED-FOR");  
   if (ipAddress == null) {  
       ipAddress = request.getRemoteAddr();  
   }

   System.out.println(ipAddress);

This should be possible to implement using either interceptors or servlet filters. Using an interceptor, the code would look somewhat like this:

@Component
public class IpCheckingInterceptor extends HandlerInterceptorAdapter {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // Your header-checking code
        String ipAddress = request.getHeader("X-FORWARDED-FOR");  
        if (ipAddress == null) {  
            ipAddress = request.getRemoteAddr();  
        }
        if (<ipAddress not OK>) {
            throw new ForbiddenException("You are not allowed to access this page");
        }
        return true;
    }
}

Depending on how your Spring app is configured, you may need to register the interceptor in your XML config, or it could get registered automatically based on conventions - some examples can be found here: Is it possible to wire a Spring MVC Interceptor using annotations?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM