spring boot 中设置默认网页的方法
废话不多说,直接上代码,相信都能看的懂
一共两布,第一步,创建Interceptor拦截
packagecom.cy.example.config; importjavax.servlet.http.HttpServletRequest; importjavax.servlet.http.HttpServletResponse; importjavax.servlet.http.HttpSession; importorg.slf4j.Logger; importorg.slf4j.LoggerFactory; importorg.springframework.web.servlet.HandlerInterceptor; importorg.springframework.web.servlet.ModelAndView; publicclassLoginInterceptorimplementsHandlerInterceptor{ privateLoggerlogger=LoggerFactory.getLogger(LoginInterceptor.class); publicvoidpostHandle(HttpServletRequestrequest, HttpServletResponseresponse,Objecthandler, ModelAndViewmodelAndView)throwsException{ //TODOAuto-generatedmethodstub } publicvoidafterCompletion(HttpServletRequestrequest, HttpServletResponseresponse,Objecthandler,Exceptionex) throwsException{ //TODOAuto-generatedmethodstub } publicbooleanpreHandle(HttpServletRequestrequest, HttpServletResponseresponse,Objecthandler)throwsException{ //TODOAuto-generatedmethodstub //获取session HttpSessionsession=request.getSession(true); logger.info("----进入登录拦截器--url:"+request.getServletPath()+"-----"); if(session.getAttribute(WebConfig.LOGIN_USER)==null){ logger.info("------跳转到login页面-----"); response.sendRedirect(request.getContextPath()+"/index"); returnfalse; }else{ session.setAttribute(WebConfig.LOGIN_USER,session.getAttribute(WebConfig.LOGIN_USER)); returntrue; } } }
第二步,注册创建的拦截器
packagecom.cy.example.config; importorg.springframework.context.annotation.Configuration; importorg.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; importorg.springframework.web.servlet.config.annotation.InterceptorRegistry; importorg.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; importorg.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration publicclassWebConfigextendsWebMvcConfigurerAdapter{ publicstaticStringLOGIN_USER="loginUser"; publicWebConfig(){ super(); } //因为新加了拦截器,这里需要重新设置资源地址 @Override publicvoidaddResourceHandlers(ResourceHandlerRegistryregistry){ registry.addResourceHandler("/static/**").addResourceLocations( "classpath:/static/"); registry.addResourceHandler("/templates/**").addResourceLocations( "classpath:/templates/"); super.addResourceHandlers(registry); } @Override publicvoidconfigureDefaultServletHandling( DefaultServletHandlerConfigurerconfigurer){ configurer.enable(); } @Override publicvoidaddInterceptors(InterceptorRegistryregistry){ //拦截规则:除了login,其他都拦截判断,excludePathPatterns是排除拦截的路径,一个是登录验证地址,一个是登录页 registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns("/index","/system/user/validate"); super.addInterceptors(registry); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。