springboo 攔截器

index.html (登錄頁)

<form class="form-signin" th:action="@{/user/login}" method="post">

controller

package com.zoe.customer.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@Controller
public class loginController {
    @PostMapping("/user/login")
    public String test4(String name, String password, Model model, HttpSession httpSession) {
        if (name.equals("admin") && password.equals("123")) {
            httpSession.setAttribute("session",name);
            return "redirect:/main";
        }else {
            model.addAttribute("msg","賬號(hào)密碼錯(cuò)誤");
            return "index";
        }
    }
}

登錄成功 session會(huì)存儲(chǔ)一個(gè)string
登錄失敗 沒有session存儲(chǔ)任何東西
那么對(duì)鏈接進(jìn)行攔截,來查看時(shí)候存有session
有就放行
沒有就跳到首頁

攔截器

package com.zoe.customer.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object name = request.getSession().getAttribute("session");
        if (name == null) {
            System.out.println("未登錄");
            request.getRequestDispatcher("/").forward(request,response);
            return false; //false 不放行
        }else {
            System.out.println("已登錄"+name);
            return  true; // true 放行
        }

    }
}

配置類 對(duì)靜態(tài)類文件進(jìn)行放行

package com.zoe.customer.configuration;

import com.zoe.customer.interceptor.LoginHandlerInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
public class MyConfiguration implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("main").setViewName("dashboard");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginHandlerInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/","/user/login","/static/**");
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容