本文整理匯總了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;
}
示例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, "/*");
}
示例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);
}
示例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;
}
示例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);
}
示例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);
}
示例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, "/*");
}
示例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);
}
}
示例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;
}
示例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
}
示例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);
}
示例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);
}
示例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);
}
示例14: getServletContext
import javax.servlet.ServletContext; //導入依賴的package包/類
@Override
public ServletContext getServletContext() {
if (servletContext == null) {
servletContext = rootJspCtxt.getServletContext();
}
return servletContext;
}
示例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))));
}
});
}