添加自定义注解
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 | 28,626 条评论
博客作者 viagra generic online pharmacy
Hi mates, how is all, and what you wish for to say about this piece of writing, in my view its genuinely amazing in support of me.
博客作者 canadian pharmaceuticals online safe
Hello, this weekend is good for me, because this moment i am reading this great informative article here at my home.
博客作者 Lexaqigd
По Минску доступен круглосуточная служба эвакуатора. Ознакомьтесь с тем, как вызвать [url=https://evakuator-minsk-24.by]эвакуатор минск[/url] без задержек.
博客作者 walmart pharmacy online
Hello, Neat post. There is a problem together with your website in web explorer, might check this? IE nonetheless is the marketplace chief and a big portion of folks will leave out your wonderful writing because of this problem.
博客作者 Психолог gwb
Профессиональный психотерапевт в сети. Консультации предоставляется 24/7. Конфиденциально, действенно. Первая консультация -50% от цены. Не откладывайте на потом! https://w-495.ru/
博客作者 Психолог fdq
Надежный психоаналитик дистанционно. Терапия предоставляется в любое время. Приватно, действенно. Первая консультация -50% от цены. Сделайте шаг к улучшению! https://w-495.ru/
博客作者 Психолог qpu
Надежный специалист по психическому здоровью онлайн. Решение проблем доступна в любое время. Анонимно, эффективно. Выгодные цены. Сделайте шаг к улучшению! https://w-495.ru/
博客作者 pharmacy online shopping
Howdy! This is kind of off topic but I need some advice from an established blog. Is it very difficult to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about creating my own but I’m not sure where to begin. Do you have any tips or suggestions? Thanks
博客作者 drugstore online shopping
Thanks for every other excellent article. Where else could anybody get that type of information in such a perfect means of writing? I have a presentation next week, and I’m at the search for such info.
博客作者 online canadian pharcharmy
I like what you guys are usually up too. Such clever work and coverage! Keep up the wonderful works guys I’ve included you guys to my personal blogroll.
博客作者 Georgetor
пояснения https://mega555-moriarti.com
博客作者 canada pharmaceuticals online
Excellent blog post. I absolutely appreciate this website. Continue the good work!
博客作者 canadian pharmaceuticals online
What’s up it’s me, I am also visiting this website on a regular basis, this web page is truly pleasant and the visitors are really sharing nice thoughts.
博客作者 viagra pharmacy 100mg
Thanks for finally talking about > %blog_title% < Liked it!
博客作者 wbahis giriş
Thank you for content. Area rugs and online home decor store. Hello Administ . Seo Paketi Skype: ByuMuT@KRaLBenim.Com –– live:by_umut