返回顶部

收藏

Spring 3.1 在 Servlet 3.0 中无 XML 配置

更多

Spring 3.1 增加了对 Servlet 3.0 的支持,在 Servlet 3.0 中,一个标准的Web项目可以不再需要 web.xml ,但 Spring 如何处理呢?原文:http://blog.codeleak.pl/2011/06/spring-31-mvc-xml-free- configuration-in.html

Initializer.java

public class Initializer implements WebApplicationInitializer {
 public void onStartup(ServletContext servletContext)
   throws ServletException {
  AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
  mvcContext.register(MvcConfig.class);
  mvcContext.refresh();

  ServletRegistration.Dynamic dispatcher = servletContext.addServlet(
    "dispatcher", new DispatcherServlet(mvcContext));
  dispatcher.setLoadOnStartup(1);
  dispatcher.addMapping("/app/*");
 }
}

MvcConfig.java

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "pl.codeleak.springmvc31demo.web")
public class MvcConfig {
 @Bean
 public InternalResourceViewResolver configureInternalResourceViewResolver() {
  InternalResourceViewResolver resolver = new InternalResourceViewResolver();
  resolver.setPrefix("/WEB-INF/views/");
  resolver.setSuffix(".jsp");
  return resolver;
 }
}

HomeController.java

@Controller
public class HomeController {

 private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

 @RequestMapping(value = "/", method = RequestMethod.GET)
 public String home() {
  logger.info("Welcome home!");
  return "home";
 }
}

标签:Servlet,Spring

收藏

0人收藏

支持

0

反对

0

发表评论