使用Servlet3.0+无web.xml的配置方式,在SpringMVC里实现WebApplicationInitializer接口便可实现等同于web.xml的配置。
pom.xml 配置文件的内容略…
index.jsp
在src/main/resources下建立views目录,并在此目录下新建index.jps
MyMvcConfig.java
@Configuration
@EnableWebMvc
@ComponentScan("com.netant.spring4")
public class MyMvcConfig {
/** 视图解析器 */
@Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/"); // 运行时的目录结构
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
}
Web配置
WebInitializer.java
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
/**
* WebApplicationInitializer是Spring用来提供配置Servlet3.0+的接口,
* 从而实现了替代web.xml的配置。实现此接口将会自动被SpringServletContainerInitializer(用来启动Servlet3.0容器)获取到。
*/
public class WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(MyMvcConfig.class);
context.setServletContext(servletContext); // 新建WebApplicationContext,注册配置类,并将其和当前ServletContext关联
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(context)); // 注册Spring MVC的DispatcherServlet
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
简单控制器
@Controller
public class HelloController {
@RequestMapping("/index")
public String sayHello(){
return "index";
}
}
运行
将程序部署到Tomcat中,启动Tomcat并访问http://….
运行结果: