1. 程式人生 > >spring boot 中設定預設網頁

spring boot 中設定預設網頁

廢話不多說,直接上程式碼,相信都能看的懂
一共兩布,第一步,建立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);
    }

}