Java 类javax.servlet.ServletContext 实例源码

项目:ssm-demo    文件:LoadImageController.java   
/**
 *
 *
 * @param request
 * @return
 * @throws Exception
 */
@RequestMapping("/upload")
public String upload(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile file) throws Exception {
    ServletContext sc = request.getSession().getServletContext();
    String dir = sc.getRealPath("/upload");
    String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1, file.getOriginalFilename().length());

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
    Random r = new Random();
    String imgName = "";
    if (type.equals("jpg")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".jpg";
    } else if (type.equals("png")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".png";
    } else if (type.equals("jpeg")) {
        imgName = sdf.format(new Date()) + r.nextInt(100) + ".jpeg";
    } else {
        return null;
    }
    FileUtils.writeByteArrayToFile(new File(dir, imgName), file.getBytes());
    response.getWriter().print("upload/" + imgName);
    return null;
}
项目:Smart-Shopping    文件:WebMvcInitialiser.java   
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    //register config classes
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
    rootContext.register(WebMvcConfig.class);
    rootContext.register(JPAConfig.class);
    rootContext.register(WebSecurityConfig.class);
    rootContext.register(ServiceConfig.class);
    //set session timeout
    servletContext.addListener(new SessionListener(maxInactiveInterval));
    //set dispatcher servlet and mapping
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
            new DispatcherServlet(rootContext));
    dispatcher.addMapping("/");
    dispatcher.setLoadOnStartup(1);

    //register filters
    FilterRegistration.Dynamic filterRegistration = servletContext.addFilter("endcodingFilter", new CharacterEncodingFilter());
    filterRegistration.setInitParameter("encoding", "UTF-8");
    filterRegistration.setInitParameter("forceEncoding", "true");
    //make sure encodingFilter is matched first
    filterRegistration.addMappingForUrlPatterns(null, false, "/*");
    //disable appending jsessionid to the URL
    filterRegistration = servletContext.addFilter("disableUrlSessionFilter", new DisableUrlSessionFilter());
    filterRegistration.addMappingForUrlPatterns(null, true, "/*");
}
项目:incubator-sdap-mudrod    文件:MudrodContextListener.java   
/**
 * @see ServletContextListener#contextInitialized(ServletContextEvent)
 */
@Override
public void contextInitialized(ServletContextEvent arg0) {
  me = new MudrodEngine();
  Properties props = me.loadConfig();
  me.setESDriver(new ESDriver(props));
  me.setSparkDriver(new SparkDriver(props));

  ServletContext ctx = arg0.getServletContext();
  Searcher searcher = new Searcher(props, me.getESDriver(), null);
  Ranker ranker = new Ranker(props, me.getESDriver(), me.getSparkDriver(), "SparkSVM");
  Ontology ontImpl = new OntologyFactory(props).getOntology();
  ctx.setAttribute("MudrodInstance", me);
  ctx.setAttribute("MudrodSearcher", searcher);
  ctx.setAttribute("MudrodRanker", ranker);
  ctx.setAttribute("Ontology", ontImpl);
}
项目:ysoserial-modified    文件:MyfacesTest.java   
private static FacesContext createMockFacesContext () throws MalformedURLException {
    FacesContext ctx = Mockito.mock(FacesContext.class);
    CompositeELResolver cer = new CompositeELResolver();
    FacesELContext elc = new FacesELContext(cer, ctx);
    ServletRequest requestMock = Mockito.mock(ServletRequest.class);
    ServletContext contextMock = Mockito.mock(ServletContext.class);
    URL url = new URL("file:///");
    Mockito.when(contextMock.getResource(Matchers.anyString())).thenReturn(url);
    Mockito.when(requestMock.getServletContext()).thenReturn(contextMock);
    Answer<?> attrContext = new MockRequestContext();
    Mockito.when(requestMock.getAttribute(Matchers.anyString())).thenAnswer(attrContext);
    Mockito.doAnswer(attrContext).when(requestMock).setAttribute(Matchers.anyString(), Matchers.any());
    cer.add(new MockELResolver(requestMock));
    cer.add(new BeanELResolver());
    cer.add(new MapELResolver());
    Mockito.when(ctx.getELContext()).thenReturn(elc);
    return ctx;
}
项目:uavstack    文件:JettyPlusIT.java   
/**
 * getBasePath
 * 
 * @param context
 * @param sContext
 */
private void getBasePath(InterceptContext context, ServletContext sContext) {

    String basePath = sContext.getRealPath("");

    if (basePath == null) {
        return;
    }

    if (basePath.lastIndexOf("/") == (basePath.length() - 1)
            || basePath.lastIndexOf("\\") == (basePath.length() - 1)) {
        basePath = basePath.substring(0, basePath.length() - 1);
    }

    context.put(InterceptConstants.BASEPATH, basePath);
}
项目:lams    文件:UrlController.java   
/**
 * Method associated to a tile and called immediately before the tile 
 * is included.  This implementation calls an <code>Action</code>. 
 * No servlet is set by this method.
 *
 * @param tileContext Current tile context.
 * @param request Current request.
 * @param response Current response.
 * @param servletContext Current servlet context.
 */
public void perform(
    ComponentContext tileContext,
    HttpServletRequest request,
    HttpServletResponse response,
    ServletContext servletContext)
    throws ServletException, IOException {

    RequestDispatcher rd = servletContext.getRequestDispatcher(url);
    if (rd == null) {
        throw new ServletException(
            "Controller can't find url '" + url + "'.");
    }

    rd.include(request, response);
}
项目:autopivot    文件:AutoPivotWebAppInitializer.java   
/**
 * Configure the given {@link ServletContext} with any servlets, filters, listeners
 * context-params and attributes necessary for initializing this web application. See examples
 * {@linkplain WebApplicationInitializer above}.
 *
 * @param servletContext the {@code ServletContext} to initialize
 * @throws ServletException if any call against the given {@code ServletContext} throws a {@code ServletException}
 */
public void onStartup(ServletContext servletContext) throws ServletException {
    // Spring Context Bootstrapping
    AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext();
    rootAppContext.register(AutoPivotConfig.class);
    servletContext.addListener(new ContextLoaderListener(rootAppContext));

    // Set the session cookie name. Must be done when there are several servers (AP,
    // Content server, ActiveMonitor) with the same URL but running on different ports.
    // Cookies ignore the port (See RFC 6265).
    CookieUtil.configure(servletContext.getSessionCookieConfig(), CookieUtil.COOKIE_NAME);

    // The main servlet/the central dispatcher
    final DispatcherServlet servlet = new DispatcherServlet(rootAppContext);
    servlet.setDispatchOptionsRequest(true);
    Dynamic dispatcher = servletContext.addServlet("springDispatcherServlet", servlet);
    dispatcher.addMapping("/*");
    dispatcher.setLoadOnStartup(1);

    // Spring Security Filter
    final FilterRegistration.Dynamic springSecurity = servletContext.addFilter(SPRING_SECURITY_FILTER_CHAIN, new DelegatingFilterProxy());
    springSecurity.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");

}
项目:alvisnlp    文件:DRMAAExecutor.java   
@Override
public void execute(ServletContext servletContext, PlanBuilder planBuilder, Run run, boolean async) {
    SessionFactory sessionFactory = SessionFactory.getFactory();
    Session session = sessionFactory.getSession();
    try {
        session.init("");
        JobTemplate jobTemplate = createJobTemplate(servletContext, session, run);
        String jobId = enqueue(session, run, jobTemplate);
        if (async) {
            String status = waitForStatus(session, jobId);
            if (status != null) {
                run.addStatus(status, "", true);
            }
        }
        session.deleteJobTemplate(jobTemplate);
        session.exit();
    }
    catch (DrmaaException e) {
        throw new RuntimeException(e);
    }
}
项目:lams    文件:I18nFactorySet.java   
/**
 * Initialization method.
 * Init the factory by reading appropriate configuration file.
 * This method is called exactly once immediately after factory creation in
 * case of internal creation (by DefinitionUtil).
 * @param servletContext Servlet Context passed to newly created factory.
 * @param proposedFilename File names, comma separated, to use as  base file names.
 * @throws DefinitionsFactoryException An error occur during initialization.
 */
protected void initFactory(
    ServletContext servletContext,
    String proposedFilename)
    throws DefinitionsFactoryException, FileNotFoundException {

    // Init list of filenames
    StringTokenizer tokenizer = new StringTokenizer(proposedFilename, ",");
    this.filenames = new ArrayList(tokenizer.countTokens());
    while (tokenizer.hasMoreTokens()) {
        this.filenames.add(tokenizer.nextToken().trim());
    }

    loaded = new HashMap();
    defaultFactory = createDefaultFactory(servletContext);
    if (log.isDebugEnabled())
        log.debug("default factory:" + defaultFactory);
}
项目:lams    文件:JspServletWrapper.java   
public JspServletWrapper(ServletContext servletContext,
             Options options,
             String tagFilePath,
             TagInfo tagInfo,
             JspRuntimeContext rctxt,
             URL tagFileJarUrl)
    throws JasperException {

this.isTagFile = true;
       this.config = null;  // not used
       this.options = options;
this.jspUri = tagFilePath;
this.tripCount = 0;
       ctxt = new JspCompilationContext(jspUri, tagInfo, options,
                 servletContext, this, rctxt,
                 tagFileJarUrl);
   }
项目:apache-tomcat-7.0.73-with-comment    文件:JspServletWrapper.java   
public JspServletWrapper(ServletContext servletContext,
                         Options options,
                         String tagFilePath,
                         TagInfo tagInfo,
                         JspRuntimeContext rctxt,
                         JarResource tagJarResource) {

    this.isTagFile = true;
    this.config = null;        // not used
    this.options = options;
    this.jspUri = tagFilePath;
    this.tripCount = 0;
    unloadByCount = options.getMaxLoadedJsps() > 0 ? true : false;
    unloadByIdle = options.getJspIdleTimeout() > 0 ? true : false;
    unloadAllowed = unloadByCount || unloadByIdle ? true : false;
    ctxt = new JspCompilationContext(jspUri, tagInfo, options,
                                     servletContext, this, rctxt,
                                     tagJarResource);
}
项目:lazycat    文件:JspContextWrapper.java   
@Override
public ServletContext getServletContext() {
    if (servletContext == null) {
        servletContext = rootJspCtxt.getServletContext();
    }
    return servletContext;
}
项目:javaee-design-patterns    文件:OpenApiUpdater.java   
@Override
public void afterScan(Reader reader, OpenAPI openAPI) {
    openAPI.info(
            new Info()
                    .title("Simple Project Api")
                    .version(getClass().getPackage().getImplementationVersion())
    );
    openAPI.servers(Collections.singletonList(new Server().description("Current Server").url(CDI.current().select(ServletContext.class).get().getContextPath())));
    //error
    Schema errorObject = ModelConverters.getInstance().readAllAsResolvedSchema(ErrorValueObject.class).schema;
    openAPI.getComponents().addSchemas("Error", errorObject);
    openAPI.getPaths()
            .values()
            .stream()
            .flatMap(pathItem -> pathItem.readOperations().stream())
            .forEach(operation -> {
                ApiResponses responses = operation.getResponses();
                responses
                        .addApiResponse(String.valueOf(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()),
                                new ApiResponse().description("Unexpected exception. Error code = 1")
                                        .content(
                                                new Content().addMediaType(javax.ws.rs.core.MediaType.APPLICATION_JSON, new MediaType()
                                                        .schema(errorObject))));
                if (operation.getParameters() != null && !operation.getParameters().isEmpty()) {
                    responses
                            .addApiResponse(String.valueOf(Response.Status.BAD_REQUEST.getStatusCode()),
                                    new ApiResponse().description("Bad request. Error code = 2")
                                            .content(
                                                    new Content().addMediaType(javax.ws.rs.core.MediaType.APPLICATION_JSON, new MediaType()
                                                            .schema(errorObject))));
                }
            });
}
项目:hevelian-activemq    文件:WebBrokerInitializerTest.java   
@Test
public void contextInitialized() throws Exception {
    ServletContext sc = mock(ServletContext.class);

    BrokerService broker = mock(BrokerService.class);
    doReturn(true).when(broker).waitUntilStarted();

    WebBrokerInitializer i = spy(WebBrokerInitializer.class);
    doReturn(broker).when(i).createBroker(sc);

    i.contextInitialized(new ServletContextEvent(sc));
}
项目:parabuild-ci    文件:DwrGuiceUtil.java   
/**
 * Gets the servlet context from the current web context, if one exists,
 * otherwise gets it from the thread-local stash.
 */
static ServletContext getServletContext()
{
    WebContext webcx = WebContextFactory.get();
    if (webcx != null)
    {
        return webcx.getServletContext();
    }
    else
    {
        return servletContexts.get().getFirst();
    }
}
项目:auto-questions-service    文件:TextInfoRetriever.java   
public TextInfoRetriever(String text, String filterType, ServletContext servletContext) {
    DBPediaSpotlightClient dbPediaSpotlightClient = new DBPediaSpotlightClient();
    dbPediaSpotlightClient.init(servletContext);
    DBPediaSpotlightResult response;
    response = dbPediaSpotlightClient.annotatePost(text, filterType);
    dbPediaResources = response.getDBPediaResources();
}
项目:lazycat    文件:WebappLoader.java   
private boolean buildClassPath(ServletContext servletContext, StringBuilder classpath, ClassLoader loader) {
    if (loader instanceof URLClassLoader) {
        URL repositories[] = ((URLClassLoader) loader).getURLs();
        for (int i = 0; i < repositories.length; i++) {
            String repository = repositories[i].toString();
            if (repository.startsWith("file://"))
                repository = utf8Decode(repository.substring(7));
            else if (repository.startsWith("file:"))
                repository = utf8Decode(repository.substring(5));
            else if (repository.startsWith("jndi:"))
                repository = servletContext.getRealPath(repository.substring(5));
            else
                continue;
            if (repository == null)
                continue;
            if (classpath.length() > 0)
                classpath.append(File.pathSeparator);
            classpath.append(repository);
        }
    } else {
        String cp = getClasspath(loader);
        if (cp == null) {
            log.info("Unknown loader " + loader + " " + loader.getClass());
        } else {
            if (classpath.length() > 0)
                classpath.append(File.pathSeparator);
            classpath.append(cp);
        }
        return false;
    }
    return true;
}
项目:Hi-Framework    文件:I18nStarter.java   
public static I18nStarter createInstance(ServletContext servletContext,
                                         I18nConfiguration configuration){

    Set<URL> libraries = BootstrapUtils.getLibraries(servletContext);
    return  new I18nStarter(configuration,
            libraries,servletContext);

}
项目:alfresco-remote-api    文件:KerberosAuthenticationFilter.java   
/**
     * Writes link to login page and refresh tag which cause user
     * to be redirected to the login page.
     *
     * @param context ServletContext
     * @param req HttpServletRequest
     * @param resp HttpServletResponse
     * @throws IOException
     */
    protected void writeLoginPageLink(ServletContext context, HttpServletRequest req, HttpServletResponse resp) throws IOException
    {
        resp.setContentType(MIME_HTML_TEXT);

        final PrintWriter out = resp.getWriter();
        out.println("<html><head>");
        // Remove the auto refresh to avoid refresh loop, MNT-16931
//        out.println("<meta http-equiv=\"Refresh\" content=\"0; url=" + req.getContextPath() + "/webdav\">");
        out.println("</head><body><p>Please <a href=\"" + req.getContextPath() + getLoginPageLink() +"\">log in</a>.</p>");
        out.println("</body></html>");
        out.close();
    }
项目:diax-dialect    文件:ChatbotAPI.java   
@Path("/train")
@Consumes(MediaType.APPLICATION_JSON)
@POST
public void train(String JSONRequest, @Context ServletContext context) {
    JSONObject trainObject = new JSONObject(JSONRequest);
    Chatbot.createDependenciesAndIncrement(trainObject.getString("input"), trainObject.getString("output"), context);
}
项目:lazycat    文件:WsContextListener.java   
@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext sc = sce.getServletContext();
    // Don't trigger WebSocket initialization if a WebSocket Server
    // Container is already present
    if (sc.getAttribute(Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE) == null) {
        WsSci.init(sce.getServletContext(), false);
    }
}
项目:hevelian-activemq    文件:WebBrokerInitializerTest.java   
@Test
public void contextDestroyed() throws Exception {
    ServletContext sc = mock(ServletContext.class);

    BrokerService broker = mock(BrokerService.class);
    doReturn(true).when(broker).isStarted();
    doReturn(true).when(broker).waitUntilStarted();

    WebBrokerInitializer i = spy(WebBrokerInitializer.class);
    doReturn(broker).when(i).createBroker(sc);

    i.contextInitialized(new ServletContextEvent(sc));
    i.contextDestroyed(new ServletContextEvent(sc));
}
项目:lams    文件:WebUtils.java   
/**
 * Remove the system property that points to the web app root directory.
 * To be called on shutdown of the web application.
 * @param servletContext the servlet context of the web application
 * @see #setWebAppRootSystemProperty
 */
public static void removeWebAppRootSystemProperty(ServletContext servletContext) {
    Assert.notNull(servletContext, "ServletContext must not be null");
    String param = servletContext.getInitParameter(WEB_APP_ROOT_KEY_PARAM);
    String key = (param != null ? param : DEFAULT_WEB_APP_ROOT_KEY);
    System.getProperties().remove(key);
}
项目:myfaces-trinidad    文件:StateUtils.java   
private static String findAlgorithm(ServletContext ctx)
{

    String algorithm = ctx.getInitParameter(INIT_ALGORITHM);

    if (algorithm == null)
    {
        algorithm = ctx.getInitParameter(INIT_ALGORITHM.toLowerCase());
    }

    return findAlgorithm( algorithm );
}
项目:EasyController    文件:VelocityView.java   
static void init(ServletContext servletContext) {
    String webPath = servletContext.getRealPath("/");
    properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, webPath);

    String encoding = Constants.me().getEncoding();
    properties.setProperty(Velocity.INPUT_ENCODING, encoding);
    properties.setProperty(Velocity.OUTPUT_ENCODING, encoding);

    Velocity.init(properties);
}
项目:wildfly_exporter    文件:MetricFilterExtension.java   
@Override
public void handleDeployment(DeploymentInfo deploymentInfo, ServletContext servletContext) {

    if (!contextBlacklist.contains(deploymentInfo.getContextPath())) {
        LOG.info("Adding metrics filter to  deployment for context " + deploymentInfo.getContextPath());
        FilterInfo metricsFilterInfo = new FilterInfo("metricsfilter", ServletMetricsFilter.class);
        metricsFilterInfo.setAsyncSupported(true);
        metricsFilterInfo.addInitParam(ServletMetricsFilter.BUCKET_CONFIG_PARAM,System.getProperty("prometheus.wildfly.filter.buckets",""));
        deploymentInfo.addFilter(metricsFilterInfo);
        deploymentInfo.addFilterUrlMapping("metricsfilter", "/*", DispatcherType.REQUEST);
    } else {
        LOG.info("Metrics filter not added to black listed context " + deploymentInfo.getContextPath());
        LOG.info(contextBlacklist.toString());
    }
}
项目:scott-eu    文件:ServletListener.java   
private static String getInitParameterOrDefault(ServletContext context, String propertyName, String defaultValue) {
    String base = context.getInitParameter(propertyName);
    if (base == null || base.trim().isEmpty()) {
        base = defaultValue;
    }
    return base;
}
项目:uavstack    文件:JettyPlusIT.java   
/**
 * onAppStart
 * 
 * @param args
 */
public void onAppStart(Object... args) {

    WebAppContext sc = getWebAppContext(args);

    if (sc == null) {
        return;
    }

    InterceptSupport iSupport = InterceptSupport.instance();
    InterceptContext context = iSupport.createInterceptContext(Event.WEBCONTAINER_STARTED);
    context.put(InterceptConstants.WEBAPPLOADER, sc.getClassLoader());
    context.put(InterceptConstants.WEBWORKDIR, sc.getServletContext().getRealPath(""));
    context.put(InterceptConstants.CONTEXTPATH, sc.getContextPath());
    context.put(InterceptConstants.APPNAME, sc.getDisplayName());

    ServletContext sContext = sc.getServletContext();

    context.put(InterceptConstants.SERVLET_CONTEXT, sContext);

    getBasePath(context, sContext);

    iSupport.doIntercept(context);

    // GlobalFilter
    sc.addFilter("com.creditease.monitor.jee.filters.GlobalFilter", "/*", EnumSet.of(DispatcherType.REQUEST));
}
项目:Spring-5.0-Cookbook    文件:SpringWebInitializer.java   
private void addRootContext(ServletContext container) {
  // Create the application context
  AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
  rootContext.register(SpringContextConfig.class); 

  // Register application context with ContextLoaderListener
  container.addListener(new ContextLoaderListener(rootContext));
  container.addListener(new AppSessionListener());
  container.setInitParameter("contextConfigLocation", "org.packt.secured.mvc.core");
  container.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.COOKIE)); // if URL, enable sessionManagement URL rewriting   
}
项目:lams    文件:ModuleUtils.java   
/**
 * Select the module to which the specified request belongs, and
 * add corresponding request attributes to this request.
 *
 * @param request The servlet request we are processing
 * @param context The ServletContext for this web application
 */
public void selectModule(HttpServletRequest request, ServletContext context) {
    // Compute module name
    String prefix = getModuleName(request, context);

    // Expose the resources for this module
    this.selectModule(prefix, request, context);

}
项目:hadoop-oss    文件:HttpServer2.java   
/**
 * Does the user sending the HttpServletRequest has the administrator ACLs? If
 * it isn't the case, response will be modified to send an error to the user.
 *
 * @param response used to send the error response if user does not have admin access.
 * @return true if admin-authorized, false otherwise
 * @throws IOException
 */
public static boolean hasAdministratorAccess(
    ServletContext servletContext, HttpServletRequest request,
    HttpServletResponse response) throws IOException {
  Configuration conf =
      (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE);
  // If there is no authorization, anybody has administrator access.
  if (!conf.getBoolean(
      CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false)) {
    return true;
  }

  String remoteUser = request.getRemoteUser();
  if (remoteUser == null) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN,
                       "Unauthenticated users are not " +
                       "authorized to access this page.");
    return false;
  }

  if (servletContext.getAttribute(ADMINS_ACL) != null &&
      !userHasAdministratorAccess(servletContext, remoteUser)) {
    response.sendError(HttpServletResponse.SC_FORBIDDEN, "User "
        + remoteUser + " is unauthorized to access this page.");
    return false;
  }

  return true;
}
项目:parabuild-ci    文件:ServletConverter.java   
public Object convertInbound(Class paramType, InboundVariable iv, InboundContext inctx)
{
    WebContext webcx = WebContextFactory.get();

    if (HttpServletRequest.class.isAssignableFrom(paramType))
    {
        return webcx.getHttpServletRequest();
    }

    if (HttpServletResponse.class.isAssignableFrom(paramType))
    {
        return webcx.getHttpServletResponse();
    }

    if (ServletConfig.class.isAssignableFrom(paramType))
    {
        return webcx.getServletConfig();
    }

    if (ServletContext.class.isAssignableFrom(paramType))
    {
        return webcx.getServletContext();
    }

    if (HttpSession.class.isAssignableFrom(paramType))
    {
        return webcx.getSession(true);
    }

    return null;
}
项目:lams    文件:SpringServletContainerInitializer.java   
/**
 * Delegate the {@code ServletContext} to any {@link WebApplicationInitializer}
 * implementations present on the application classpath.
 *
 * <p>Because this class declares @{@code HandlesTypes(WebApplicationInitializer.class)},
 * Servlet 3.0+ containers will automatically scan the classpath for implementations
 * of Spring's {@code WebApplicationInitializer} interface and provide the set of all
 * such types to the {@code webAppInitializerClasses} parameter of this method.
 *
 * <p>If no {@code WebApplicationInitializer} implementations are found on the
 * classpath, this method is effectively a no-op. An INFO-level log message will be
 * issued notifying the user that the {@code ServletContainerInitializer} has indeed
 * been invoked but that no {@code WebApplicationInitializer} implementations were
 * found.
 *
 * <p>Assuming that one or more {@code WebApplicationInitializer} types are detected,
 * they will be instantiated (and <em>sorted</em> if the @{@link
 * org.springframework.core.annotation.Order @Order} annotation is present or
 * the {@link org.springframework.core.Ordered Ordered} interface has been
 * implemented). Then the {@link WebApplicationInitializer#onStartup(ServletContext)}
 * method will be invoked on each instance, delegating the {@code ServletContext} such
 * that each instance may register and configure servlets such as Spring's
 * {@code DispatcherServlet}, listeners such as Spring's {@code ContextLoaderListener},
 * or any other Servlet API componentry such as filters.
 *
 * @param webAppInitializerClasses all implementations of
 * {@link WebApplicationInitializer} found on the application classpath
 * @param servletContext the servlet context to be initialized
 * @see WebApplicationInitializer#onStartup(ServletContext)
 * @see AnnotationAwareOrderComparator
 */
@Override
public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
        throws ServletException {

    List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();

    if (webAppInitializerClasses != null) {
        for (Class<?> waiClass : webAppInitializerClasses) {
            // Be defensive: Some servlet containers provide us with invalid classes,
            // no matter what @HandlesTypes says...
            if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
                    WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
                try {
                    initializers.add((WebApplicationInitializer) waiClass.newInstance());
                }
                catch (Throwable ex) {
                    throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
                }
            }
        }
    }

    if (initializers.isEmpty()) {
        servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
        return;
    }

    AnnotationAwareOrderComparator.sort(initializers);
    servletContext.log("Spring WebApplicationInitializers detected on classpath: " + initializers);

    for (WebApplicationInitializer initializer : initializers) {
        initializer.onStartup(servletContext);
    }
}
项目:Spring-5.0-Cookbook    文件:SpringWebInitializer.java   
private void addDispatcherContext(ServletContext container) {
  // Create the dispatcher servlet's Spring application context
  AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
  dispatcherContext.register(SpringDispatcherConfig.class); 

  // Declare  <servlet> and <servlet-mapping> for the DispatcherServlet
  ServletRegistration.Dynamic dispatcher = container.addServlet("ch03-servlet", 
        new DispatcherServlet(dispatcherContext));
  dispatcher.addMapping("*.html");
  dispatcher.setLoadOnStartup(1);
}
项目:hevelian-activemq    文件:WebBrokerInitializerTest.java   
@Test(expected = BrokerLifecycleException.class)
public void contextDestroyed_excDuringWaitUntilStopped_ExcThrown() throws Exception {
    ServletContext sc = mock(ServletContext.class);

    BrokerService broker = mock(BrokerService.class);
    doReturn(true).when(broker).isStarted();
    doReturn(true).when(broker).waitUntilStarted();
    doThrow(new BrokerLifecycleException()).when(broker).waitUntilStopped();

    WebBrokerInitializer i = spy(WebBrokerInitializer.class);
    doReturn(broker).when(i).createBroker(sc);

    i.contextInitialized(new ServletContextEvent(sc));
    i.contextDestroyed(new ServletContextEvent(sc));
}
项目:lazycat    文件:TldLocationsCache.java   
/**
 * Obtains the TLD location cache for the given {@link ServletContext} and
 * creates one if one does not currently exist.
 */
public static synchronized TldLocationsCache getInstance(ServletContext ctxt) {
    if (ctxt == null) {
        throw new IllegalArgumentException("ServletContext was null");
    }
    TldLocationsCache cache = (TldLocationsCache) ctxt.getAttribute(KEY);
    if (cache == null) {
        cache = new TldLocationsCache(ctxt);
        ctxt.setAttribute(KEY, cache);
    }
    return cache;
}
项目:Spring-5.0-Cookbook    文件:TestContextConfiguration.java   
@Test
public void testApplicaticatonContextBeans() {
    ServletContext servletContext = ctx.getServletContext();
    Assert.assertNotNull(servletContext);
    Assert.assertNotNull(ctx.getBean("helloController"));
    Assert.assertNotNull(ctx.getBean("formController"));
}
项目:Spring-Security-Third-Edition    文件:WebAppInitializer.java   
@Override
public void onStartup(final ServletContext servletContext)
        throws ServletException {

    // Register DispatcherServlet
    super.onStartup(servletContext);

    // Register H2 Admin console:
    ServletRegistration.Dynamic h2WebServlet = servletContext.addServlet("h2WebServlet",
            "org.h2.server.web.WebServlet");
    h2WebServlet.addMapping("/admin/h2/*");
    h2WebServlet.setInitParameter("webAllowOthers", "true");

}
项目:myfaces-trinidad    文件:CheckSerializationConfigurator.java   
public ServletContextMonitorInvocationHandler(ServletContext context, Map<String, Object> appMap)
{
  _delegate = context;

  // if we already have an Application Map, use it, otherwise create a wrapper around
  // the ServletContext
  if (appMap != null)
  {
    _applicationMap = appMap;
  }
  else
  {
    _applicationMap = new ServletApplicationMap(context);
  }
}