1 /** 2 * Licensed to the Apache Software Foundation (ASF) under one or more 3 * contributor license agreements. See the NOTICE file distributed with 4 * this work for additional information regarding copyright ownership. 5 * The ASF licenses this file to You under the Apache License, Version 2.0 6 * (the "License"); you may not use this file except in compliance with 7 * the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package org.apache.geronimo.console.servlet; 19 20 import java.io.IOException; 21 22 import javax.servlet.RequestDispatcher; 23 import javax.servlet.ServletConfig; 24 import javax.servlet.ServletContext; 25 import javax.servlet.ServletException; 26 import javax.servlet.UnavailableException; 27 import javax.servlet.http.HttpServlet; 28 import javax.servlet.http.HttpServletRequest; 29 import javax.servlet.http.HttpServletResponse; 30 31 /** 32 * Servlet that forwards GET and POST requests to a servlet 33 * in an alternate context. The servlet path and alternate 34 * context are passed in as configuration parameters (e.g. 35 * via <config-param> elements in the web.xml). 36 */ 37 public class ContextForwardServlet extends HttpServlet { 38 39 // name of the configuration parameter containing the context path 40 public static final String CONTEXT_PATH = "context-path"; 41 // name of the configuration parameter containing the servlet path 42 public static final String SERVLET_PATH = "servlet-path"; 43 44 private String servletPath; 45 private String contextPath; 46 47 public void init(ServletConfig config) throws ServletException { 48 super.init(config); 49 contextPath = config.getInitParameter(CONTEXT_PATH); 50 servletPath = config.getInitParameter(SERVLET_PATH); 51 if (contextPath == null || servletPath == null) { 52 throw new UnavailableException("context-path and servlet-path " + 53 "must be provided as configuration parameters"); 54 } 55 } 56 57 public void doGet(HttpServletRequest req, HttpServletResponse resp) 58 throws ServletException, IOException { 59 doPost(req, resp); 60 } 61 62 public void doPost(HttpServletRequest req, HttpServletResponse resp) 63 throws ServletException, IOException { 64 String dispatchURI = servletPath + (req.getPathInfo() == null ? "" : req.getPathInfo()); 65 String queryString = req.getQueryString(); 66 if (queryString != null) { 67 dispatchURI += "?" + queryString; 68 } 69 ServletContext forwardContext = getServletContext().getContext(contextPath); 70 RequestDispatcher dispatcher = forwardContext.getRequestDispatcher(dispatchURI); 71 dispatcher.forward(req, resp); 72 } 73 }