001/* 002 * Copyright 2012-2018 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.boot.docs.cloudfoundry; 018 019import java.io.IOException; 020import java.util.Collections; 021 022import javax.servlet.GenericServlet; 023import javax.servlet.Servlet; 024import javax.servlet.ServletContainerInitializer; 025import javax.servlet.ServletContext; 026import javax.servlet.ServletException; 027import javax.servlet.ServletRequest; 028import javax.servlet.ServletResponse; 029 030import org.apache.catalina.Host; 031import org.apache.catalina.core.StandardContext; 032import org.apache.catalina.startup.Tomcat; 033 034import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory; 035import org.springframework.boot.web.servlet.ServletContextInitializer; 036import org.springframework.context.annotation.Bean; 037 038/** 039 * Example configuration for custom context path in Cloud Foundry. 040 * 041 * @author Johnny Lim 042 */ 043public class CloudFoundryCustomContextPathExample { 044 045 // tag::configuration[] 046 @Bean 047 public TomcatServletWebServerFactory servletWebServerFactory() { 048 return new TomcatServletWebServerFactory() { 049 050 @Override 051 protected void prepareContext(Host host, 052 ServletContextInitializer[] initializers) { 053 super.prepareContext(host, initializers); 054 StandardContext child = new StandardContext(); 055 child.addLifecycleListener(new Tomcat.FixContextListener()); 056 child.setPath("/cloudfoundryapplication"); 057 ServletContainerInitializer initializer = getServletContextInitializer( 058 getContextPath()); 059 child.addServletContainerInitializer(initializer, Collections.emptySet()); 060 child.setCrossContext(true); 061 host.addChild(child); 062 } 063 064 }; 065 } 066 067 private ServletContainerInitializer getServletContextInitializer(String contextPath) { 068 return (c, context) -> { 069 Servlet servlet = new GenericServlet() { 070 071 @Override 072 public void service(ServletRequest req, ServletResponse res) 073 throws ServletException, IOException { 074 ServletContext context = req.getServletContext() 075 .getContext(contextPath); 076 context.getRequestDispatcher("/cloudfoundryapplication").forward(req, 077 res); 078 } 079 080 }; 081 context.addServlet("cloudfoundry", servlet).addMapping("/*"); 082 }; 083 } 084 // end::configuration[] 085 086}