SpringBoot重写url urlrewrite

猿份哥 5月前 ⋅ 144 阅读

1.扩展UrlRewriteFilter

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.tuckey.web.filters.urlrewrite.Conf;
import org.tuckey.web.filters.urlrewrite.UrlRewriteFilter;

import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import java.io.IOException;

@Configuration
public class UrlRewriteFilterConfig extends UrlRewriteFilter {

    private static final String URL_REWRITE = "classpath:/urlrewrite.xml";

    // Inject the Resource from the given location
    @Value(URL_REWRITE)
    private Resource resource;

    // Override the loadUrlRewriter method, and write your own implementation
    protected void loadUrlRewriter(FilterConfig filterConfig) throws ServletException {
        try {
            // Create a UrlRewrite Conf object with the injected resource
            Conf conf = new Conf(filterConfig.getServletContext(), resource.getInputStream(), resource.getFilename(),
                    "@@traceability@@");
            checkConf(conf);
        } catch (IOException ex) {
            throw new ServletException("Unable to load URL rewrite configuration file from " + URL_REWRITE, ex);
        }
    }
}

2.在resource目录下添加urlrewrite.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE urlrewrite PUBLIC "-//tuckey.org//DTD UrlRewrite 4.0//EN"
        "http://www.tuckey.org/res/dtds/urlrewrite4.0.dtd">
<urlrewrite>
   
    <!-- 栏目详情地址 -->
    <rule>
        <from>^/(\w+)bb(\w+).html</from> <!-- 客户端访问地址 -->
        <to>/order/detail/$1/$2</to><!--服务器controller接收的地址 $1/$2 表示依次替换\w和\w-->
    </rule>
   
</urlrewrite>

全部评论: 0

    我有话说: