當前位置: 首頁>>代碼示例>>Java>>正文


Java ServletContext類代碼示例

本文整理匯總了Java中javax.servlet.ServletContext的典型用法代碼示例。如果您正苦於以下問題:Java ServletContext類的具體用法?Java ServletContext怎麽用?Java ServletContext使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ServletContext類屬於javax.servlet包,在下文中一共展示了ServletContext類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: upload

import javax.servlet.ServletContext; //導入依賴的package包/類
/**
 *
 *
 * @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;
}
 
開發者ID:ZHENFENG13,項目名稱:ssm-demo,代碼行數:30,代碼來源:LoadImageController.java

示例2: onStartup

import javax.servlet.ServletContext; //導入依賴的package包/類
@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, "/*");
}
 
開發者ID:Azanx,項目名稱:Smart-Shopping,代碼行數:27,代碼來源:WebMvcInitialiser.java

示例3: contextInitialized

import javax.servlet.ServletContext; //導入依賴的package包/類
/**
 * @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);
}
 
開發者ID:apache,項目名稱:incubator-sdap-mudrod,代碼行數:20,代碼來源:MudrodContextListener.java

示例4: createMockFacesContext

import javax.servlet.ServletContext; //導入依賴的package包/類
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;
}
 
開發者ID:pimps,項目名稱:ysoserial-modified,代碼行數:19,代碼來源:MyfacesTest.java

示例5: getBasePath

import javax.servlet.ServletContext; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:uavorg,項目名稱:uavstack,代碼行數:22,代碼來源:JettyPlusIT.java

示例6: perform

import javax.servlet.ServletContext; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:26,代碼來源:UrlController.java

示例7: onStartup

import javax.servlet.ServletContext; //導入依賴的package包/類
/**
 * 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, "/*");

}
 
開發者ID:activeviam,項目名稱:autopivot,代碼行數:32,代碼來源:AutoPivotWebAppInitializer.java

示例8: execute

import javax.servlet.ServletContext; //導入依賴的package包/類
@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);
	}
}
 
開發者ID:Bibliome,項目名稱:alvisnlp,代碼行數:22,代碼來源:DRMAAExecutor.java

示例9: convertInbound

import javax.servlet.ServletContext; //導入依賴的package包/類
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;
}
 
開發者ID:parabuild-ci,項目名稱:parabuild-ci,代碼行數:32,代碼來源:ServletConverter.java

示例10: contextInitializeServletListener

import javax.servlet.ServletContext; //導入依賴的package包/類
public static void contextInitializeServletListener(final ServletContextEvent servletContextEvent)
{
    
    // Start of user code contextInitializeServletListener
    final ServletContext context = servletContextEvent.getServletContext();
    final String queryUri = context.getInitParameter(
            "se.ericsson.cf.scott.sandbox.store.query");
    final String updateUri = context.getInitParameter(
            "se.ericsson.cf.scott.sandbox.store.update");
    try {
        store = StoreFactory.sparql(queryUri, updateUri);
        // TODO [email protected]: Remember to deactivate when switch to more persistent arch
        store.removeAll();
    } catch (IOException |ARQException e) {
        log.error("SPARQL Store failed to initialise with the URIs query={};update={}",
                queryUri, updateUri, e);
    }
    // End of user code
}
 
開發者ID:EricssonResearch,項目名稱:scott-eu,代碼行數:20,代碼來源:WarehouseControllerManager.java

示例11: initFactory

import javax.servlet.ServletContext; //導入依賴的package包/類
/**
 * 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);
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:27,代碼來源:I18nFactorySet.java

示例12: JspServletWrapper

import javax.servlet.ServletContext; //導入依賴的package包/類
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);
   }
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:18,代碼來源:JspServletWrapper.java

示例13: JspServletWrapper

import javax.servlet.ServletContext; //導入依賴的package包/類
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);
}
 
開發者ID:sunmingshuai,項目名稱:apache-tomcat-7.0.73-with-comment,代碼行數:20,代碼來源:JspServletWrapper.java

示例14: getServletContext

import javax.servlet.ServletContext; //導入依賴的package包/類
@Override
public ServletContext getServletContext() {
	if (servletContext == null) {
		servletContext = rootJspCtxt.getServletContext();
	}
	return servletContext;
}
 
開發者ID:how2j,項目名稱:lazycat,代碼行數:8,代碼來源:JspContextWrapper.java

示例15: afterScan

import javax.servlet.ServletContext; //導入依賴的package包/類
@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))));
                }
            });
}
 
開發者ID:anton-tregubov,項目名稱:javaee-design-patterns,代碼行數:34,代碼來源:OpenApiUpdater.java


注:本文中的javax.servlet.ServletContext類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。