添加自定义注解
package org.book.configuration.aop; import java.lang.annotation.*; @Documented @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface NoCheckLogin { }
创建一个SpringMvcHandler 类,继承HandlerInterceptorAdapter
package org.book.configuration.Handler; import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.book.common.JsonResult; import org.book.configuration.aop.NoCheckLogin; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.PrintWriter; import java.lang.reflect.Method; @Slf4j public class SpringMvcHandler extends HandlerInterceptorAdapter { public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { } public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { } public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HandlerMethod hm = null; Method method = null; if(handler instanceof HandlerMethod) { hm = (HandlerMethod) handler; method = hm.getMethod();// 获取方法 } else { return true; } // 该方法是否添加 允许未登录访问注解 if (method !=null && method.isAnnotationPresent(NoCheckLogin.class)) { // 不拦截 return true; } String name = (String) request.getSession().getAttribute("user"); if (name != null) { return true; } else { response.setCharacterEncoding("UTF-8"); response.setContentType("application/json; charset=utf-8"); PrintWriter out = null; try { out = response.getWriter(); out.append(new JSONObject().toJSONString(JsonResult.renderFail("用户未登录")) ); }catch (Exception e){ out = response.getWriter(); out.append(new JSONObject().toJSONString(JsonResult.renderError("后台出错"))); log.info(e.getStackTrace().toString()); } return false; } } }
被@NoLoginCheck注解的方法不会被拦截在springmvc配置文件配置拦截路径和排除路径
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/**"/> <mvc:mapping path="/"/> <mvc:mapping path="/index.jsp"/> <mvc:exclude-mapping path="/assets/**"/> <mvc:exclude-mapping path="/images/**"/> <bean class="org.book.configuration.Handler.SpringMvcHandler"></bean> </mvc:interceptor> </mvc:interceptors>
1)预处理preHandle()方法
用户发送请求时,先执行preHandle()方法。会先按照顺序执行所有拦截器的preHandle方法,一直遇到return false为止,比如第二个preHandle方法是return false,则第三个以及以后所有拦截器都不会执行。若都是return true,则执行用户请求的url方法。
2)后处理postHandle()
方法调用了Service并返回ModelAndView,但未进行页面渲染,可以在这里继续修改ModelAndView
3)返回处理afterCompletion()
方法已经渲染了页面,在afterCompletion中,可以根据ex是否为null判断是否发生了异常,进行日志记录。注:一般使用preHandle这个拦截器进行预处理,对url进行请求拦截
Comments | 29,499 条评论
博客作者 DavidLargo
Get drug info. Find medicine information.
[url=https://medsonline365.top/46/#]lasix cheap[/url]
Get pill details. Medicine leaflet available.
博客作者 promocodedaurb
[url=https://t.me/s/megamarket_promokod_skidka/585]фрибут винлайн промокод[/url]
博客作者 promocodedaurb
[url=https://t.me/s/megamarket_promokod_skidka/23]промокод 90 дней[/url]
博客作者 Cedricmor
important link [url=https://cakewallet.cc]coinomi кошелек официальный сайтAds[/url]
博客作者 pharmaceuticals online australia
Simply want to say your article is as astonishing. The clarity in your post is just nice and i can assume you are an expert on this subject. Well with your permission allow me to grab your feed to keep updated with forthcoming post. Thanks a million and please keep up the enjoyable work.
博客作者 promokoddaurb
[url=https://t.me/yoni_chelny/12]интимный массаж челны[/url]
博客作者 promokoddaurb
[url=https://t.me/s/yoni_chelny/13]йони и лингам массаж[/url]
博客作者 capcutdaurb
[url=https://t.me/fontscapcutn/1291]nord шрифт скачать русский кап кут[/url]
博客作者 capcutdaurb
[url=https://t.me/fontscapcutn/1188]скачать шрифт в кап кут cheri[/url]
博客作者 simkartidaurb
[url=https://t.me/karty_sim_optom/29]купить сим карту оператора[/url]
博客作者 simkartidaurb
[url=https://t.me/s/karty_sim_optom/13]сим карта для интернета купить билайн[/url]
博客作者 eksdaurb
[url=https://t.me/s/moskva_ekskursii/56]экскурсии по москве 6 сентября[/url]
博客作者 eksdaurb
[url=https://t.me/s/moskva_ekskursii/145]экскурсии для 1 класса в москве интересные[/url]
博客作者 buy generic viagra online
Having read this I thought it was very informative. I appreciate you finding the time and effort to put this content together. I once again find myself spending a significant amount of time both reading and commenting. But so what, it was still worth it!
博客作者 Genaiuvk
Фермерам будет полезна советы по выбору [url=https://factos.ru]зернодробилка для домашнего хозяйства[/url]. Узнайте, какие функции важны.