我如何在spring mvc java中自定义过滤302状态代码,并将response.redirect重定向到自定义页面?

问题描述 投票:0回答:1

大家好,我想在java spring上创建RedirectionFilter。主要目的是在检测到状态代码302之后发送重定向并将响应内容替换为自定义文本内容。第一个问题是不知道如何捕获响应代码302。这是我目前的想法。

public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) (request);
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        String redirectURL="www.google.com";
if(statuscode == 302 ){
httpServletResponse.sendRedirect(redirectURL);
}

类似的东西。我没有主意。感谢您的帮助。

java spring-mvc servlets filter
1个回答
0
投票

您可以使用HandlerInterceptorAdapter在每次调用后获取响应,并且可以验证响应代码并执行必要的操作

@Component
public class TestInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.Object object) throws Exception {
    System.out.println("test");
    return true;
}
@Override
public void afterCompletion(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response, java.lang.Object handler, @org.springframework.lang.Nullable java.lang.Exception ex) throws java.lang.Exception {
    if(response.getStatus()==302){
        // your code
    }
}
}

创建拦截器后需要在InterceptorRegistry中进行注册

@Component
public class InterceptorsConfig implements WebMvcConfigurer {

    @Autowired
    private TestInterceptor testInterceptor;

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

一旦触发请求,控件将首先到达拦截器。

Restcontroller示例

@RestController
@RequestMapping("/test")
public class Restcontroller {

    @GetMapping
    public ModelAndView redirectWithUsingRedirectPrefix(ModelMap model) {
        model.addAttribute("attribute", "redirectWithRedirectPrefix");
        return new ModelAndView("redirect:/redirectedUrl", model);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.