使用springMVC我们一般都会在web.xml中配置一个dispatcher,现在我们基于用java代码的方式来使用springMVC
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan public class MVCConfig { @Bean public InternalResourceViewResolver viewResolver(){ InternalResourceViewResolver viewResolver=new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/"); viewResolver.setSuffix(".jsp"); viewResolver.setViewClass(JstlView.class); return viewResolver; } }
以上是一个普通的spring配置类,在其中是配置了一个jsp的ViewResolver,相信熟悉springMVC的知道这个ViewResolver。
@Configuration声明当前类为配置类,
@EnableWebMvc注解会开启一些默认配置,如ViewResolver
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; public class WebConfig implements WebApplicationInitializer{ @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext context=new AnnotationConfigWebApplicationContext(); context.register(MVCConfig.class); context.setServletContext(servletContext); Dynamic servlet=servletContext.addServlet("dispatcher", new DispatcherServlet(context)); servlet.addMapping("/"); servlet.setLoadOnStartup(1); } }
以上代码其实就相当于我们在web.xml中配置的dispatcher,webApplicationInitializer是spring提供用来配置Servlet3.0+配置的接口,从而实现了替代web.xml的位置,实现此接口将会自动被SpringServletContainerInitialzer(用来启动Servlet3.0容器)获取到,然后我们需要注册我们前面写的MVCConfig配置类,并将其和当前servletContext关联。
import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class HelloController { @RequestMapping("index") public String hello(){ return "index"; } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> Hello World </body> </html>
上面就是一个控制器和相应的index.jsp代码,将项目部署到tomcat中,启动,访问相应的URL。
注:以上分享来自 JavaEE开发的颠覆者: Spring Boot实战书籍