首先创建第一个类实现HandlerInterceptor接口
package com.fzx.handlerIntercepter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.fzx.bean.User;
public class LoginHandlerIntercepter implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
// 最主要的实现这个方法
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// TODO Auto-generated method stub
// 从session作用域中取值
User user = (User) request.getSession().getAttribute("user");
// 判断是否为空
if(user!=null) {
// 不为空则执行
return true;
}else {
// 为空则返回登录页面重新登录
response.sendRedirect("/login.jsp");
}
return false;
}
}
其次创建第二个类实现WebMvcConfigurer接口
package com.fzx.handlerIntercepter;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class LoginWebMvc implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// TODO Auto-generated method stub
// 这句话表示拦截所有,但是不拦截登录页面和登录的方法还有static下的所有
registry.addInterceptor(new LoginHandlerIntercepter()).addPathPatterns("/**").excludePathPatterns("/login.jsp","/shop/login","/static/**");
}
}
application.properties下要声明一下
## 这是spring boot在使用jsp页面的时候必须要声明的一句话
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
## 连接数据库
spring.datasource.url=jdbc:mysql://localhost:3306/yuekao?useUnicode=true&characterEncoding=utf-8
## 数据库账号
spring.datasource.username=root
## 数据库密码
spring.datasource.password=root
## 扫描com.bw.dao包下的.xml文件
mybatis.mapper-locations=classpath:/com/bw/dao/*.xml
server.port=8080
## 最主要的是这句话,这样css和jQuery才可以被放行
spring.mvc.static-path-pattern=/static/**
这时页面引用css或jQuery的时候就必须这样写了
<link rel="stylesheet" href="/static/css/style.css" type="text/css">
<script type="text/javascript" src="/static/jQuery/jquery-1.8.2.min.js"></script>
在这里呢,我是用的jsp页面作为前台展示,所以pom.xml中要引用两个重要的依赖
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
小生此为初学者,能力有限,望各位大神勿喷……