1.私のプロジェクト環境:springboot2.0.0 + thymeleaf
2.カスタムインターセプターを追加する目的:プロジェクトは通常ローカルで実行され、クラウドサーバーに公開された後、フロントエンドページのjsファイルとcssファイルに多数のエラーが報告されます。インポートされた静的ファイルパスを正しくするために、インターセプターが追加され、プロジェクトパスがフロントエンドページで使用するリクエストドメインに配置されます。
3.プロジェクトディレクトリは次のとおりです。ボックス内のファイルは、カスタムインターセプターに必要なファイルです。
4.インターセプターをカスタマイズし、@ Componentアノテーションをマークして、インターセプターをスプリングコンテナーに配置します。
package com.admin.mall.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* 作用:拦截所有请求,设置rootPath给前端页面使用
*/
@Component
public class MyInterceptor implements HandlerInterceptor {
/**
* 在整个请求结束之后被调用,DispatcherServlet 渲染视图之后执行(进行资源清理工作)
*/
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
}
/**
* 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后)
*/
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
}
/**
* 在请求处理之前进行调用(Controller方法调用之前)
*
* @return 返回true才会继续向下执行,返回false取消当前请求
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
String rootPath = request.getContextPath();
//设置前端的全局地址,可以是request.getContextPath(),也可以是包含ip、端口号、项目名等等的全路径
request.setAttribute("rootPath", rootPath);
return true;
}
}
5.カスタムインターセプター(登録済みインターセプター)をプロジェクトに追加します。このクラスで@Configurationをマークして、それが構成クラスであることを示します。
package com.admin.mall;
import com.admin.mall.interceptor.MyInterceptor;
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
private MyInterceptor myInterceptor;
/**
* 添加自定义拦截器
*/
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor)
.addPathPatterns("/**")//拦截的访问路径,拦截所有
.excludePathPatterns("/static/*");//排除的请求路径,排除静态资源路径
super.addInterceptors(registry);
}
/**
* 添加静态资源映射路径,css、js等都放在classpath下的static中
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**")
.addResourceLocations("classpath:/static/");
super.addResourceHandlers(registry);
}
}
プロジェクトをクラウドサーバーにデプロイする際に、フロントエンドで見つからない静的リソースファイルが多数あったため、shiroがプロジェクトに統合されました。当初、これが問題であると考えられ、スプリングブーツのプロンプトが比較的弱かったので、私はピットを踏んだ。複数のインターセプターがある場合は、実行の順序と実行されるかどうかに注意するのが最善であることに注意する必要があります。