公司最新需求:根据传递的参数进行业务判断,如果符合条件则继续后面的业务逻辑,否则跳转到指定的错误页面。有些是请求的controller 使用了spring aop的方式进行验证;但是有些是html页面,这些是需要使用过滤器了。
1.框架是spring mvc框架
添加自定义的过滤器
package cn.zm518.news.filter;import cn.zm518.circle.client.entity.CircleStateVo;import cn.zm518.circle.client.service.CircleClient;import cn.zm518.common.properties.SystemProperties;import cn.zm518.news.common.util.StringUtil;import org.apache.commons.lang.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.web.filter.OncePerRequestFilter;import javax.servlet.FilterChain;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;import java.io.PrintWriter;/** * @Author fan * @Date 2018/07/18 * 拦截封号的文章列表以及详情页 */public class CircleFilter extends OncePerRequestFilter { public static final String shequnHost = SystemProperties.getInstance().getProperty("community.rpc.url"); public static final String url = SystemProperties.getInstance().getProperty("seal.circle.url"); public static final int CIRCLE_STEAL = 2; //社群是否被封号 @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { // 请求的uri String uri = request.getRequestURI(); // uri跳转到文章列表以及详情时才进行过滤 if (uri.indexOf("statics/html/article") == 1) { // 执行过滤 // 获取登录的社群circleId String circleId = request.getParameter("circleId"); if (StringUtils.isNotBlank(circleId)) { CircleClient circleClient = CircleClient.getInstance(shequnHost); CircleStateVo circleStateVo = circleClient.getCircleStateVo(circleId); if (circleStateVo != null && circleStateVo.getState() == CIRCLE_STEAL){ // 如果session中不存在登录者实体,则弹出框提示重新登录 // 设置request和response的字符集,防止乱码 request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); StringBuilder builder = new StringBuilder(); builder.append(""); out.print(builder.toString()); } } else { filterChain.doFilter(request, response); } } else { filterChain.doFilter(request, response); } }}
2.在web.xml添加自定义的过滤器
sessionFilter cn.zm518.news.filter.CircleFilter sessionFilter /*
3.比如请求本地的html页面
http://localhost:8068/statics/html/article.html?circleId=4f98421633973cf75-7fef&newsId=41df20164b5c0c282-7ffe&followerId=&from=singlemessage
会先进入自定义过滤器,如果不满足条件,则会优先过滤掉。负责会跳过继续执行后面的业务逻辑。