spring boot 拦截器实现拦截前端请求并返回json至前端页面

拦截器主体

import com.alibaba.fastjson.JSONObject;
import com.ufclub.vis.constant.StatusConstant;
import com.ufclub.vis.entity.BaseResult;
import com.ufclub.vis.entity.admin.order.OrderInfo;
import com.ufclub.vis.service.admin.order.OrderInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
 
/**
 * Created by tangzw on 2018/9/6 0006.
 * 拦截订单超过48小时后需要返回首页
 */
@Component
public class RepeatInterceptor implements HandlerInterceptor {
 
    private Logger logger = LoggerFactory.getLogger(this.getClass());
 
    //拦截发起视频和确认签订
    private static final String[] requestUrls = new String[]{"/front/video/callVideo/", "/front/sign/doSign/"};
 
    @Autowired
    private OrderInfoService orderInfoService;
 
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
 
        boolean ajaxFlag = false;
        if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            ajaxFlag = true;
        }
        String requestURI = request.getRequestURI();
        String orderIdStr = null;
        if (requestURI != null) {
            for (String url : requestUrls) {
                if (requestURI.indexOf(url) != -1) {
                    orderIdStr = requestURI.substring(requestURI.indexOf(url) + url.length());
                    char[] chars = orderIdStr.toCharArray();
                    for (int i = 0; i < chars.length; i++) {
                        if (!Character.isDigit(chars[i])) {
                            orderIdStr = orderIdStr.substring(0, i);
                            break;
                        }
                    }
                }
            }
 
            if (orderIdStr != null) {
                Integer orderId;
                try {
                    orderId = Integer.parseInt(orderIdStr);
                } catch (Exception e) {
                    logger.error("状态拦截器订单id转换异常,orderId:" + orderIdStr + ",链接:" + requestURI, e);
                    return false;
                }
 
                //查询订单状态
                OrderInfo orderInfo = orderInfoService.selectByPrimaryKey(orderId);
                //订单是否已经回到身份验证
                if (StatusConstant.ORDER_VERIFY_IDCARD.equals(orderInfo.getStatus())){
                    logger.error("状态拦截器订单已超过48小时,回到身份验证状态,orderId:" + orderIdStr + ",链接:" + requestURI);
                    //if (ajaxFlag){
                    //    response.setHeader("orderStatus", "expire");
                    //}else {
                    //    response.sendRedirect(expireUrl);
                    //}
                    //return false;
                    BaseResult baseResult = new BaseResult();
                    baseResult.setCode(0);
                    baseResult.setMessage("订单状态变更,请重新操作");
                    baseResult.setData(StatusConstant.ORDER_VERIFY_IDCARD);
                    String jsonObjectStr = JSONObject.toJSONString(baseResult);
                    returnJson(response,jsonObjectStr);
                    return false;
                }
            }
        }
        return true;
    }
 
    private void returnJson(HttpServletResponse response, String json) throws Exception{
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);
 
        } catch (IOException e) {
            logger.error("response error",e);
        } finally {
            if (writer != null)
                writer.close();
        }
    }
 
 
 
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
 
    }
 
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
 
    }
}
前端页面接收(原请求ajax,不需要新建)

             $.ajax({
                url: "",
                type: 'POST',
                data: {"status" : "VIDEO"},
                dataType: 'json',
                success: function (data){            
                        if (data.code == 0) {
                            layer.msg( data.message, {time : 3500}, function(){
                                window.location.href = "/front/index";
                            });
                        } else {
                            layer.msg( data.message, {time : 3500}, function(){});                        
                        }
                }    
            });
启用拦截器

import com.ufclub.vis.web.interceptor.AutoLoginInterceptor;
import com.ufclub.vis.web.interceptor.OrderStatusInterceptor;
import com.ufclub.vis.web.interceptor.RepeatInterceptor;
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.WebMvcConfigurerAdapter;
 
 
@Configuration
public class IntercpetorConfig extends WebMvcConfigurerAdapter {
 
 
 
    @Autowired
    private RepeatInterceptor repeatInterceptor;
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(repeatInterceptor).addPathPatterns("/front/**");
    }
}
 
--------------------- 
作者:做个好人XL 
来源:CSDN 
原文:https://blog.csdn.net/wo88798/article/details/82465211 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值