2021年1月19日 星期二

[SpringBoot 1.5] 登入及攔截器HandlerInterceptor

一般在Controller中我們會使用以下語法

@RequestMapping(value = "/user/login", method = RequestMethod.POST)

但是在較新版中已經簡化成以下

@PostMapping(value = "/user/login")

因為PostMapping已經有將 method = RequestMethod.POST 寫好

controller的程式碼如下

@PostMapping(value = "/user/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String,Object> map){
if(!StringUtils.isEmpty(username)&&"123456".equals(password)){
//登入成功
return "dashboard";
}else{
//登入失敗
map.put("msg","用戶名密碼錯誤");
return "login";
}
}

前端的程式碼

<label class="sr-only" th:text="#{login.username}">Username</label>
<input type="text" name="username" class="form-control" placeholder="Username"
th:placeholder="#{login.username}" required="" autofocus="">
<label class="sr-only" th:text="#{login.password}">Password</label>
<input type="password" name="password" class="form-control" placeholder="Password"
th:placeholder="#{login.password}" required="">

這裡的對應是由name來做@RequestParam的對應

那這邊特別紀錄一下, 因為thymeleaf有緩存的設置

所以這邊要在properties檔案中加入這段

spring.thymeleaf.cache=false

以後在修改靜態頁面只要ctrl+f9 刷一下瀏覽器就可以看效果了

而錯誤訊息可以用以下這段在頁面顯示

<p style="color: red;" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

----------------------------------------

製作攔截器

1 在controller加入Session檢核, 只要成功登入, 就將username塞到Session中

@PostMapping(value = "/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String,Object> map, HttpSession session){
if(!StringUtils.isEmpty(username)&&"123456".equals(password)){
//登入成功
session.setAttribute("loginUser",username);
return "redirect:/main.html";
}else{
//登入失敗
map.put("msg","用戶名密碼錯誤");
return "login";
}
}

2 在component包中製作一個LoginHandlerInterceptor 類別去繼承HandlerInterceptor 

類別, 並複寫三個父類方法

public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}

3 在preHandle中加入以下這段程式碼當作檢核, 如果沒有權限的話, 

會有錯誤訊息, 並且導頁到首頁

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user=request.getSession().getAttribute("loginUser");
if(user==null){
request.setAttribute("msg","沒有權限請先登入");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else{
return true;
}
}

4在自設定的configuration檔案中的@Bean, 增加addInterceptors的方法

加入攔截器並排除不需要攔截的頁面

@Bean
public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
WebMvcConfigurerAdapter adapter= new WebMvcConfigurerAdapter(){
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("login");
registry.addViewController("/index.html").setViewName("login");
registry.addViewController("/main.html").setViewName("dashboard");
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/login");
}
};

return adapter;
}

5從Session中取出使用者資訊, 放在畫面上

<a class="navbar-brand col-sm-3 col-md-2 mr-0" href="#">[[${session.loginUser}]]</a>


這樣就完成了, 每當用戶進入到下個頁面就會被攔截器去檢核


沒有留言:

張貼留言

[leetcode] [KMP] KMP

ABCDABD... ABCDABF... 簡單的說, 傳統解兩字串匹配部分 可能會來個雙迴圈, 哀個比對, 當不匹配的時候, 會將下方列再後移1位 然後不匹配再後移 然而 如果像上放已經有4個屬於匹配的字串, 她就應該直接往後移四位來匹配, 而不是只移動1位 隱藏的思維是, 當...