java拦截器的使用

我们在写后台考虑的,前端在请求的时候校验是否登陆,参数签名是否符合我们的需求,所以就需要设置拦截器在拦截器里面校验,以前的写法是直接使用HandlerInterceptor,但是会导致接口中无法拿到body里面的值,就需要处理传递过去,代码如下:

package top.yang.intelAI.interceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration   //标注此文件为一个配置项,spring boot才会扫描到该配置。该注解类似于之前使用xml进行配置
public class CustomWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

    @Bean
    public InitInterceptor myInterceptor(){
        return new InitInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration registration = registry.addInterceptor(myInterceptor());  //对来自/user/** 这个链接来的请求进行拦截
        registration.addPathPatterns("/**");
        registration.excludePathPatterns("xx/xxx/xx");
        registration.addPathPatterns("xx/xxx/xx"); //请求路径
    }
}
package top.yang.intelAI.interceptor;

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 top.yang.intelAI.entity.LoginInfoVo;
import top.yang.intelAI.service.LoginService;
import top.yang.intelAI.util.ErrorCodeEnum;
import top.yang.intelAI.util.FormatReqResDataParamsUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class InitInterceptor implements HandlerInterceptor {

    @Autowired
    LoginService loginService; //service接口

    private static final Logger logger = LoggerFactory.getLogger(InitInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        RequestWrapper myRequestWrapper = new RequestWrapper((HttpServletRequest) request);
        response.setCharacterEncoding("utf-8");
        Map params = FormatReqResDataParamsUtils.getRequestOriginParams(request);
        String sessionId = (String) params.get("sessionId");
        if(params ==null || sessionId==null || sessionId.length() == 0){
            String responseString = FormatReqResDataParamsUtils.formatResponseParams(ErrorCodeEnum.NOT_LOGIN_ACCOUNT_ERROR,new HashMap<>());
            response.getWriter().print(responseString);
            return  false;
        }
        LoginInfoVo loginInfoVo = loginService.getLoginInfo(sessionId);
        if(loginInfoVo == null){
            String responseString = FormatReqResDataParamsUtils.formatResponseParams(ErrorCodeEnum.NOT_LOGIN_ACCOUNT_ERROR,new HashMap<>());
            response.getWriter().print(responseString);
            return  false;
        }
        return true;
    }

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

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {
    }
}
package top.yang.intelAI.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;


public class FormatReqResDataParamsUtils {
    public String resJSON = "{msg:'',code;0,data:{}}}";

    /**
     * 格式化返回参数
     *
     * @return
     */
    public static String formatResponseParams(ErrorCodeEnum notAccountError, Object params) {
        Map map = new HashMap();
        map.put("code", notAccountError.getCode());
        map.put("msg", notAccountError.getDesc());
        map.put("data", params);
        String returnData = new Gson().toJson(map);
        return returnData;
    }

    public static Map getRequestParams(HttpServletRequest request) {
        BufferedReader bufferReader;
        try {
            bufferReader = new BufferedReader(request.getReader());
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = bufferReader.readLine()) != null) {
                sb.append(line);
            }
            String decodeUrl = URLDecoder.decode(sb.toString(), "UTF-8");
            Map addReptitleData =  new Gson().fromJson(decodeUrl, Map.class);
            if (addReptitleData.containsKey("data")) {
                String allDataParams = URLDecoder.decode((String) addReptitleData.get("data"), "UTF-8");
                Map params = new Gson().fromJson(allDataParams, Map.class);
                return params;
            }
            return addReptitleData;
        }catch(Exception e) {
            return new HashMap();
        }
    }

    public static Map getOriginRequestParams(HttpServletRequest request) {
        BufferedReader bufferReader;
        try {
            bufferReader = new BufferedReader(request.getReader());
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = bufferReader.readLine()) != null) {
                sb.append(line);
            }
            String decodeUrl = URLDecoder.decode(sb.toString(), "UTF-8");
            String allDataParams = decodeUrl;
            Map params = new Gson().fromJson(allDataParams, Map.class);
            return params;
        }catch(Exception e) {
            return new HashMap();
        }
    }

    public static Map getRequestOriginParams(HttpServletRequest request) {
        BufferedReader bufferReader;
        try {
            bufferReader = new BufferedReader(request.getReader());
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = bufferReader.readLine()) != null) {
                sb.append(line);
            }
            String decodeUrl = URLDecoder.decode(sb.toString(), "UTF-8");
            Map addReptitleData = new Gson().fromJson(decodeUrl, Map.class);
            if (addReptitleData.containsKey("data")) {
                Map params = new Gson().fromJson(URLDecoder.decode((String) addReptitleData.get("data"), "UTF-8"), Map.class);
                addReptitleData.put("data", params);
                return addReptitleData;
            }
            return addReptitleData;
        } catch (Exception e) {
            return new HashMap();
        }
    }
}
package top.yang.intelAI.interceptor;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
public class RequestWrapper extends HttpServletRequestWrapper {

    /**
     * 存储请求数据
     */
    private String body;

    public RequestWrapper(HttpServletRequest request) {
        super(request);
        renewBody(request);
    }

    /**
     * 重写getInputStream方法
     *
     * @return
     */
    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
        ServletInputStream servletInputStream = new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
            }

            @Override
            public int read() {
                return byteArrayInputStream.read();
            }
        };
        return servletInputStream;

    }

    /**
     * 重写getReader方法
     *
     * @return
     */
    @Override
    public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    /**
     * 读取body的值
     *
     * @param request
     */
    private void renewBody(HttpServletRequest request) {
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
        try {
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
        body = stringBuilder.toString();
    }

    public String getBody() {
        return body;
    }
}

 

你可能感兴趣的:(拦截器,spring,boot)