本帖最后由 关谷神奇 于 2021-6-22 16:31 编辑
使用springboot进行开发时,应该如何释放静态页面,以下是我拦截器的配置,用于拦截登录状态,我将html文件放入static包里面之后,依然会被拦截掉,请教如何配置。
package com.zm.crmserver.controller;
import com.zm.crmserver.annotation.Auth;
import com.zm.crmserver.pojo.User;
import com.zm.crmserver.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
//拦截器
@Component
public class AuthIntercepter implements HandlerInterceptor {
@Autowired
JWTUtil jwtUtil;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//拦截器跨域配置方式2
if("OPTIONS".equals(request.getMethod().toUpperCase())) {
//System.out.println("Method:OPTIONS");
return true;
}
if (!request.getMethod().equalsIgnoreCase("GET") && !request.getMethod().equalsIgnoreCase("POST")) {
return true;
}
String token = request.getHeader("token");
boolean valid = jwtUtil.isValid(token);
if (valid) {
User user = jwtUtil.get(token);
if (user!=null) {
Method method = ((HandlerMethod) handler).getMethod();
Integer u_id = user.getU_id();
//request.setAttribute("u_id",u_id);
request.setAttribute("user",user);
if(method.isAnnotationPresent(Auth.class)){//判断是否有@auth注解
//获取注解对象
Auth auth = method.getAnnotation(Auth.class);
//
String value = auth.value();//获取注解中的值
if (value.contains(user.getR_id()+"")) {//判断注解中值是否包含rid
return true;
}
}else {
return true;
}
}
}
//响应一个json格式对象
response.setContentType("application/json;charset=utf-8");
String str = "{\"msg\":\"nopermission\"}";
response.getWriter().write(str);//响应数据
return false;
}
}
package com.zm.crmserver.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
//添加拦截器 拦截器
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Autowired
AuthIntercepter authIntercepter;
/**
*我尝试在下面代码里面进行释放,依然不行,
*/
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authIntercepter).addPathPatterns("/**").excludePathPatterns("/login");
}
//下面这段代码网上搜索的
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
|