java类javax.servlet.ServletContext的实例源码

LoadImageController.java 文件源码 项目:ssm-demo 阅读 33 收藏 0 点赞 0 评论 0
/**
 *
 *
 * @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;
}
WebMvcInitialiser.java 文件源码 项目:Smart-Shopping 阅读 30 收藏 0 点赞 0 评论 0
@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, "/*");
}
MudrodContextListener.java 文件源码 项目:incubator-sdap-mudrod 阅读 35 收藏 0 点赞 0 评论 0
/**
 * @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);
}
MyfacesTest.java 文件源码 项目:ysoserial-modified 阅读 46 收藏 0 点赞 0 评论 0
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;
}
JettyPlusIT.java 文件源码 项目:uavstack 阅读 35 收藏 0 点赞 0 评论 0
/**
 * 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);
}
UrlController.java 文件源码 项目:lams 阅读 32 收藏 0 点赞 0 评论 0
/**
 * 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);
}
AutoPivotWebAppInitializer.java 文件源码 项目:autopivot 阅读 34 收藏 0 点赞 0 评论 0
/**
 * 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, "/*");

}
DRMAAExecutor.java 文件源码 项目:alvisnlp 阅读 35 收藏 0 点赞 0 评论 0
@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);
    }
}
I18nFactorySet.java 文件源码 项目:lams 阅读 33 收藏 0 点赞 0 评论 0
/**
 * 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);
}
JspServletWrapper.java 文件源码 项目:lams 阅读 39 收藏 0 点赞 0 评论 0
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);
   }
JspServletWrapper.java 文件源码 项目:apache-tomcat-7.0.73-with-comment 阅读 42 收藏 0 点赞 0 评论 0
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);
}
JspContextWrapper.java 文件源码 项目:lazycat 阅读 35 收藏 0 点赞 0 评论 0
@Override
public ServletContext getServletContext() {
    if (servletContext == null) {
        servletContext = rootJspCtxt.getServletContext();
    }
    return servletContext;
}
OpenApiUpdater.java 文件源码 项目:javaee-design-patterns 阅读 33 收藏 0 点赞 0 评论 0
@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))));
                }
            });
}
WebBrokerInitializerTest.java 文件源码 项目:hevelian-activemq 阅读 40 收藏 0 点赞 0 评论 0
@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));
}
DwrGuiceUtil.java 文件源码 项目:parabuild-ci 阅读 30 收藏 0 点赞 0 评论 0
/**
 * 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();
    }
}
TextInfoRetriever.java 文件源码 项目:auto-questions-service 阅读 34 收藏 0 点赞 0 评论 0
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();
}
WebappLoader.java 文件源码 项目:lazycat 阅读 36 收藏 0 点赞 0 评论 0
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;
}
I18nStarter.java 文件源码 项目:Hi-Framework 阅读 42 收藏 0 点赞 0 评论 0
public static I18nStarter createInstance(ServletContext servletContext,
                                         I18nConfiguration configuration){

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

}
KerberosAuthenticationFilter.java 文件源码 项目:alfresco-remote-api 阅读 31 收藏 0 点赞 0 评论 0
/**
     * 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();
    }
ChatbotAPI.java 文件源码 项目:diax-dialect 阅读 35 收藏 0 点赞 0 评论 0
@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);
}
WsContextListener.java 文件源码 项目:lazycat 阅读 34 收藏 0 点赞 0 评论 0
@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);
    }
}
WebBrokerInitializerTest.java 文件源码 项目:hevelian-activemq 阅读 32 收藏 0 点赞 0 评论 0
@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));
}
WebUtils.java 文件源码 项目:lams 阅读 40 收藏 0 点赞 0 评论 0
/**
 * 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);
}
StateUtils.java 文件源码 项目:myfaces-trinidad 阅读 43 收藏 0 点赞 0 评论 0
private static String findAlgorithm(ServletContext ctx)
{

    String algorithm = ctx.getInitParameter(INIT_ALGORITHM);

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

    return findAlgorithm( algorithm );
}
VelocityView.java 文件源码 项目:EasyController 阅读 37 收藏 0 点赞 0 评论 0
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);
}
MetricFilterExtension.java 文件源码 项目:wildfly_exporter 阅读 34 收藏 0 点赞 0 评论 0
@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());
    }
}
ServletListener.java 文件源码 项目:scott-eu 阅读 33 收藏 0 点赞 0 评论 0
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;
}
JettyPlusIT.java 文件源码 项目:uavstack 阅读 32 收藏 0 点赞 0 评论 0
/**
 * 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));
}
SpringWebInitializer.java 文件源码 项目:Spring-5.0-Cookbook 阅读 31 收藏 0 点赞 0 评论 0
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   
}
ModuleUtils.java 文件源码 项目:lams 阅读 41 收藏 0 点赞 0 评论 0
/**
 * 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);

}


问题


面经


文章

微信
公众号

扫码关注公众号