栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用Spring拦截器做转发

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用Spring拦截器做转发


一、简介

使用spring的WebMvcConfigurer和HandlerInterceptor来拦截和转发到另外的服务对应的请求,可以在转发过程中添加或者删除原请求的一些参数。


二、基本使用
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Configuration
public class LocalServiceDispatcher implements WebMvcConfigurer, HandlerInterceptor {

    // MD5盐值
    static final String SALT = "aaa";

	private static String url;

    private static int port;

    @Autowired
    LocalBean local;

    @Bean
    public void setValue() {
        url = local.getUrl();
        port = local.getPort();
    }
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    	// 以/local起始的所有请求,都将进行拦截,进入preHandle中
        registry.addInterceptor(new LocalServiceDispatcher()).addPathPatterns("/local/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 最终返回结果
        HttpResponse result;

        String uri = request.getRequestURI().replace("/jeecg-boot", "");
        String targetAddress = "http://" + url + ":" + port + uri;
        log.info("监听到请求local相关接口,转发到地址:" + url);

        Map parameterMap = request.getParameterMap();

        // 得到参数
        // 基本参数
        HashMap map = new HashMap<>();
        for (Map.Entry entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue()[0];
            map.put(key, value);
        }
        // 加入认证参数
        String timestamp = String.valueOf(DateUtil.current());
        // 加盐然后进行MD5
        String stage = SALT + timestamp;
        String md5 = SecureUtil.md5(stage);
        map.put("sign", md5);
        map.put("timestamp", timestamp);

        // 是否为文件上传
        Part file = null;
        try {
            file = request.getPart("file");
        } catch (Exception ignore) {
        }
        if (file != null) {
            // 获取文件
            String fileName = file.getSubmittedFileName();
            String stageFilePath = System.getProperty("user.dir") + "/stage";
            // 文件夹不存在则创建
            File folder = new File(stageFilePath);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            // 写出文件
            String filePath = stageFilePath + "/" + fileName;
            file.write(filePath);
            File outFile = new File(stageFilePath + "/" + fileName);
            // 直接返回结果
            result = HttpUtil.createPost(targetAddress).contentType("multipart/form-data").formStr(map).form("file", outFile).execute();
            outFile.delete();
            // 最后删除文件
        } else {
            result = HttpUtil.createPost(targetAddress).formStr(map).execute();
        }
//        System.out.println(result);
        // 避免乱码
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(result.body());

        // 仅提供结果到前端,不再继续执行其他内容
        return false;
    }
}

三、使用配置文件自定义转发地址

配置文件

local:
  url: 127.0.0.1
  port: 8090
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Configuration
public class LocalServiceDispatcher implements WebMvcConfigurer, HandlerInterceptor {

    // MD5盐值
    static final String SALT = "aaa";

 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    	// 以/local起始的所有请求,都将进行拦截,进入preHandle中
        registry.addInterceptor(new LocalServiceDispatcher()).addPathPatterns("/local/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 最终返回结果
        HttpResponse result;

        String uri = request.getRequestURI().replace("/jeecg-boot", "");
        String targetAddress = "http://localhost:8080" + uri;
        log.info("监听到请求local相关接口,转发到地址:" + url);

        Map parameterMap = request.getParameterMap();

        // 得到参数
        // 基本参数
        HashMap map = new HashMap<>();
        for (Map.Entry entry : parameterMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue()[0];
            map.put(key, value);
        }
        // 加入认证参数
        String timestamp = String.valueOf(DateUtil.current());
        // 加盐然后进行MD5
        String stage = SALT + timestamp;
        String md5 = SecureUtil.md5(stage);
        map.put("sign", md5);
        map.put("timestamp", timestamp);

        // 是否为文件上传
        Part file = null;
        try {
            file = request.getPart("file");
        } catch (Exception ignore) {
        }
        if (file != null) {
            // 获取文件
            String fileName = file.getSubmittedFileName();
            String stageFilePath = System.getProperty("user.dir") + "/stage";
            // 文件夹不存在则创建
            File folder = new File(stageFilePath);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            // 写出文件
            String filePath = stageFilePath + "/" + fileName;
            file.write(filePath);
            File outFile = new File(stageFilePath + "/" + fileName);
            // 直接返回结果
            result = HttpUtil.createPost(targetAddress).contentType("multipart/form-data").formStr(map).form("file", outFile).execute();
            outFile.delete();
            // 最后删除文件
        } else {
            result = HttpUtil.createPost(targetAddress).formStr(map).execute();
        }
//        System.out.println(result);
        // 避免乱码
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(result.body());

        // 仅提供结果到前端,不再继续执行其他内容
        return false;
    }
}


@Configuration
@Data
@AllArgsConstructor
@NoArgsConstructor
@ConfigurationProperties(prefix = "local")
class LocalBean {
    private String url;
    private int port;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/337058.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号