Spring的Annotation搞定所有

首先是一个叫MyMvcConfig的类, 里面相当于当年的spring-mvc配置.xml

@Configuration
@EnableWebMvc
@ComponentScan("com.wulala.controller")
public class MyMvcConfig extends WebMvcConfigurerAdapter {
    // 这只是一个普通的配置类, 配置了JSP的ViewResolver用来指定映射路径
    // 跟文件扩展名,@EnableWebMvc注解会开启一些默认配置
    // 继承会用下面的addResource的方式进行配置

    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/classes/views/");
        viewResolver.setSuffix(".jsp");
        viewResolver.setViewClass(JstlView.class);
        System.out.println("from view resolver");
        return viewResolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/assets/**").addResourceLocations("classpath://assets/");
    }

    @Bean
    public DemoInterceptor demoInterceptor() {
        return new DemoInterceptor();
    }

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

}

一方面它指定了jsp视图的位置

一方面它加入了一个Interceptor, 这个注入器, 是一个HandlerInterceptorAdapter, 每个请求执行前后都可以做点儿事:

public class DemoInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        request.setAttribute("startTime", startTime);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modleAndView) throws Exception {
        long startTime = (Long) request.getAttribute("startTime");
        request.removeAttribute("startTime");
        long endTime = System.currentTimeMillis();
        System.out.println("本次请求处理时间为:" + new Long(endTime - startTime) + "ms");
        request.setAttribute("handlingTime", endTime - startTime);
    }
}

然后是一个WebInitializer

public class WebInitializer implements WebApplicationInitializer {
    
    public void onStartup(ServletContext servletContext)throws ServletException{
        AnnotationConfigWebApplicationContext ctx=new AnnotationConfigWebApplicationContext();
        ctx.register(MyMvcConfig.class);
        ctx.register(MyMvcConfig.class);
        ctx.setServletContext(servletContext);
        
        //注册DispatcherServlet
        Dynamic servlet=servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
      
        servlet.addMapping("/");
        servlet.setLoadOnStartup(1);
        
    }

}

跟servlet相关, 配置根地址的映射?

Controller就不贴了, 总之, 这种纯用java类方式配置, 嗯, 很新颖, 很潮流?

唔知, 继续, 可能下面会很好玩.

 

哦对了, 有了这个Interceptor, 可以在控制台输出一下请求使用的时间, 估计后面为实时监控服务器的状态打下基础.

posted @ 2018-10-23 11:01  Montauk  阅读(138)  评论(0编辑  收藏  举报