添加自定义注解
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,688 条评论
博客作者 online pharmacies
Hey there! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly? My blog looks weird when viewing from my iphone 4. I’m trying to find a theme or plugin that might be able to correct this problem. If you have any suggestions, please share. Many thanks!
博客作者 canadian pharmaceuticals online
I could not resist commenting. Exceptionally well written!
博客作者 pharmaceuticals online australia
Link exchange is nothing else however it is simply placing the other person’s website link on your page at suitable place and other person will also do similar in favor of you.
博客作者 https://radioaktiv.ru/smd_resistor.html
https://radioaktiv.ru/smd_resistor.html
博客作者 Genajnxn
Планируете покупку [url=https://factos.ru]молотковая дробилка[/url]? Узнайте больше о преимуществах этого модели дробилки для надежного измельчения зерна.
博客作者 panacea pharmacy
This paragraph will help the internet users for creating new blog or even a weblog from start to end.
博客作者 Dwightesogy
Use Cases for Effective Numbers
Conclusion
A essential covey is an innovative deciphering that enhances communication, https://giaoduckinangsaomai.com/chuong_trinh_hoc/chuong-trinh-hoc-1/?unapproved=91977&moderation-hash=f18fa1435ac671dd8262aeeb12741396#comment-91977 donation a area of benefits for individuals and businesses alike. Its obedience, cost-effectiveness, and solitude features make it an pleasing opportunity in place of anyone looking to benefit their communication capabilities. As technology continues to evolve, accepted numbers longing likely sport an increasingly quintessential role in shaping how we connect and communicate in a globalized world.
博客作者 JosephNaigh
Experts predict a competitive trial with Fulham liable to having the sharpness necessary to their higher status in the unite and recent form. However, Birmingham’s at ease profit could traverse exchange for an electrifying encounter.
Predicted Mark: Birmingham 1 – 2 Fulham https://birminghamvsfulham.ru/.
博客作者 canadian government approved pharmacies
I am extremely impressed with your writing skills as well as with the layout on your weblog. Is this a paid theme or did you modify it yourself? Anyway keep up the nice quality writing, it is rare to see a nice blog like this one nowadays.
博客作者 https://www.dogsfiles.com/index.php?ind=dogsbase&breed=57
https://www.dogsfiles.com/index.php?ind=dogsbase&breed=57
博客作者 mexican border pharmacies
Its like you read my mind! You seem to know so much about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a bit, but other than that, this is magnificent blog. A great read. I’ll definitely be back.
博客作者 ThomasKathy
Вентиляция это важный нюанс обеспечения комфортного и здорового локального климата в помещениях. Для эффективной работы системы вентиляции необходимо верно выбирать комплектующие и девайсы, которые помогут обеспечить подходящий уровень воздухообмена и очистки воздуха. В данном посте мы рассмотрим главные элементы и девайсы, применяемые в системах вентиляции.
Вентиляторы это ключевые элементы вентиляционных систем. Они обеспечивают нужную тягу и движение воздуха в помещениях. Существуют разные типы вентиляторов:
Воздуховоды это каналы, через которые происходит перемещение воздуха. Они бывают:
Решетки и диффузоры предусмотрены для рассредотачивания воздуха по помещению и могут быть различной формы и размера.
博客作者 Belkchind
[url=https://cheapsmartphonebuy.link]MAC PRO IPAD MINI[/url]
iPhone 6s Plus, 64GB, Rose Gold 150.00$ iPhone 6s Plus, 64GB, Gold 150.00$ iPhone 6s Plus, 128GB, Space Gray 180.00$ iPhone 6s Plus, 128GB, Silver 180.00$ iPhone 6s Plus, 128GB, Rose Gold 180.00$ iPhone 6s Plus, 128GB, Gold 180.00$ iMac 27-inch, 3.3GHz, 2TB 800.00$ iPhone XR, 128GB, Blue 250.00$ iPhone XR, 128GB, Yellow 250.00$ iPhone XR, 128GB, Coral 250.00$ iPhone XR, 128GB, Red 250.00$ iPhone XR, 256GB, White 300.00$ iPhone XR, 256GB, Black 300.00$ iPhone XR, 256GB, Blue 300.00$ iPhone XR, 256GB, Yellow 300.00$ iPhone 6s Plus, 32GB, Silver 100.00$ MacBook Air 13-inch, 1.6GHz, 256GB 450.00$ Mac
[url=https://cheapsmartphonebuy.link] Cheap iPhone SE 2020 Cheap iPhone XS Max[/url]
博客作者 canadian pharmaceuticals
Ahaa, its nice dialogue about this article at this place at this website, I have read all that, so at this time me also commenting at this place.
博客作者 Pashayioh
Хотите узнать больше? Переходите на [url=https://hzaim.ru]сайт[/url], где представлена все нужные данные о займах и способах их получения.