java - How to create my own filter with Spring MVC? -
i use spring mvc (4.0.1) backend rest services , angularjs frontend.
every request server backend has http-header session id
i can read header in server backend following code:
@autowired protected httpservletrequest request; string xheader=request.getheader("x-auth-token"); //returns sessionid header
now call method getpermission(xheader)
return true or false. if user exists in db return true else false!
i want create filter behavior, checks every request if user have permission access controllers! if method returns false should send 401 error , not reach controller!
how can , create own filter? use java config , no xml.
i think must add filter here:
public class webinitializer extends abstractannotationconfigdispatcherservletinitializer { @override protected filter[] getservletfilters() { myownfilter=new myownfilter(); return new filter[] {myownfilter}; } }
alternative filters, can use handlerinterceptor
.
public class sessionmanager implements handlerinterceptor{ // method called before controller @override public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception { string xheader = request.getheader("x-auth-token"); boolean permission = getpermission(xheader); if(permission) { return true; } else { response.setstatus(httpstatus.unauthorized.value()); return false; // above code send 401 no response body. // if need 401 view, redirect instead of // returning false. // response.sendredirect("/401"); // assuming have handler mapping 401 } return false; } @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 { } }
and add interceptor webmvc config.
@enablewebmvc @configuration public class webconfig extends webmvcconfigureradapter { @bean sessionmanager getsessionmanager() { return new sessionmanager(); } @override public void addinterceptors(interceptorregistry registry) { registry.addinterceptor(getsessionmanager()) .addpathpatterns("/**") .excludepathpatterns("/resources/**", "/login"); // assuming put serve static files /resources/ mapping // , pre login page served /login mapping } }
Comments
Post a Comment