springmvc 自定义过滤器 过滤失败返回自定义的信息

时间:2022-02-16 09:58:39

1、我们项目中会经常使用带springmvc 的拦截器来校验当前请求的前置规则,比如是不是有访问权限,参数合法等。

2、拦截器说明:

  我的项目是自定义类继承 

org.springframework.web.servlet.handler.HandlerInterceptorAdapter,然后实现其中的三个前置、后置和最后渲染的拦截方法。主要业务一般写在
preHandle(request,response,object);方法中,比如参数校验。

3、为了解决拦截失败返回参数的一致性,我们需要返回自己的回调信息

   

package com.cloudstore.v4.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.cloudstore.init.entity.initMember;
import com.cloudstore.init.service.initMemberService;
import com.cloudstore.v4.entity.TAuthMember;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

public class AuthHandler extends HandlerInterceptorAdapter {

    @Autowired
    private initMemberService memberService;


    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String ecId = httpServletRequest.getParameter("ecId");
        if(StringUtils.isEmpty(ecId)){
            writeFailure(httpServletResponse);
            return false;
        } 
        return true;
    }

    private void writeFailure(HttpServletResponse response) throws IOException {
        JSONObject result = new JSONObject();
        result.put("code",0);
        result.put("errMsg","对不起,你没有权限!");
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(result.toString());
        writer.flush();
        writer.close();

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

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

    }
}

 

 

 以上是一个简单的参数校验。如果不为空就放过,否则,就返回{code:0,errMsg:'你没有权限'}这样的数据格式。和我们api的返回格式一样