java - How to use Spring MVC handler interceptors in Controller? -


i working on spring mvc controller project. have jsp page contains forms , people type entries in , press submit button.

as hit url on browser, show jsp page -

http://localhost:8080/testweb/testoperation 

now supposed - intercept ip address request header above url hit , if ip address in access list, show actual jsp page otherwise show error jsp page.

and reading spring mvc handler interceptors here not sure how implement in example first time spring mvc confuse little bit.

now below code base - hit url on browser -

http://localhost:8080/testweb/testoperation 

it automatically goes below method , shows me testoperation jsp page on browser , 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 using spring mvc handler interceptors if possible @ all?

is possible somehow?

below code use extract ip address header -

   string ipaddress = request.getheader("x-forwarded-for");      if (ipaddress == null) {          ipaddress = request.getremoteaddr();      }     system.out.println(ipaddress); 

this should possible implement using either interceptors or servlet filters. using interceptor, code this:

@component public class ipcheckinginterceptor extends handlerinterceptoradapter {     public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception {         // header-checking code         string ipaddress = request.getheader("x-forwarded-for");           if (ipaddress == null) {               ipaddress = request.getremoteaddr();           }         if (<ipaddress not ok>) {             throw new forbiddenexception("you not allowed access page");         }         return true;     } } 

depending on how spring app configured, may need register interceptor in xml config, or registered automatically based on conventions - examples can found here: is possible wire spring mvc interceptor using annotations?


Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -