001 /*******************************************************************************
002 * Copyright (c) PicoContainer Organization. All rights reserved.
003 * ---------------------------------------------------------------------------
004 * The software in this package is published under the terms of the BSD style
005 * license a copy of which has been included with this distribution in the
006 * LICENSE.txt file.
007 ******************************************************************************/
008
009 package org.picocontainer.web;
010
011 import org.picocontainer.injectors.ProviderAdapter;
012 import org.picocontainer.MutablePicoContainer;
013
014 import javax.servlet.http.HttpServletRequest;
015
016 /**
017 * Use this to make a request level component that pulls an string from a named parameter (GET or POST)
018 * of the request. If a parameter of the supplied name is not available for the current
019 * request path, then an exception will be thrown.
020 */
021 public class StringFromRequest extends ProviderAdapter {
022 private final String paramName;
023
024 public StringFromRequest(String paramName) {
025 this.paramName = paramName;
026 }
027
028 @Override
029 public Class getComponentImplementation() {
030 return String.class;
031 }
032
033 @Override
034 public Object getComponentKey() {
035 return paramName;
036 }
037
038 public Object provide(HttpServletRequest req) {
039 String parameter = req.getParameter(paramName);
040 if (parameter == null) {
041 throw new RuntimeException(paramName + " not in request parameters");
042 }
043 return parameter;
044 }
045
046 /**
047 * Add a number of StringFromRequest adapters to a container.
048 * @param toContainer the container to add to
049 * @param names the list of names to make adapters from
050 */
051 public static void addStringRequestParameters(MutablePicoContainer toContainer, String... names) {
052 for (String name : names) {
053 toContainer.addAdapter(new StringFromRequest(name));
054 }
055 }
056 }