1、创建PermFilter
过滤所有地址,读取配置文件来获得需要拦截的地址,包含ajax请求重定向处理
package com.systop.modules.ptyh.filter;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.annotation.Order;
import org.springframework.util.ResourceUtils;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* @author guoliwei
* @title: PermFilter
* @projectName
* @description:
* @date 2019/10/99:19
*/
@Order(1)
@WebFilter(filterName = "permFilter",urlPatterns = {"/*"})
public class PermFilter implements Filter {
/** 忽略的登录url集合 **/
private static List<String> IGNORE_LOGIN_URL = new ArrayList<>();
/** 权限url配置资源文件 **/
public static final String KEY = "classpath:/permission.xml";
/** 未登录跳转路径 **/
private String loginUrl = "/ptyh/yhrz/login";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
try {
SAXReader reader = new SAXReader();
Document document = reader.read( ResourceUtils.getFile(KEY) );
Element element = document.getRootElement();
//读取各级用户配置
List<Element> propertys = element.elements("property");
for (Element property : propertys) {
List<Element> urlEles = property.elements("url");
if( "intercept".equals( property.attributeValue("value") ) ) {
urlEles.stream().forEach( url -> IGNORE_LOGIN_URL.add( StringUtils.trim( url.attributeValue("value") ) ));
}
}
System.out.println("商城权限过滤名单共("+IGNORE_LOGIN_URL.size()+")条,已经加载完毕!");
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
String contextPath = httpServletRequest.getServletContext().getContextPath();
StringBuffer requestUrl = httpServletRequest.getRequestURL();//用户请求地址
//验证请求地址中需要拦截的名单
if(IGNORE_LOGIN_URL.stream().filter( url -> validUrl(requestUrl.toString(), url) ).count() > 0 ) {
//验证用户是否登录
if( httpServletRequest.getSession().getAttribute("ptUser") == null ) {
if("XMLHttpRequest".equals(httpServletRequest.getHeader("X-Requested-With"))){
//前端需要判断是否是重定向
httpServletResponse.setHeader("REDIRECT", "REDIRECT");
//需要重定向的路径
httpServletResponse.setHeader("CONTENTPATH", loginUrl);
httpServletResponse.setHeader("status", "500");
}else {
httpServletResponse.sendRedirect(contextPath + loginUrl);
}
return;
}
}
chain.doFilter(httpServletRequest, httpServletResponse);
}
/**
* 验证请求路径和url,支持*号通配符
* @param requestUrl 请求路径
* @param url 待验证url
* @return
*/
private static boolean validUrl(String requestUrl,String url){
if( url.endsWith("*") ) {//如果包含*号通配符,则只验证通配符之前的路径
String beforeUrl = StringUtils.substringBeforeLast(url, "*");
return StringUtils.contains(requestUrl, beforeUrl);
}else {
return StringUtils.contains(requestUrl, url);
}
}
@Override
public void destroy() {
System.out.println("destroy");
}
}
2、创建permission.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
<configuration>
<!-- url鉴权拦截器配置文件 -->
<!-- url配置支持末尾通配符,仅支持*号(所有) -->
<!-- 商城权限拦截名单 -->
<property value="intercept">
<url value="/mall/cart/*" name="购物车"></url>
<url value="/cgscenter/collection/*" name="收藏"></url>
<url value="/cgscenter/cancelCollection/*" name="取消收藏"></url>
<url value="/cgscenter/*" name="采购商中心"></url>
<url value="/gyscenter/*" name="供应商中心"></url>
<url value="/wlscenter/*" name="供应商中心"></url>
</property>
<!-- 忽略权限验证的地址 -->
</configuration>
3、在公共部分的js加入如下代码
var jqxhr;
//设置ajax请求完成后运行的函数,
$.ajaxSetup({
complete:function(){
if("REDIRECT" == jqxhr.getResponseHeader("REDIRECT")){ //若HEADER中含有REDIRECT说明后端想重定向,
var win = window;
while(win != win.top){
win = win.top;
}
if (jqxhr.getResponseHeader("status") == '500'){
win.location.href = jqxhr.getResponseHeader("CONTENTPATH");//将后端重定向的地址取出来,使用win.location.href去实现重定向的要求
}
}
}
});
4、发起ajax请求
jqxhr = $.ajax({
type: "POST", // 用POST方式传输
data:,
dataType:"json",
url: "${ctx}/*****************",// 目标地址
success: function (result){
if(result.code==200){
*******
}else{
alert(result.message)
}
},
error:function(){
}
});