添加登录拦截器代码:
package com.wen.ojweb.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@Configuration
public class UserLoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession(true);
Object username=session.getAttribute("user");
if(username!=null) {//已登录
return true;
}else {//未登录
//直接重定向到登录页面
response.sendRedirect(request.getContextPath()+"/countdownPage");
return false;
}
}
}
在Application类中注册登录拦截器
package com.wen.ojweb;
import com.wen.ojweb.config.UserLoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication
@Configuration
@EnableCaching
public class OjwebApplication extends WebMvcConfigurerAdapter {
@Autowired
private UserLoginInterceptor userLoginInterceptor;
/**
* 注册拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
super.addInterceptors(registry);
//添加对用户是否登录的拦截器,并添加过滤项、排除项
registry.addInterceptor(userLoginInterceptor).addPathPatterns("/**")
.excludePathPatterns("/css/**","/js/**","/img/**","/font/**","/images/**","/lay/**","/favicon.ico","/layui.all.js","/layui.js")//排除样式、脚本、图片等资源文件
.excludePathPatterns("/")//排除登录页面
.excludePathPatterns("/login")//排除登录操作
.excludePathPatterns("/registerPage")//排除注册页面
.excludePathPatterns("/register")//排除注册操作
.excludePathPatterns("/countdownPage");//排除倒计时页面
}
public static void main(String[] args) {
SpringApplication.run(OjwebApplication.class, args);
}
}
跳转到的倒计时页面的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>返回登录页面</title>
</head>
<body>
<span id="text"></span>
<a href="javascript:countDown"></a>秒后自动跳转到登录界面……
<script>
var curWwwPath=window.document.location.href;
//获取主机地址之后的目录,如: myproj/view/my
var pathName=window.document.location.pathname;
var pos=curWwwPath.indexOf(pathName);
//获取主机地址,如: http://localhost:8080
var localhostPaht=curWwwPath.substring(0,pos);
function countDown(secs){
text.innerText=secs;
if(--secs>0)
setTimeout("countDown("+secs+")",1000);
else
window.location.href=localhostPaht+"/";
}
countDown(5);
</script>
</body>
</html>
添加拦截器后尝试不登录请求管理员权限的操作:
会跳转到倒计时页面,测试成功