简单的实现登录拦截及统一异常处理(自定义异常)
程序员文章站
2024-01-31 23:43:10
webmvc配置类: 注:registry.addInterceptor(拦截器类对象).addPathPatterns("需要拦截的请求路径").excludePathPatterns("可以放行的请求路径"); 拦截器类,这里为登录拦截 到这里实现了简单的登录拦截,但是上面通过response对 ......
webmvc配置类:
@configuration public class webmvcconfig extends webmvcconfigurationsupport{ @override protected void addinterceptors(interceptorregistry registry) { registry.addinterceptor(new logininterceptor()) .addpathpatterns("/**") .excludepathpatterns("/user/login"); } }
注:registry.addinterceptor(拦截器类对象).addpathpatterns("需要拦截的请求路径").excludepathpatterns("可以放行的请求路径");
拦截器类,这里为登录拦截
public class logininterceptor implements handlerinterceptor{ @override public void aftercompletion(httpservletrequest arg0, httpservletresponse arg1, object arg2, exception arg3) throws exception { // todo auto-generated method stub } @override public void posthandle(httpservletrequest arg0, httpservletresponse arg1, object arg2, modelandview arg3) throws exception { // todo auto-generated method stub } @override public boolean prehandle(httpservletrequest hservletrequest, httpservletresponse hservletresponse, object object) throws exception { // 案例采用session存储登录用户,所以从session获取登录用户
httpsession session = hservletrequest.getsession(); tuser tuser=(tuser)session.getattribute("user");
// 判断session里是否能取出用户 if(tuser==null) { returnerrormessage(hservletresponse, "当前操作需要先进行用户登录"); return false; } return true; } private void returnerrormessage(httpservletresponse response, string errormessage) throws ioexception { response.setcharacterencoding("utf-8"); map<string, object> var=new hashmap<>(); var.put("success", false); var.put("errormessage", errormessage); response.setcontenttype("application/json"); printwriter out = response.getwriter(); objectmapper mapper = new objectmapper(); string jsonofrst =mapper.writevalueasstring(var); out.print(jsonofrst); out.flush(); } }
到这里实现了简单的登录拦截,但是上面通过response对象获取的输出流来写入错误信息,下面采用自定义异常来处理
异常类
public class unloggedexception extends runtimeexception{ private static final long serialversionuid = 181074719716690931l; public unloggedexception() { super("当前操作需要先进行登录"); } }
修改拦截器类的prehandle方法,于是returnerrormessage方法可以去掉了
@override public boolean prehandle(httpservletrequest hservletrequest, httpservletresponse hservletresponse, object object) throws exception { httpsession session = hservletrequest.getsession(); tuser tuser=(tuser)session.getattribute("user"); if(tuser==null) { throw new unloggedexception(); } return true; }
最后配置异常处理类
@controlleradvice @responsebody public class globalexceptionhandler { @exceptionhandler public jsonobject handleexception(exception e) { return actionhelper.responsefailed(e.getmessage()); } }
上面的返回值及actionhelper为我使用的返回工具类,依赖为com.alibaba的fastjson,版本参考1.2.49。
可以根据实际情况修改返回方式及返回值。
此后所有的异常,都可以通过自定义异常的方式,交由异常处理类来进行处理,返回结果。