20.0、springboot-Interceptor拦截器实现
首先写一个登录界面跳转的Controller如下:
IndexController.java文件
package com.hkl.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;
import javax.servlet.http.HttpSession;
@Controller
public class IndexController {
@RequestMapping("/user/gotomanager")
public String gotomanager(@RequestParam("username") String username, @RequestParam("password") String password, Model model, HttpSession session) {
if(!StringUtils.isEmpty(username) && password.equals("123")) {
session.setAttribute("username",username);
return "redirect:/manager";
}else {
model.addAttribute("msg","您输入的用户名或密码有误!");
return "index";
}
}
}
登录界面的html文件:
Index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>登录界面</title>
</head>
<body>
<h1 text="登录界面"></h1>
<p style="color: red" th:text="${msg}"></p>
<form th:action="@{/user/gotomanager}">
<input name="username" type="text" /><br/>
<input name="password" type="password" /><br/>
<input type="submit" value="登录"><br/>
</form>
</body>
</html>
写好Interceptor拦截器文件:
LoginHandlerInterceptor.java
package com.hkl.config;
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 username = request.getSession().getAttribute("username");
if(username == null) {//如果获取到的session为空说明用户尚未登录!
request.setAttribute("msg","权限不够!请先登录!");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else {
return true;
}
}
}
最后一定要记得将这个写好的拦截器类注入到configuration配置文件中:
MyMvcConfig.java
package com.hkl.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;
//扩展 springmvc dispatchservlet
@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").excludePathPatterns("/index.html","/","/user/gotomanager");
}
}