javax.servlet.ServletContext.setAttribute()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(12.6k)|赞(0)|评价(0)|浏览(173)

本文整理了Java中javax.servlet.ServletContext.setAttribute()方法的一些代码示例,展示了ServletContext.setAttribute()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ServletContext.setAttribute()方法的具体详情如下:
包路径:javax.servlet.ServletContext
类名称:ServletContext
方法名:setAttribute

ServletContext.setAttribute介绍

[英]Binds an object to a given attribute name in this servlet context. If the name specified is already used for an attribute, this method will replace the attribute with the new to the new attribute.

If listeners are configured on the ServletContext the container notifies them accordingly.

If a null value is passed, the effect is the same as calling removeAttribute().

Attribute names should follow the same convention as package names. The Java Servlet API specification reserves names matching java.*, javax.*, and sun.*.
[中]在此servlet上下文中将对象绑定到给定的属性名。如果指定的名称已用于属性,则此方法将用新属性的新名称替换该属性。
如果在ServletContext上配置了侦听器,容器会相应地通知它们。
如果传递了空值,其效果与调用removeAttribute()相同。
属性名称应遵循与包名称相同的约定。Java Servlet API规范保留了匹配java.*javax.*sun.*的名称。

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
  Object scopedObject = this.servletContext.getAttribute(name);
  if (scopedObject == null) {
    scopedObject = objectFactory.getObject();
    this.servletContext.setAttribute(name, scopedObject);
  }
  return scopedObject;
}

代码示例来源:origin: Red5/red5-server

/**
 * Sets the scheduler factory in the servlet context.
 * 
 * @param servletContext
 *            sevlet context
 */
public void setServletAttribute(ServletContext servletContext) {
  log.debug("Storing the scheduler factory in the servlet context");
  servletContext.setAttribute(QUARTZ_FACTORY_KEY, factory);
}

代码示例来源:origin: gocd/gocd

public void contextInitialized(ServletContextEvent evt) {
  ServletContext ctx = evt.getServletContext();
  ctx.setAttribute(DELEGATE_SERVLET, createServlet(ctx.getInitParameter(DELEGATE_SERVLET)));
}

代码示例来源:origin: apache/shiro

if (servletContext.getAttribute(ENVIRONMENT_ATTRIBUTE_KEY) != null) {
  String msg = "There is already a Shiro environment associated with the current ServletContext.  " +
      "Check if you have multiple EnvironmentLoader* definitions in your web.xml!";
  servletContext.setAttribute(ENVIRONMENT_ATTRIBUTE_KEY,environment);
  log.debug("Published WebEnvironment as ServletContext attribute with name [{}]",
      ENVIRONMENT_ATTRIBUTE_KEY);
} catch (RuntimeException ex) {
  log.error("Shiro environment initialization failed", ex);
  servletContext.setAttribute(ENVIRONMENT_ATTRIBUTE_KEY, ex);
  throw ex;
} catch (Error err) {
  log.error("Shiro environment initialization failed", err);
  servletContext.setAttribute(ENVIRONMENT_ATTRIBUTE_KEY, err);
  throw err;

代码示例来源:origin: openmrs/openmrs-core

log.debug("Starting the OpenMRS webapp");
  ServletContext servletContext = event.getServletContext();
    servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);
    WebDaemon.startOpenmrs(event.getServletContext());
  } else {
    setupNeeded = true;

代码示例来源:origin: Red5/red5-server

public void contextInitialized(ServletContextEvent event) {
  ServletContext servletContext = event.getServletContext();
  String contextName = servletContext.getContextPath().replaceAll("/", "");
  if ("".equals(contextName)) {
  ConfigurableWebApplicationContext appctx = (ConfigurableWebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
  if (appctx != null) {
    System.out.printf("ConfigurableWebApplicationContext is not null in ContextLoggingListener for: %s, this indicates a misconfiguration or load order problem%n", contextName);
    servletContext.setAttribute(Red5LoggerFactory.LOGGER_CONTEXT_ATTRIBUTE, loggerContext);

代码示例来源:origin: IanDarwin/javasrc

application.setAttribute(WINNER, null);
    String winner = null;
    synchronized(application) {
      winner = (String)application.getAttribute(WINNER);
      "ERROR: Command " + command + " invalid.");
  RequestDispatcher rd = application.getRequestDispatcher(
    "/hosts/index.jsp");
  rd.forward(request, response);
} else {
  out.println("<html><head><title>Nice try, but... </title><head>");

代码示例来源:origin: stackoverflow.com

public Object getAttribute(String s)
  return delegateContext.getAttribute(s);
public void setAttribute(String s, Object o)
  delegateContext.setAttribute(s, o);
public RequestDispatcher getRequestDispatcher(String s)
  return delegateContext.getRequestDispatcher(s);

代码示例来源:origin: caelum/vraptor

@Test
public void shouldNotIncludeTheApplicationContextOnTheRootApplicationContextParamIfAlreadySet() throws Exception {
  ConfigurableWebApplicationContext ctx = mock(ConfigurableWebApplicationContext.class);
  when(servletContext.getAttributeNames()).thenReturn(enumeration(Collections.<String> emptyList()));
  when(servletContext.getAttribute(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)).thenReturn(ctx);
    
  defaultExpectations();
  
  SpringProvider provider = new SpringProvider();
  provider.start(servletContext);
  
  verify(servletContext, never()).setAttribute(eq(ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE), isA(WebApplicationContext.class));
}

代码示例来源:origin: exoplatform/platform

if(StringUtils.isEmpty(code)){
 try {
  getServletContext().getRequestDispatcher(SR_JSP_RESOURCE).forward(request, response);
 }catch (Exception se){
  if(LOG.isErrorEnabled()){
     SoftwareRegistrationService.SOFTWARE_REGISTRATION_NODE, SettingValue.create("Software registered:" + "true"));
 softwareRegistrationService.checkSoftwareRegistration();
 getServletContext().setAttribute("status", "success");
}else if(softwareRegistration.isNotReachable()){
 request.getSession().setAttribute("notReachable", "true");
 getServletContext().getRequestDispatcher(SR_JSP_RESOURCE).forward(request, response);
 return;
}else {
 getServletContext().setAttribute("status", "failed");
 request.getSession().setAttribute("notReachable", "true");
 response.sendRedirect("/");
 return;
getServletContext().getRequestDispatcher(SR_JSP_RESOURCE_SUCCESS).forward(request, response);
return;

代码示例来源:origin: Red5/red5-server

public void registerSubContext(String webAppKey) {
  // get the sub contexts - servlet context
  ServletContext ctx = servletContext.getContext(webAppKey);
  if (ctx == null) {
    ctx = servletContext;
  }
  ContextLoader loader = new ContextLoader();
  ConfigurableWebApplicationContext appCtx = (ConfigurableWebApplicationContext) loader.initWebApplicationContext(ctx);
  appCtx.setParent(applicationContext);
  appCtx.refresh();
  ctx.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appCtx);
  ConfigurableBeanFactory appFactory = appCtx.getBeanFactory();
  logger.debug("About to grab Webcontext bean for {}", webAppKey);
  Context webContext = (Context) appCtx.getBean("web.context");
  webContext.setCoreBeanFactory(parentFactory);
  webContext.setClientRegistry(clientRegistry);
  webContext.setServiceInvoker(globalInvoker);
  webContext.setScopeResolver(globalResolver);
  webContext.setMappingStrategy(globalStrategy);
  WebScope scope = (WebScope) appFactory.getBean("web.scope");
  scope.setServer(server);
  scope.setParent(global);
  scope.register();
  scope.start();
  // register the context so we dont try to reinitialize it
  registeredContexts.add(ctx);
}

代码示例来源:origin: pippo-java/pippo

@Override
public void init(ServletConfig servletConfig) {
  if (System.getProperty("pippo.hideLogo") == null) {
    log.info(PippoUtils.getPippoLogo());
  }
  // check for runtime mode in filter init parameter
  String mode = servletConfig.getInitParameter(MODE_PARAM);
  if (!StringUtils.isNullOrEmpty(mode)) {
    System.setProperty(PippoConstants.SYSTEM_PROPERTY_PIPPO_MODE, mode);
  }
  if (application == null) {
    createApplication(servletConfig);
    log.debug("Created application '{}'", application);
  }
  ServletContext servletContext = servletConfig.getServletContext();
  // save the servlet context object in application
  application.setServletContext(servletContext);
  // set the application as an attribute of the servlet container
  if (servletContext.getAttribute(WebServer.PIPPO_APPLICATION) == null) {
    servletContext.setAttribute(WebServer.PIPPO_APPLICATION, application);
  }
  String contextPath = StringUtils.addStart(servletContext.getContextPath(), "/");
  application.getRouter().setContextPath(contextPath);
  log.debug("Serving application on context path '{}'", contextPath);
  log.debug("Initializing Route Dispatcher");
  routeDispatcher = new RouteDispatcher(application);
  routeDispatcher.init();
  String runtimeMode = application.getRuntimeMode().toString().toUpperCase();
  log.info("Pippo started ({})", runtimeMode);
}

代码示例来源:origin: gwizard/gwizard

@Override
public void contextInitialized(ServletContextEvent event) {
  log.debug("Handling servlet context event. Configuring Swagger...");
  BeanConfig beanConfig = createBeanConfig(swaggerConfig);
  event.getServletContext().setAttribute("reader", beanConfig);
  event.getServletContext().setAttribute("swagger", beanConfig.getSwagger());
  event.getServletContext().setAttribute("scanner", ScannerFactory.getScanner());
}

代码示例来源:origin: spring-projects/spring-framework

@Override
public void setServletContext(ServletContext servletContext) {
  if (this.attributes != null) {
    for (Map.Entry<String, Object> entry : this.attributes.entrySet()) {
      String attributeName = entry.getKey();
      if (logger.isDebugEnabled()) {
        if (servletContext.getAttribute(attributeName) != null) {
          logger.debug("Replacing existing ServletContext attribute with name '" + attributeName + "'");
        }
      }
      servletContext.setAttribute(attributeName, entry.getValue());
      if (logger.isTraceEnabled()) {
        logger.trace("Exported ServletContext attribute with name '" + attributeName + "'");
      }
    }
  }
}

代码示例来源:origin: org.freemarker/freemarker

public void contextInitialized(ServletContextEvent arg0) {
  arg0.getServletContext().setAttribute(ATTR_NAME, this);
  
  synchronized (servletContextListeners) {
    int s = servletContextListeners.size();
    for (int i = 0; i < s; ++i) {
      ((ServletContextListener) servletContextListeners.get(i)).contextInitialized(arg0);
    }
  }
}

代码示例来源:origin: wildfly/wildfly

@Override
public void contextInitialized(final ServletContextEvent sce) {
  // if the servlet version is 3.1 or higher, setup a ELResolver which allows usage of static fields java.lang.*
  final ServletContext servletContext = sce.getServletContext();
  final JspApplicationContext jspApplicationContext = JspFactory.getDefaultFactory().getJspApplicationContext(servletContext);
  if (servletContext.getEffectiveMajorVersion() > 3
      || (servletContext.getEffectiveMajorVersion() == 3 && servletContext.getEffectiveMinorVersion() >= 1)) {
    jspApplicationContext.addELResolver(new ImportedClassELResolver());
  }
  // setup a wrapped JspApplicationContext if there are any EL expression factory wrappers for this servlet context
  final List<ExpressionFactoryWrapper> expressionFactoryWrappers = (List<ExpressionFactoryWrapper>) sce.getServletContext().getAttribute(CONTEXT_KEY);
  if (expressionFactoryWrappers != null && !expressionFactoryWrappers.isEmpty()) {
    final JspApplicationContextWrapper jspApplicationContextWrapper = new JspApplicationContextWrapper(JspApplicationContextImpl.getInstance(servletContext), expressionFactoryWrappers, sce.getServletContext());
    sce.getServletContext().setAttribute(JspApplicationContextImpl.class.getName(), jspApplicationContextWrapper);
  }
}

代码示例来源:origin: webx/citrus

private void prepareComponent(WebxComponentImpl component, String componentLocation) {
  String componentName = component.getName();
  WebxComponentContext wcc = new WebxComponentContext(component);
  wcc.setServletContext(getServletContext());
  wcc.setNamespace(componentName);
  wcc.addApplicationListener(new SourceFilteringListener(wcc, component));
  if (componentLocation != null) {
    wcc.setConfigLocation(componentLocation);
  }
  component.setApplicationContext(wcc);
  // 将context保存在servletContext中
  String attrName = getComponentContextAttributeName(componentName);
  getServletContext().setAttribute(attrName, wcc);
  log.debug("Published WebApplicationContext of component {} as ServletContext attribute with name [{}]",
       componentName, attrName);
}

代码示例来源:origin: pippo-java/pippo

log.debug("Created application '{}'", application);
if (servletContext.getAttribute(WebServer.PIPPO_APPLICATION) == null) {
  servletContext.setAttribute(WebServer.PIPPO_APPLICATION, application);
    log.debug("Context path is '{}'", contextPath);
  log.debug("Serving application on path '{}'", applicationPath);
  log.debug("Initializing Route Dispatcher");

代码示例来源:origin: org.apache.syncope.client/syncope-client-enduser

@Override
public void contextInitialized(final ServletContextEvent sce) {
  ClassPathScanImplementationLookup lookup = new ClassPathScanImplementationLookup();
  lookup.load();
  sce.getServletContext().setAttribute(CLASSPATH_LOOKUP, lookup);
  LOG.debug("Initialization completed");
}

代码示例来源:origin: stackoverflow.com

ServletContext context = request.getSession().getServletContext();

if (username != "" & username != null ) {
  context.setAttribute("savedUserName", username);
}
writer.println("Context Parameter : " + (String)context.getAttribute("savedUserName"));

相关文章

微信公众号

最新文章

更多

ServletContext类方法