spring boot 中设置默认网页的方法
程序员文章站
2023-10-20 10:21:26
废话不多说,直接上代码,相信都能看的懂
一共两布,第一步,创建interceptor拦截
package com.cy.example.config;...
废话不多说,直接上代码,相信都能看的懂
一共两布,第一步,创建interceptor拦截
package com.cy.example.config; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.springframework.web.servlet.handlerinterceptor; import org.springframework.web.servlet.modelandview; public class logininterceptor implements handlerinterceptor { private logger logger = loggerfactory.getlogger(logininterceptor.class); public void posthandle(httpservletrequest request, httpservletresponse response, object handler, modelandview modelandview) throws exception { // todo auto-generated method stub } public void aftercompletion(httpservletrequest request, httpservletresponse response, object handler, exception ex) throws exception { // todo auto-generated method stub } public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception { // todo auto-generated method stub //获取session httpsession session = request.getsession(true); logger.info("----进入登录拦截器--url:"+request.getservletpath()+"-----"); if(session.getattribute(webconfig.login_user) == null){ logger.info("------跳转到login页面-----"); response.sendredirect(request.getcontextpath()+"/index"); return false; }else{ session.setattribute(webconfig.login_user, session.getattribute(webconfig.login_user)); return true; } } }
第二步,注册创建的拦截器
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.interceptorregistry; import org.springframework.web.servlet.config.annotation.resourcehandlerregistry; import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter; @configuration public class webconfig extends webmvcconfigureradapter { public static string login_user = "loginuser"; public webconfig() { super(); } //因为新加了拦截器,这里需要重新设置资源地址 @override public void addresourcehandlers(resourcehandlerregistry registry) { registry.addresourcehandler("/static/**").addresourcelocations( "classpath:/static/"); registry.addresourcehandler("/templates/**").addresourcelocations( "classpath:/templates/"); super.addresourcehandlers(registry); } @override public void configuredefaultservlethandling( defaultservlethandlerconfigurer configurer) { configurer.enable(); } @override public void addinterceptors(interceptorregistry registry) { // 拦截规则:除了login,其他都拦截判断,excludepathpatterns是排除拦截的路径,一个是登录验证地址,一个是登录页 registry.addinterceptor(new logininterceptor()).addpathpatterns("/**").excludepathpatterns("/index","/system/user/validate"); super.addinterceptors(registry); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。