spring Sping Boot 中的拦截和转发请求

vqlkdk9b  于 2023-08-02  发布在  Spring
关注(0)|答案(1)|浏览(188)

我在我的application.properties中有以下配置-

server.servlet.context-path=/
spring.mvc.servlet.path=/abc

字符串
我需要将localhost:8080/home.html转发到localhost:8080/abc/home.html
我该怎么做?

eimct9ow

eimct9ow1#

我不知道这怎么能和配置一起工作。我使用一个interceptor for the language slug来做类似的事情。
下面是一个程序化方法的示例:

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;

@Component
public class UrlInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (!request.getRequestURI().startsWith("/abc/")) {
            response.sendRedirect("/abc" + request.getRequestURI());
            return false;
        }
        return true;
    }
}

字符串

配置

import com.example.demo.interceptor.UrlLocaleInterceptor;
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 InterceptorsConfig implements WebMvcConfigurer {
    private final UrlInterceptor urlInterceptor;

    @Autowired
    public InterceptorsConfig(UrlInterceptor urlInterceptor) {
        this.urlInterceptor = urlInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(this.urlInterceptor);
    }
}

相关问题