SpringMVC调用全局方法

时间:2017-07-23 16:19:53

标签: spring spring-mvc

我是springMVC的初学者,所以请大家轻松一下......我每次用户输入我的网络应用程序时都会尝试调用方法 的地方。

我尝试ContextRefreshedEvent但它只在应用程序启动时有效。 有没有办法实现这个目标?

3 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

示例

public class MyInterceptoor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, 
               HttpServletResponse response, Object handler) throws Exception {

    }
}

需要在配置中连接拦截器。

  <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/myproject/**"/> 
            <bean class="com.mvc.myproject.MyInterceptoor" />
        </mvc:interceptor>
    </mvc:interceptors>

Spring Documentation HandlerInterceptorAdapter

答案 2 :(得分:0)

对于SpringBoot,您可以这样做。制作HandlerInterceptorAdaptor

@Component
public class AccessInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)  {
        System.out.println("preHandled for controller = " + handler);
        return true;
    }

}

将其添加到Spring WebMvcConfiguration类:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Autowired
    AccessInterceptor accessInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(accessInterceptor).addPathPatterns("/**");
    }
}

享受......