当前位置: 萬仟网 > IT编程>开发语言>Java > spring boot使用拦截器修改请求URL域名 换 IP 访问的方法

spring boot使用拦截器修改请求URL域名 换 IP 访问的方法

2022年09月18日 Java 我要评论
interceptor 介绍拦截器(interceptor)同 filter 过滤器一样,它俩都是面向切面编程——aop 的具体实现(aop切面编程只是一种编程思想而已)。你可

interceptor 介绍

拦截器(interceptor)同 filter 过滤器一样,它俩都是面向切面编程——aop 的具体实现(aop切面编程只是一种编程思想而已)。

你可以使用 interceptor 来执行某些任务,例如在 controller 处理请求之前编写日志,添加或更新配置…

在 spring中,当请求发送到 controller 时,在被controller处理之前,它必须经过 interceptors(0或多个)。

spring interceptor是一个非常类似于servlet filter 的概念 。

interceptor 作用

日志记录:记录请求信息的日志,以便进行信息监控、信息统计、计算 pv(page view)等;
权限检查:如登录检测,进入处理器检测是否登录;
性能监控:通过拦截器在进入处理器之前记录开始时间,在处理完后记录结束时间,从而得到该请求的处理时间。(反向代理,如 apache 也可以自动记录)
通用行为:读取 cookie 得到用户信息并将用户对象放入请求,从而方便后续流程使用,还有如提取 locale、theme 信息等,只要是多个处理器都需要的即可使用拦截器实现。

自定义 interceptor

如果你需要自定义 interceptor 的话必须实现 org.springframework.web.servlet.handlerinterceptor接口或继承 org.springframework.web.servlet.handler.handlerinterceptoradapter类,并且需要重写下面下面 3 个方法:

prehandler(httpservletrequest request, httpservletresponse response, object handler) 方法在请求处理之前被调用。该方法在 interceptor 类中最先执行,用来进行一些前置初始化操作或是对当前请求做预处理,也可以进行一些判断来决定请求是否要继续进行下去。该方法的返回至是 boolean 类型,当它返回 false 时,表示请求结束,后续的 interceptor 和 controller 都不会再执行;当它返回为 true 时会继续调用下一个 interceptor 的 prehandle 方法,如果已经是最后一个 interceptor 的时候就会调用当前请求的 controller 方法。
posthandler(httpservletrequest request, httpservletresponse response, object handler, modelandview modelandview) 方法在当前请求处理完成之后,也就是 controller 方法调用之后执行,但是它会在 dispatcherservlet 进行视图返回渲染之前被调用,所以我们可以在这个方法中对 controller 处理之后的 modelandview 对象进行操作。
aftercompletion(httpservletrequest request, httpservletresponse response, object handle, exception ex) 方法需要在当前对应的 interceptor 类的 posthandler 方法返回值为 true 时才会执行。顾名思义,该方法将在整个请求结束之后,也就是在 dispatcherservlet 渲染了对应的视图之后执行。此方法主要用来进行资源清理。

接下来结合实际代码进行学习。

案例1 :域名换ip访问

package com.config;
import org.springframework.http.httprequest;
import org.springframework.http.client.clienthttprequestexecution;
import org.springframework.http.client.clienthttprequestinterceptor;
import org.springframework.http.client.clienthttpresponse;
import org.springframework.http.client.support.httprequestwrapper;
import org.springframework.stereotype.component;
import org.springframework.web.util.uricomponentsbuilder;
import java.io.ioexception;
import java.net.uri;
@component
public class interceptor implements clienthttprequestinterceptor {
    /**
     * intercept the given request, and return a response. the given {@link clienthttprequestexecution} allows
     * the interceptor to pass on the request and response to the next entity in the chain.
     *
     * <p>a typical implementation of this method would follow the following pattern:
     * <ol>
     * <li>examine the {@linkplain httprequest request} and body</li>
     * <li>optionally {@linkplain httprequestwrapper wrap} the request to filter http attributes.</li>
     * <li>optionally modify the body of the request.</li>
     * <li><strong>either</strong>
     * <ul>
     * <li>execute the request using {@link clienthttprequestexecution#execute(httprequest, byte[])},</li>
     * <strong>or</strong>
     * <li>do not execute the request to block the execution altogether.</li>
     * </ul>
     * <li>optionally wrap the response to filter http attributes.</li>
     * </ol>
     *
     * @param request   the request, containing method, uri, and headers
     * @param body      the body of the request
     * @param execution the request execution
     * @return the response
     * @throws ioexception in case of i/o errors
     */
    @override
    public clienthttpresponse intercept(httprequest request, byte[] body, clienthttprequestexecution execution) throws ioexception {
        string str = request.geturi().tostring();
        string str1 = str.replace("https://baidu.com", "http://39.156.66.10:8080");
        uri newuri = uricomponentsbuilder.fromuri(uri.create(str)).build().touri();
         return execution.execute(new urimodifyhttprequestwrapper(request, newuri), body);
    }
    private static class urimodifyhttprequestwrapper extends httprequestwrapper {
        private final uri uri;
        public urimodifyhttprequestwrapper(httprequest request, uri uri) {
            super(request);
            this.uri = uri;
        }
        @override
        public uri geturi() {
            return uri;
        }
    }
}

案例2: erverwebexchange通过拦截器修改请求url

@override
public mono<void> filter(serverwebexchange exchange, gatewayfilterchain chain)
{
    serverhttprequest str = exchange.getrequest();
    //新url
    string newpath ="/system/loanorg/list";
    serverhttprequest newrequest = str.mutate().path(newpath).build();
    exchange.getattributes().put("path", newrequest.geturi());
    return chain.filter(exchange.mutate() .request(newrequest).build());
}

案例3: 将请求路径中/idea都去掉

1.定义拦截器

import org.springframework.stereotype.component;
import org.springframework.web.servlet.handlerinterceptor;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpservletresponsewrapper;
@component
public class globalinterceptor implements handlerinterceptor {
    @override
    public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception {
        httpservletresponsewrapper httpresponse = new httpservletresponsewrapper((httpservletresponse) response);
        system.out.println(request.getrequesturi());
        string path=request.getrequesturi();
        if(path.indexof("/idea")>-1){
            path = path.replaceall("/idea","");
            request.getrequestdispatcher(path).forward(request,response);
        }
 
        return true;
    }
}

2.定义webmvcconfig

import com.globalinterceptor;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.annotation.configuration;
import org.springframework.web.servlet.config.annotation.interceptorregistry;
import org.springframework.web.servlet.config.annotation.webmvcconfigurer;
@configuration
public class webmvcconfig implements webmvcconfigurer {
    @autowired
    globalinterceptor globalinterceptor;
 
    @override
    public void addinterceptors(interceptorregistry registry) {
        registry.addinterceptor(globalinterceptor).addpathpatterns("/idea/**");
    }
} 

案例4: springboot 利用过滤器filter修改请求url地址

要求:

代码中配置的url路径为http://127.0.0.1/api/asso

现在要求http://127.0.0.1/asso 也可以同样访问同一个conroller下面的method,并且要求参数全部跟随

代码:

package com.framework.filter;

import java.io.ioexception;
import javax.servlet.filter;
import javax.servlet.filterchain;
import javax.servlet.filterconfig;
import javax.servlet.servletexception;
import javax.servlet.servletrequest;
import javax.servlet.servletresponse;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpservletresponsewrapper;

/**
 * 修改请求路由,当进入url为/a/b时,将其url修改为/api/a/b
 *  
 **/
public class urlfilter implements filter {
    @override
    public void init(filterconfig filterconfig) throws servletexception {
    }

    @override
    public void destroy() {
    }

    @override
    public void dofilter(servletrequest request, servletresponse response, filterchain chain) throws ioexception, servletexception {
        httpservletrequest httprequest = (httpservletrequest)request;
        httpservletresponsewrapper httpresponse = new httpservletresponsewrapper((httpservletresponse) response);
        system.out.println(httprequest.getrequesturi());
        string path=httprequest.getrequesturi();
        if(path.indexof("/api/")<0){
            path="/api"+path;
            system.out.println(path);
            httprequest.getrequestdispatcher(path).forward(request,response);
        }
       else {
            chain.dofilter(request,response);

        }
        return;
    }
}


这个类必须继承filter类,这个是servlet的规范。有了过滤器类以后,以前的web项目可以在web.xml中进行配置,但是spring boot项目并没有web.xml这个文件,那怎么配置?在spring boot中,我们需要filterregistrationbean来完成配置。

其实现过程如下:

package com.shitou.huishi.framework.filter;
import org.springframework.boot.web.servlet.filterregistrationbean;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
/**
 * created by qhong on 2018/5/16 15:28
 **/
@configuration
public class filterconfig {
    @bean
    public filterregistrationbean registfilter() {
        filterregistrationbean registration = new filterregistrationbean();
        registration.setfilter(new urlfilter());
        registration.addurlpatterns("/*");
        registration.setname("urlfilter");
        registration.setorder(1);
        return registration;
    }
}

案例5.拦截器: webmvcconfigureradapter拦截器

拦截所有请求

	@configuration
	public class custmvcconfigureradapter extends webmvcconfigureradapter {
    @autowired
    private custinterceptor custinterceptor;
    @override
    public void addinterceptors(interceptorregistry registry) {
        registry.addinterceptor(custinterceptor).addpathpatterns("/**");
    }
}
排除指定路径

    @override
    public void addinterceptors(interceptorregistry registry) {
        registry.addinterceptor(custinterceptor).addpathpatterns("/**").excludepathpatterns("/select/**");
    }

拦截指定路径

@override
public void addinterceptors(interceptorregistry registry) {
    registry.addinterceptor(custinterceptor).addpathpatterns("/user/**");
}

custinterceptor具体拦截类

@component
public class custinterceptor extends handlerinterceptoradapter {
	   @override
    public boolean prehandle(httpservletrequest request, httpservletresponse response, object handler) throws exception {
        boolean needlogin = needlogin(request);
        if (!needlogin) {
            return true;
        }
        boolean islogin = checklogin(request, response);
        return islogin;
    }
}

结语

到此这篇关于spring boot使用拦截器修改请求url域名 换 ip 访问的文章就介绍到这了,更多相关spring boot拦截器修改请求url域名内容请搜索萬仟网以前的文章或继续浏览下面的相关文章希望大家以后多多支持萬仟网!

(0)
打赏 微信扫一扫 微信扫一扫

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。

发表评论

验证码:
Copyright © 2017-2022  萬仟网 保留所有权利. 琼ICP备2022007597号