SpringBoot拦截器中返回信息提示及乱码问题

package cn.wanda.common.Interceptor;


import cn.wanda.common.annotation.UserAuth;
import cn.wanda.common.base.PerAuthorityEntity;
import cn.wanda.common.utils.RedisUtils;
import cn.wanda.modules.sso.service.impl.AuthService;
import cn.wanda.modules.sso.utils.AuthConstant;
import cn.wanda.modules.sys.dao.SysMenuDao;
import cn.wanda.modules.sys.entity.SysMenuEntity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dozer.DozerBeanMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.method.HandlerMethod;
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.PrintWriter;
import java.util.*;

/**
 * 拦截器    通过@UserAuth 实现拦截
 *
 * @author : WangYuanYi
 * @description :
 * @create :2021-11-22 09:03:00
 */
@Configuration
@Slf4j
@AllArgsConstructor
public class AdminInterceptor implements HandlerInterceptor  {

    private AuthService authService;

    private SysMenuDao sysMenuDao;

    private RedisUtils redisUtils;

    public AdminInterceptor() {

    }

    /**
     * 目标方法执行之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

  
       if (!StringUtils.isEmpty(s2) && !authUrlHashSet.contains(s2)) {
                  // 解决乱码问题  必须写在response.getWriter() 之前
                  response.setCharacterEncoding("UTF-8");
                  PrintWriter out = null;
             try {
                 JSONObject res = new JSONObject();
                 res.put("msg", "暂无权限");
                 res.put("code", "500");
                 out = response.getWriter();
                 out.append(res.toString());
                 return false;
              } catch (Exception e) {
               e.printStackTrace();
                response.sendError(500);
                return false;
                }
            
        }
        return true;

    }

    /**
     * 目标方法执行完成之后
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 页面渲染以后
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }





    public static <T> List<T> mapList(Collection sourceList, Class<T> destinationClass) {
        DozerBeanMapper dozer = new DozerBeanMapper();
        List<T> destinationList = new ArrayList<>();
        for (Object sourceObject : sourceList) {
            T destinationObject = dozer.map(sourceObject, destinationClass);
            destinationList.add(destinationObject);
        }
        return destinationList;
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot拦截器Spring框架提供的一个强大且易于使用的特性,它可以在请求到达控制器方法之前或之后进行必要的处理操作。其拦截器可以用来修改响应数据,以满足特定业务需求。 在Spring Boot,我们可以通过实现HandlerInterceptor接口来自定义拦截器,从而实现对请求的拦截处理。在这个拦截器,我们可以使用拦截器的preHandle()方法,在处理请求之前修改返回数据,代码如下: ```java public class CustomInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // do something before the actual request is handled return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // do something after the actual request has been handled if (modelAndView != null) { modelAndView.addObject("data", "Custom Data"); } } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // do something after the request has been completed } } ``` 在上述代码,我们通过实现postHandle()方法,在处理完请求之后修改返回数据。首先判断返回的数据是否为空,如果不为空,则可以为返回的数据设置一个新的属性,这里我们为其设置了一个“data”的属性,值为“Custom Data”。 然后,在Spring Boot,要想使用自定义的拦截器,需要将其注册到WebMvcConfigurerAdapter配置。代码如下: ```java @Configuration public class CustomInterceptorConfig extends WebMvcConfigurerAdapter { @Autowired CustomInterceptor customInterceptor; @Override public void addInterceptors(InterceptorRegistry registry){ registry.addInterceptor(customInterceptor); } } ``` 在上述代码,我们定义了一个CustomInterceptorConfig的类,继承自WebMvcConfigurerAdapter,通过@Autowired注入了我们自定义的拦截器。然后,在addInterceptors()方法将其注册到InterceptorRegistry。 最后,在创建完整个Spring Boot应用程序之后,当我们发起请求后,Spring Boot将会首先执行CustomInterceptor的preHandle()方法,然后执行业务逻辑,在成功返回数据之后,Spring Boot再执行CustomInterceptor的postHandle()方法,完成数据修改的操作。 总之,通过Spring Boot拦截器,我们可以很方便地在请求处理过程修改返回的数据,满足特定的业务需求。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值