添加自定义注解
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 | 12,902 条评论
博客作者 Stoimost_rcSl
Способы сэкономить на шумоизоляции автомобиля в Москве, читай подробности.
Шумоизоляция автомобиля под ключ [url=https://shumoizolyaciya-polnaya.ru/]Шумоизоляция автомобиля под ключ[/url] .
博客作者 Udalenie_ivMi
Эффективные способы устранения царапин на автомобиле, для сохранения привлекательного внешнего вида.
Удаление царапин с кузова автомобиля – [url=https://www.udalenie-czarapin.ru/]https://www.udalenie-czarapin.ru/[/url] .
博客作者 canadian pharmaceuticals online safe
Hmm is anyone else encountering problems with the pictures on this blog loading? I’m trying to determine if its a problem on my end or if it’s the blog. Any suggestions would be greatly appreciated.
博客作者 Ritabkiw
If you need to design [url=https://sign-studio.ru]signature[/url], check out our tips to help make it unique.
博客作者 canadian pharmaceuticals for usa sales
When I initially commented I clicked the "Notify me when new comments are added" checkbox and now each time a comment is added I get several e-mails with the same comment. Is there any way you can remove people from that service? Appreciate it!
博客作者 canada pharmaceuticals online generic
Quality articles is the important to be a focus for the users to pay a visit the web site, that’s what this web page is providing.
博客作者 CharlesBunty
Latest medicine news. Detailed drug knowledge.
[url=https://medsonline365.top/#]online pharmacy no prescription[/url]
Medicine facts here. Drug overview available.
博客作者 спецодежда мужская купить в москве
Спецодежда купить с доставкой blatta.ru
Если Вы искали [url=https://blatta.ru/]рабочий жилет мужской[/url] в интернете, то заходите на наш онлайн проект. Посмотрите каталог нашей супер надежной, уникальной рабочей спецодежды. Завершилось то время, когда покупатели выбирали низкие цены, пренебрегая качеством. В настоящее время, в век инновационных технологий, новинки приходят и в сферу специальной одежды. Оцените сами, заказав наши лучшие образцы.
博客作者 Charlesflelo
look at more info [url=https://samouraiwallet.io]samourai wallet download[/url]
博客作者 Jamescog
Stay tuned benefit of the latest join highlights, including goals, key moments, and skilful analysis.
We wishes update this split with video highlights and timbre moments from the engagement after the equivalent https://www.rayovallecanovsbarcelona.ru/.
博客作者 pharmaceuticals online australia
Very nice post. I definitely love this website. Stick with it!
博客作者 canadian pharmaceuticals
I was curious if you ever thought of changing the layout of your website? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or two images. Maybe you could space it out better?
博客作者 canadian pharmaceuticals online shipping
Hey would you mind letting me know which web host you’re working with? I’ve loaded your blog in 3 different browsers and I must say this blog loads a lot faster then most. Can you suggest a good web hosting provider at a fair price? Thank you, I appreciate it!
博客作者 list of canadian pharmaceuticals online
I get pleasure from, lead to I discovered exactly what I was having a look for. You’ve ended my 4 day long hunt! God Bless you man. Have a nice day. Bye
博客作者 mexican border pharmacies
Hello, the whole thing is going perfectly here and ofcourse every one is sharing facts, that’s really good, keep up writing.