现在有个需求,我只想要带有 /api/{path}的才能访问,并且path传的参必须在数据库中里面存在
@GetMapping("/api/{path}")
public String getData(@PathVariable String path){
String data = urlService.getData(path);
return data;
}
必须要传/api/get才能访问,传其他的不行
代码实现
拦截器
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.donglin.entity.UrlEntity;
import com.donglin.mapper.UrlMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
public class URLInterceptor implements HandlerInterceptor {
@Autowired
private UrlMapper urlMapper;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getServletPath();
String[] split = path.split("/");
path = split[split.length-1];
QueryWrapper<UrlEntity> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("path", path);
List<UrlEntity> list = urlMapper.selectList(queryWrapper);
if (list.size() != 0) {
// 进行前置处理
return true;
// 或者 return false; 禁用某些请求
} else {
return false;
}
}
}
配置类
import org.springframework.context.annotation.Bean;
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 WebMvcConfig implements WebMvcConfigurer {
@Bean
public URLInterceptor urlInterceptor(){
return new URLInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(urlInterceptor()).addPathPatterns("/api/**");
}
}
提醒一下小坑(上面代码是对的)
urlMapper为空
@Autowired
private UrlMapper urlMapper;
为null的原因
原因是因为拦截器的加载在springcontext之前,所以自动注入的mapper是null
解决方案
在添加拦截器之前用@bean注解将拦截器注入工厂,接着添加拦截器
@Bean
public URLInterceptor urlInterceptor(){
return new URLInterceptor();
}
registry.addInterceptor里面是urlInterceptor(),不是之前的new URLInterceptor()
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(urlInterceptor()).addPathPatterns("/api/**");
}