干掉 web.xml
基于 servelet3.0,完全注解,将 web.xml 消灭掉.
WebApplicationInitializer 代替 web.xml 工作
基于注解的方式,在应用启动之前,使用该类去注册相关拦截器和 servlet.这里主要说 springmvc 的注册,主要是注册 dispatcherservlet,初始化 web 的代码如下:
springmvc 配置
public class WebInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
//注册springmvc
ctx.register(SpringMvcConfig.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
//拦截所有请求
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
通过注解的形式进行 springmvc 的配置,代替原始的 springmvc.xml.
这里涉及到 springmvc 的一个渲染器和静态资源的注册.
/**
* springmvc的配置
* 注解解释为:
* 配置类
* 允许使用springmvc,启用之后会开启一些默认配置,比如ViewResolver
* 扫描包为com.cx.os
*/
@Configuration
@EnableWebMvc
@ComponentScan("com.cx.os")
public class SpringMvcConfig extends WebMvcConfigurerAdapter{
@Bean
public InternalResourceViewResolver viewResolver(){
//viewresolver来渲染页面
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
//指定渲染页面路径
viewResolver.setPrefix("/WEB-INF/views/");
//指定页面格式
viewResolver.setSuffix(".jsp");
//使用jstl标准进行页面的渲染
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/statics/**").addResourceLocations("/WEB-INF/statics/");
}
渲染器:主要有 jstl 和 jsp 两种,在设置 viewclass 之前需要设置渲染页面的路径和页面的格式,使用如下方法进行设置:
静态资源注册
//指定渲染页面路径
viewResolver.setPrefix("/WEB-INF/views/");
//指定页面格式
viewResolver.setSuffix(".jsp");
springmvc 默认拦截了所有页面请求,同时包括 CSS 和 js 文件.重写 addResourceHandlers 方法进行资源拦截,其中 addResourceHandler 为请求路径,addResourceLocations 为实际路径.
验证静态资源是否设置成功的方式:
直接在浏览器访问资源文件如:localhost:8080/statics/js/jquery.js,看是否正常访问到资源.
sitemesh 拦截器
sitemesh3.0 提供了基于注解的配置方式,集成 ConfigurableSiteMeshFilter 之后,重写 applyCustomConfiguration 方法.
其中,webfilter 取代 web.xml 的拦截器.而重写的 applyCustomConfiguration 方法里面对应的 addDecoratorPath 方法两个参数分别为,装饰页面和装饰模板.上面代码表示使用 decorator.jsp 装饰所有页面.这里需要注意一下装饰模板的路径.
@WebFilter(filterName = "sitemesh",urlPatterns = {"/*")
public class MySiteMeshFilter extends ConfigurableSiteMeshFilter{
@Override
protected void applyCustomConfiguration(SiteMeshFilterBuilder builder) {
//使用decorator.jsp去装配所有的页面
builder.addDecoratorPath("/*","/decorator.jsp");
}
}
注意事项
在进行 maven 打包的时候报错,找不到 web.xml 文件.通过配置 pom 文件解决该问题:
注意使用 maven tomcat 插件的时候,该插件默认打包的 web 路径为 webapp,将展示 jsp 和 html 文件放在 webapp 下面可以正常访问,放到 resources 下面则不能正常访问.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
如何去配置打包属性 [warSourceDirectory],暂未找出合理方法
见 apache 官方文档 ,这里面有讲解,暂未找到解决方案.
如果,你的资源文件在 resources 下面,那么只能使用 tomcat 发布或者将资源文件放到 webapp 下面.
来源: http://www.jianshu.com/p/4895cf38f503