Using an interceptor in spring

In this situation:

Why am I using an interceptor?

I want to write a module that stores data about all requests that are submitted to my server. This data would help me a lot in data visualization.

How am I currently using?

@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 the interceptor like 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 problem is here,

When I try to login "localhost: 8096 / myApp / # / login" it returns me 404 pages that were not found. This is only observed when adding an interceptor configuration. Although I think this is necessary as I have to tell my application that this is the interceptor I want to register.

What can you do here?

Observations:

When I debug and see inside the preHandle the interesting point was the "handler" parameter which gave me org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml

where when I normally use the application (no interceptor) I get likeorg.springframework.web.servlet.mvc.ParameterizableViewController@1bff7859

It took my mind off to have addViewControllers inside the interceptor config. But I have no idea how to add them or what to add. I tried to add a view controller for "/" and "/ login" respectively with the view names. But somehow it doesn't work.

Can anyone enlighten me on this. I went through almost all the links in stackoverflow on this and couldn't find anything, maybe I couldn't relate to my requirement.

+3


source to share


1 answer


This issue is addressed by removing the EnableWebMvc annotation. I didn't know what he was doing;)

I missed the following snippet while reading,



enter image description here

I never need full control over spring MVC. I just wanted to implement an interceptor.

+1


source







All Articles