Reputation: 37
Hi all I want to create RedirectionFilter at java spring. The main purpose is when status code 302 is detected then send redirect and replacing the response content by custom text content. The first problem is don't know how to catch the response code 302. This is my current thinking .
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);
}
Something like that. I have out of ideas. Thanks for helping.
Upvotes: 0
Views: 945
Reputation: 159
You can use HandlerInterceptorAdapter to get the response after each call and can validate the response code and do necessary things
@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
}
}
}
After creating a interceptor need to register it in InterceptorRegistry
@Component
public class InterceptorsConfig implements WebMvcConfigurer {
@Autowired
private TestInterceptor testInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(testInterceptor);
}
}
Once triggering a request, the control will come to interceptor first.
Restcontroller sample
@RestController
@RequestMapping("/test")
public class Restcontroller {
@GetMapping
public ModelAndView redirectWithUsingRedirectPrefix(ModelMap model) {
model.addAttribute("attribute", "redirectWithRedirectPrefix");
return new ModelAndView("redirect:/redirectedUrl", model);
}
}
Upvotes: 1