Kiran Joshi
Kiran Joshi

Reputation: 746

Usage of interceptor in spring

This is the situation :

Why Am I using interceptor ?

I want to write a module which stores the data about all the requests that are being served at my server. This data would help me very well in doing data visualizations.

How am I using currently?

@Component
public class MyCustomInterceptor extends HandlerInterceptorAdapter{         
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception
    {
        System.out.println("In Interceptor");       
        return true;
    }       
    public void postHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
        System.out.println("In Post Handler");
    }       
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        System.out.println("After completion");
    }           
}

And I am registering interceptor as below,

@Configuration
@EnableWebMvc
@ComponentScan(basePackages="demo.mycustom")
public class MyInterceptorConfig extends WebMvcConfigurerAdapter{

    @Autowired
    MyCustomInterceptor obj;

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

Now the challenge here is,

When I try to login "localhost:8096/myApp/#/login", this is returning me 404 page not found. This is being observed only when I add interceptor configuration. Although I think this is needed as I have to tell my application that this is the interceptor that I want to register.

What can be done here?

Observations :

When I debug and see inside preHandle the interesting point was "handler" parameter was giving me org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml where as when I use the application normally (Without interceptor) I am getting as org.springframework.web.servlet.mvc.ParameterizableViewController@1bff7859

This diverted my mind to have addViewControllers inside the interceptor configuration. But I have no idea as to how to add them and what to add them. I tried adding a view controller for "/" and "/login" with view names accordingly. But somehow it doesn't work.

Could someone enlighten me in this. I have gone through almost all the links in the stackoverflow on this and could not find anything, may be I could not relate to my requirement.

Upvotes: 4

Views: 1517

Answers (1)

Kiran Joshi
Kiran Joshi

Reputation: 746

The problem is solved by removing EnableWebMvc annotation. I din't knew what it does ;)

I missed the below piece while reading,

enter image description here

I never wanted complete control over spring MVC. I just wanted to implement the interceptor.

Upvotes: 1

Related Questions