废话不多说 , 直接上代码 , 相信都能看的懂
一 一 两布 , 第一步 , 创建 intercepteur 拦截
package com.cy.example.config; import javax.servlet.http.httpservletRequest; Importer javax.servlet.http.httpSession; import org.slf4j.logger; importation org.slf4j.loggerfactory; org.springframework.web.servlet.handlerInterceptor; import org.springframework.web.servlet.modelandView; public class LoginInterceptor implémente handlerInterceptor {private logger = loggerfactory.getLogger (loginInterceptor.class); public void Posthandle (HttpServLetRequest Request, HttpServletResponse Response, Handler, ModelandView ModelAndView) lève une exception {// TODO GÉNÉRATEUR AUTO-GÉNÉRÉ STUP} public Void AfterCompletion (HttpServletRequest Demande, HTTPSERVLERSPONSE Réponse, Handler d'objet, exception ex) Boolean Prehandle (HttpServLetRequest Request, HttpServletResponse Response, Handler d'objet) lève une exception {// TODO Méthode générée automatique Stub // 获取 Session httpSession session = request.getSession (true); Logger.info ("---- 进入登录拦截器 --url :" + request.getServletPath () + "-----"); if (session.getAttribute (webConfig.login_user) == null) {logger.info ("------ 跳转到 Login 页面 -----"); réponse.SendRedirect (request.getContextPath () + "/ index"); retourne false; } else {session.setAttribute (webConfig.login_user, session.getAttribute (webConfig.login_user)); Retour Vrai; }}}第二步 , 注册创建的拦截器
package com.cy.example.config; import org.springframework.context.annotation.configuration; import org.springframework.web.servlet.config.annotation.defaultservlethandlerConfigurer; import org.springframework.web.servlet.config.annotation.Interceptor org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.webmvcconfigurerAdapter; @configurationpublic class webconfig étend webminusoneradapter {public stating Login_user = "LOCIERS; public webConfig () {super (); } // 因为新加了拦截器 , 这里需要重新设置资源地址 @Override public void AddResourceHandlers (ResourceHandlerRegistry Registry) {registry.AddreSourceHandler ("/ static / **"). AddRaSourceLocations ("classpath: / static /"); registry.addreSourceHandler ("/ templates / **"). addResourceLocations ("classpath: / templates /"); super.AddreSourceHandlers (registre); } @Override public void configuredEfaultServLethandling (defaultServLethandLerConfigurer Configurer) {configurer.enable (); } @Override public void AddInterceptors (Registre interceptorgistry) {// 拦截规则 : 除了 Connexion , 其他都拦截判断, excludepathpatterns 是排除拦截的路径 , 一个是登录验证地址 , 一个是登录页 registre.addinterceptor (newLoginInterceptor ()). AddPathPatterns ("/ **"). super.addinterceptors (registre); }}以上就是本文的全部内容 , 希望对大家的学习有所帮助 , 也希望大家多多支持武林网。