大家好,我想在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);
}
类似的东西。我没有主意。感谢您的帮助。
您可以使用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);
}
}