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

本文介绍了一种订单状态拦截器的设计与实现,该拦截器用于检查订单是否已超过48小时未处理,若超过则将用户重定向至首页,确保业务流程的合规性和用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.youkuaiyun.com/wo88798/article/details/82465211

拦截器主体

 
  1. import com.alibaba.fastjson.JSONObject;

  2. import com.ufclub.vis.constant.StatusConstant;

  3. import com.ufclub.vis.entity.BaseResult;

  4. import com.ufclub.vis.entity.admin.order.OrderInfo;

  5. import com.ufclub.vis.service.admin.order.OrderInfoService;

  6. import org.slf4j.Logger;

  7. import org.slf4j.LoggerFactory;

  8. import org.springframework.beans.factory.annotation.Autowired;

  9. import org.springframework.stereotype.Component;

  10. import org.springframework.web.servlet.HandlerInterceptor;

  11. import org.springframework.web.servlet.ModelAndView;

  12.  
  13. import javax.servlet.http.HttpServletRequest;

  14. import javax.servlet.http.HttpServletResponse;

  15. import java.io.IOException;

  16. import java.io.PrintWriter;

  17.  
  18. /**

  19. * Created by tangzw on 2018/9/6 0006.

  20. * 拦截订单超过48小时后需要返回首页

  21. */

  22. @Component

  23. public class RepeatInterceptor implements HandlerInterceptor {

  24.  
  25. private Logger logger = LoggerFactory.getLogger(this.getClass());

  26.  
  27. //拦截发起视频和确认签订

  28. private static final String[] requestUrls = new String[]{"/front/video/callVideo/", "/front/sign/doSign/"};

  29.  
  30. @Autowired

  31. private OrderInfoService orderInfoService;

  32.  
  33. @Override

  34. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

  35.  
  36. boolean ajaxFlag = false;

  37. if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {

  38. ajaxFlag = true;

  39. }

  40. String requestURI = request.getRequestURI();

  41. String orderIdStr = null;

  42. if (requestURI != null) {

  43. for (String url : requestUrls) {

  44. if (requestURI.indexOf(url) != -1) {

  45. orderIdStr = requestURI.substring(requestURI.indexOf(url) + url.length());

  46. char[] chars = orderIdStr.toCharArray();

  47. for (int i = 0; i < chars.length; i++) {

  48. if (!Character.isDigit(chars[i])) {

  49. orderIdStr = orderIdStr.substring(0, i);

  50. break;

  51. }

  52. }

  53. }

  54. }

  55.  
  56. if (orderIdStr != null) {

  57. Integer orderId;

  58. try {

  59. orderId = Integer.parseInt(orderIdStr);

  60. } catch (Exception e) {

  61. logger.error("状态拦截器订单id转换异常,orderId:" + orderIdStr + ",链接:" + requestURI, e);

  62. return false;

  63. }

  64.  
  65. //查询订单状态

  66. OrderInfo orderInfo = orderInfoService.selectByPrimaryKey(orderId);

  67. //订单是否已经回到身份验证

  68. if (StatusConstant.ORDER_VERIFY_IDCARD.equals(orderInfo.getStatus())){

  69. logger.error("状态拦截器订单已超过48小时,回到身份验证状态,orderId:" + orderIdStr + ",链接:" + requestURI);

  70. //if (ajaxFlag){

  71. // response.setHeader("orderStatus", "expire");

  72. //}else {

  73. // response.sendRedirect(expireUrl);

  74. //}

  75. //return false;

  76. BaseResult baseResult = new BaseResult();

  77. baseResult.setCode(0);

  78. baseResult.setMessage("订单状态变更,请重新操作");

  79. baseResult.setData(StatusConstant.ORDER_VERIFY_IDCARD);

  80. String jsonObjectStr = JSONObject.toJSONString(baseResult);

  81. returnJson(response,jsonObjectStr);

  82. return false;

  83. }

  84. }

  85. }

  86. return true;

  87. }

  88.  
  89. private void returnJson(HttpServletResponse response, String json) throws Exception{

  90. PrintWriter writer = null;

  91. response.setCharacterEncoding("UTF-8");

  92. response.setContentType("text/html; charset=utf-8");

  93. try {

  94. writer = response.getWriter();

  95. writer.print(json);

  96.  
  97. } catch (IOException e) {

  98. logger.error("response error",e);

  99. } finally {

  100. if (writer != null)

  101. writer.close();

  102. }

  103. }

  104.  
  105.  
  106.  
  107. @Override

  108. public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

  109.  
  110. }

  111.  
  112. @Override

  113. public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

  114.  
  115. }

  116. }

前端页面接收(原请求ajax,不需要新建)

 
  1. $.ajax({

  2. url: "",

  3. type: 'POST',

  4. data: {"status" : "VIDEO"},

  5. dataType: 'json',

  6. success: function (data){

  7. if (data.code == 0) {

  8. layer.msg( data.message, {time : 3500}, function(){

  9. window.location.href = "/front/index";

  10. });

  11. } else {

  12. layer.msg( data.message, {time : 3500}, function(){});

  13. }

  14. }

  15. });

启用拦截器

 
  1. import com.ufclub.vis.web.interceptor.AutoLoginInterceptor;

  2. import com.ufclub.vis.web.interceptor.OrderStatusInterceptor;

  3. import com.ufclub.vis.web.interceptor.RepeatInterceptor;

  4. import org.springframework.beans.factory.annotation.Autowired;

  5. import org.springframework.context.annotation.Configuration;

  6. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

  7. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

  8.  
  9.  
  10. @Configuration

  11. public class IntercpetorConfig extends WebMvcConfigurerAdapter {

  12.  
  13.  
  14.  
  15. @Autowired

  16. private RepeatInterceptor repeatInterceptor;

  17.  
  18. @Override

  19. public void addInterceptors(InterceptorRegistry registry) {

  20. registry.addInterceptor(repeatInterceptor).addPathPatterns("/front/**");

  21. }

  22. }

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值