SpringBoot 攔截器和過濾器

攔截器和過濾器

時光飛逝,最近也是很忙,但是忙到最後發現在自己並沒有太多的成長
工作
學習
生活
沒想到成長是不經意間的,像是被 推着,讓你身不由己
午休時間,寫寫博客,也是保留一些自己的時間和空間

需求

說一下近期的需求,最近在寫一個項目,這個項目我想做成前後端分離的,使用的框架是springboot
我希望的是是頁面也放在這個項目上,以前做了一個項目也是基於springboot的,但是並沒有實現真正的前後端分離
在這裏插入圖片描述
可以看到的是這樣的的一個結構 這個所有的靜態文件都是放在resource/templates
但是我覺得這樣並不是真正意義上的前後端分離
這其實是一種springmvc的結果,頁面的顯示其實還是後臺通過接口返回地址映射到templates的路徑

在這裏插入圖片描述
這個不是我想要的結果
下面是我想實現的結果
在這裏插入圖片描述
可以看到是我的靜態文件是放在webapp文件夾下面
其實這樣我的靜態文件和後端接口之間是完全分離的
但是這樣,我希望接口能對我有所限制,就是不是說所有的接口我都是可以調用的
有些接口需要登錄之後調用
有些接口可以直接的 調用
有了上面的需求之後,,我們看看是用攔截器還是用過濾器來實現我的需求

攔截器

無論是攔截器還是過濾器。我們實現其實是繼承接口
攔截器是AOP一個應用,一個編程思想
面向切面編程其實是面向對象編程思想
在這裏插入圖片描述
攔截器是對項目對項目中的一切資源都可以攔截

接口可以攔截
靜態資源可以攔截
靜態資源攔截,那麼我們訪問頁面,也要走這個,他會將我們的靜態資源的請求作爲一個映射的地址
去在項目中進行匹配,其實這對於我們實現前後端分離是不利的
因爲我們請求後臺資源都要告訴他,讓他去在項目中進行映射,其實我們想把靜態資源和後臺全獨立
這樣自然是不行的
那麼如何實現一個攔截器

package com.could.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.could.domain.HHUserToken;
import com.could.mapper.UserTokenMapper;

@Service
public class UserTokenInterceptor implements HandlerInterceptor {
	
	@Autowired
	private UserTokenMapper userTokenMapper;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 在請求處理之前進行調用(Controller方法調用之前),返回true纔會繼續往下執行,返回false取消當前請求
		boolean isAccess = false;
		String jssessionid = request.getHeader("jssessionid");
		if (jssessionid != null && !"".equals(jssessionid)) {
			// 查詢未過期的
			HHUserToken usertoken= userTokenMapper.selectByJssessionid(jssessionid);
			if (usertoken != null) {
				isAccess = true;
			} else {
				isAccess = false;
			}
		}
		return isAccess;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("我執行了postHandle");

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("我執行了afterCompletion");

	}

}

package com.could.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * 
 * @author wdg
 * @category 接口攔截器,有的接口需要登錄
 *
 */
@Component
@Configuration
public class UserTokenAppConfigurer extends WebMvcConfigurationSupport {

	private static final String[] excludePathPatterns = { "/templates/**", "/webapp/**" };

	private static final String[] addPathPatterns = { "/useraction/getuserinfo" };

	@Autowired
	private UserTokenInterceptor userTokenInterceptor;

	@Autowired
	private WebRescorceInterceptor webRescorceInterceptor;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 多個攔截器組成一個攔截器鏈
		// addPathPatterns 用於添加攔截規則
		// excludePathPatterns 用戶排除攔截
		registry.addWebRequestInterceptor(webRescorceInterceptor);
		registry.addInterceptor(userTokenInterceptor).addPathPatterns(addPathPatterns)
				.excludePathPatterns(excludePathPatterns);
		super.addInterceptors(registry);
	}

	@Override
	protected void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("**/template/**").addResourceLocations("webapp/templates/**.html");
	}

}

這樣就可以了

過濾器

package com.could.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class CustomerFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		long start = System.currentTimeMillis();
		chain.doFilter(request, response);
		System.out.println("Execute cost=" + (System.currentTimeMillis() - start));

	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}

package com.could.filter;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FilterConfig {

	@Bean
	public FilterRegistrationBean<CustomerFilter> registFilter() {
		FilterRegistrationBean<CustomerFilter> registration = new FilterRegistrationBean<CustomerFilter>();
		registration.setFilter(new CustomerFilter());
		registration.addUrlPatterns("/*");
		registration.setName("customerFilter");
		registration.setOrder(1);
		return registration;
	}

}

希望對你有所幫助

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章