1. 程式人生 > >spring boot 攔截器實現攔截前端請求並返回json至前端頁面

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/**");
    }
}