1. 程式人生 > >20 Web開發實戰--登入&攔截器

20 Web開發實戰--登入&攔截器

1 更改頁面,實時生效

a): 禁用模板引擎快取
	spring.thymeleaf.cache=false

b): 更改頁面完成後,按 Ctrl + F9 進行編譯

2 登入

package com.gp6.springboot18.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import
org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpSession; import java.util.Map; @Controller public class LoginController { //@RequestMapping(value = "/user/login",method = RequestMethod.POST)與@PostMapping(value = "/user/login")等效 @PostMapping(value = "/user/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"; } } }

3 自定義攔截器

3.1 MyHandlerInterceptor

package com.gp6.springboot18.config;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * 自定義攔截器
 */
public class MyHandlerInterceptor implements HandlerInterceptor {
    //目標方法執行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 判斷session是否包含使用者名稱
        Object user = request.getSession().getAttribute("loginUser");
        if(user == null){
            //未登陸,返回登陸頁面
            request.setAttribute("msg","沒有許可權請先登陸");
            request.getRequestDispatcher("/login.html").forward(request,response);
            return false;
        }else{
            //已登陸,放行請求
            return true;
        }

    }

    @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.2 將自定義攔截器注入容器

package com.gp6.springboot18.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyConfig implements WebMvcConfigurer {

    /*
        所有的WebMvcConfigurer元件會一起生效
    */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("login");
        registry.addViewController("/login.html").setViewName("login");
        registry.addViewController("/main.html").setViewName("dashboard");
    }

    //註冊攔截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /*
            SpringBoot已配置靜態資源對映,編寫攔截器時,無需考慮靜態資源
        */
        registry.addInterceptor(new MyHandlerInterceptor()).
                // 攔截的請求(/** : 所有)
                addPathPatterns("/**")

                // 放行的請求
                .excludePathPatterns("/login.html","/","/user/login");
    }

    /*
        將自定義的區域資訊解析器注入到容器中
    */
    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocaleResolver();
    }
}