下面列出了javax.servlet.http.HttpSessionAttributeListener#javax.servlet.Servlet 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void registerServlet(String context, Servlet servlet, Dictionary dictionary, HttpContext httpContext) throws ServletException, NamespaceException {
ContextHandlerCollection contexts = new ContextHandlerCollection();
server.setHandler(contexts);
ServletContextHandler root = new ServletContextHandler(contexts, "/",
ServletContextHandler.SESSIONS);
ServletHolder servletHolder = new ServletHolder(servlet);
root.addServlet(servletHolder, context);
if (!server.getServer().getState().equals(server.STARTED)) {
try {
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Destruction servlet
*/
protected void destroyServlet(){
Map<String, ServletRegistration> servletRegistrationMap = servletContext.getServletRegistrations();
for(ServletRegistration registration : servletRegistrationMap.values()){
Servlet servlet = registration.getServlet();
if(servlet == null) {
continue;
}
if(registration.isInitServlet()){
try {
servlet.destroy();
}catch (Exception e){
logger.error("destroyServlet error={},servlet={}",e.toString(),servlet,e);
}
}
}
}
/**
* onServletStop
*
* @param args
*/
@Override
public void onServletStop(Object... args) {
StandardWrapper sw = (StandardWrapper) args[0];
Servlet servlet = (Servlet) args[1];
InterceptSupport iSupport = InterceptSupport.instance();
InterceptContext context = iSupport.createInterceptContext(Event.BEFORE_SERVLET_DESTROY);
context.put(InterceptConstants.SERVLET_INSTANCE, servlet);
/**
* NOTE: spring boot rewrite the tomcat webappclassloader, makes the addURL for nothing, then we can't do
* anything on this we may use its webappclassloader's parent as the classloader
*/
context.put(InterceptConstants.WEBAPPLOADER, Thread.currentThread().getContextClassLoader().getParent());
context.put(InterceptConstants.CONTEXTPATH, sw.getServletContext().getContextPath());
iSupport.doIntercept(context);
}
public PageContext getPageContext(Servlet servlet,
ServletRequest request,
ServletResponse response,
String errorPageURL,
boolean needsSession,
int bufferSize,
boolean autoflush) {
if (Constants.IS_SECURITY_ENABLED) {
PrivilegedGetPageContext dp =
new PrivilegedGetPageContext(
this, servlet, request, response, errorPageURL,
needsSession, bufferSize, autoflush);
return AccessController.doPrivileged(dp);
} else {
return internalGetPageContext(servlet, request, response,
errorPageURL, needsSession,
bufferSize, autoflush);
}
}
@Override
protected AbstractConfiguration getConfiguration()
{
final MockServletConfig config = new MockServletConfig();
config.setInitParameter("key1", "value1");
config.setInitParameter("key2", "value2");
config.setInitParameter("list", "value1, value2");
config.setInitParameter("listesc", "value1\\,value2");
final Servlet servlet = new HttpServlet() {
/**
* Serial version UID.
*/
private static final long serialVersionUID = 1L;
@Override
public ServletConfig getServletConfig()
{
return config;
}
};
final ServletConfiguration servletConfiguration = new ServletConfiguration(servlet);
servletConfiguration.setListDelimiterHandler(new DefaultListDelimiterHandler(','));
return servletConfiguration;
}
/**
* @throws Exception if an error occurs
*/
@Test
public void emptyPut() throws Exception {
final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
servlets.put("/test", EmptyPutServlet.class);
startWebServer("./", null, servlets);
final String[] expectedAlerts = {"1"};
final WebClient client = getWebClient();
client.setAjaxController(new NicelyResynchronizingAjaxController());
final List<String> collectedAlerts = new ArrayList<>();
client.setAlertHandler(new CollectingAlertHandler(collectedAlerts));
assertEquals(0, client.getCookieManager().getCookies().size());
client.getPage(URL_FIRST + "test");
assertEquals(expectedAlerts, collectedAlerts);
assertEquals(1, client.getCookieManager().getCookies().size());
}
@Test
public void doFilterWithServletAndFilters() throws Exception {
Servlet servlet = mock(Servlet.class);
MockFilter filter2 = new MockFilter(servlet);
MockFilter filter1 = new MockFilter(null);
MockFilterChain chain = new MockFilterChain(servlet, filter1, filter2);
chain.doFilter(this.request, this.response);
assertTrue(filter1.invoked);
assertTrue(filter2.invoked);
verify(servlet).service(this.request, this.response);
try {
chain.doFilter(this.request, this.response);
fail("Expected Exception");
}
catch (IllegalStateException ex) {
assertEquals("This FilterChain has already been called!", ex.getMessage());
}
}
public static void main(String[] args) {
// initialize environment variables
System.setProperty("java.awt.headless", "true"); // no awt used here so we can switch off that stuff
// start server
List<Class<? extends Servlet>> services = new ArrayList<>();
services.addAll(Arrays.asList(MCP_SERVICES));
Service.initEnvironment(MCP_SERVICE, services, DATA_PATH, true);
// start listener
BrokerListener brokerListener = new IndexListener(INDEXER_SERVICE);
new Thread(brokerListener).start();
// start server
Data.logger.info("started MCP");
Data.logger.info("Grid Name: " + Data.config.get("grid.name"));
Data.logger.info(new GitTool().toString());
Data.logger.info("you can now search using the query api, i.e.:");
Data.logger.info("curl http://127.0.0.1:8100/yacy/grid/mcp/index/yacysearch.json?query=test");
Service.runService(null);
// this line is reached if the server was shut down
brokerListener.terminate();
}
public ServletInfo(final String name, final Class<? extends Servlet> servletClass) {
if (name == null) {
throw UndertowServletMessages.MESSAGES.paramCannotBeNull("name");
}
if (servletClass == null) {
throw UndertowServletMessages.MESSAGES.paramCannotBeNull("servletClass", "Servlet", name);
}
if (!Servlet.class.isAssignableFrom(servletClass)) {
throw UndertowServletMessages.MESSAGES.servletMustImplementServlet(name, servletClass);
}
try {
final Constructor<? extends Servlet> ctor = servletClass.getDeclaredConstructor();
ctor.setAccessible(true);
this.instanceFactory = new ConstructorInstanceFactory(ctor);
this.name = name;
this.servletClass = servletClass;
} catch (NoSuchMethodException e) {
throw UndertowServletMessages.MESSAGES.componentMustHaveDefaultConstructor("Servlet", servletClass);
}
}
/**
* Creates a new Guice aware {@link ServletHolder servlet holder} instance.
*
* @param clazz
* the class of the servlet to instantiate.
* @return the Guice aware servlet holder.
*/
public ServletHolder build(final Class<? extends Servlet> clazz) {
ServletHolder servletHolder = new ServletHolder(clazz) {
@Override
protected Servlet newInstance() throws ServletException, IllegalAccessException, InstantiationException {
try {
Servlet servlet = super.newInstance();
Injector injector = injectedInjector;
injector.injectMembers(servlet);
return servlet;
} catch (Exception e) {
LOGGER.error("Error while creating servlet for class: " + clazz + ";", e);
throw new RuntimeException(e);
}
}
};
return servletHolder;
}
/**
* @throws Exception if the test fails
*/
@Test
@Alerts(DEFAULT = {"<xml><content>blah</content></xml>", "text/xml;charset=utf-8", "gzip", "45"},
IE = {"<xml><content>blah</content></xml>", "text/xml;charset=utf-8", "null", "null"})
@NotYetImplemented(IE)
public void encodedXml() throws Exception {
final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
servlets.put("/test", EncodedXmlServlet.class);
final String html =
"<html>\n"
+ " <head>\n"
+ " <title>XMLHttpRequest Test</title>\n"
+ " <script>\n"
+ " var request;\n"
+ " function testBasicAuth() {\n"
+ " var request = new XMLHttpRequest();\n"
+ " request.open('GET', '/test', false, null, null);\n"
+ " request.send();\n"
+ " alert(request.responseText);\n"
+ " alert(request.getResponseHeader('content-type'));\n"
+ " alert(request.getResponseHeader('content-encoding'));\n"
+ " alert(request.getResponseHeader('content-length'));\n"
+ " }\n"
+ " </script>\n"
+ " </head>\n"
+ " <body onload='testBasicAuth()'>\n"
+ " </body>\n"
+ "</html>";
loadPageWithAlerts2(html, servlets);
}
/**
* @throws Exception if the test fails
*/
@Test
public void chunkedBigContent() throws Exception {
final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
servlets.put("/bigChunked", ChunkedBigContentServlet.class);
startWebServer("./", null, servlets);
final WebClient client = getWebClient();
final Page page = client.getPage(URL_FIRST + "bigChunked");
assertTrue(page instanceof UnexpectedPage);
}
/**
* Notify all lifecycle event listeners that a particular event has
* occurred for this Container. The default implementation performs
* this notification synchronously using the calling thread.
*
* @param type Event type
* @param servlet The relevant Servlet for this event
* @param request The servlet request we are processing
* @param response The servlet response we are processing
*/
public void fireInstanceEvent(String type, Servlet servlet,
ServletRequest request,
ServletResponse response) {
if (listeners.length == 0)
return;
InstanceEvent event = new InstanceEvent(wrapper, servlet, type,
request, response);
InstanceListener interested[] = listeners;
for (int i = 0; i < interested.length; i++)
interested[i].instanceEvent(event);
}
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
throws ServletException {
// Register and map servlet
Servlet s = new Bug50015Servlet();
ServletRegistration.Dynamic sr = ctx.addServlet("bug50015", s);
sr.addMapping("/bug50015");
// Limit access to users in the Tomcat role
HttpConstraintElement hce = new HttpConstraintElement(
TransportGuarantee.NONE, "tomcat");
ServletSecurityElement sse = new ServletSecurityElement(hce);
sr.setServletSecurity(sse);
}
protected Servlet createServlet() throws ServletException {
// Init paramameters - optional
//HashMap<String, String> params = new HashMap<String, String>();
//params.put("MyParam", "myValue");
Servlet servlet = (Servlet)module.createServlet(servletClass,servletName, null /*params*/);
return servlet;
}
/**
* @throws Exception if the test fails
*/
@Test
public void binaryResponseHeaders() throws Exception {
final Map<String, Class<? extends Servlet>> servlets = new HashMap<>();
servlets.put("/test", BinaryResponseHeadersServlet.class);
startWebServer("./", null, servlets);
final HtmlPage page = getWebClient().getPage(URL_FIRST + "test");
assertEquals(BinaryResponseHeadersServlet.RESPONSE,
page.getWebResponse().getContentAsString(UTF_8));
assertEquals("gzip", page.getWebResponse().getResponseHeaderValue("Content-Encoding"));
assertEquals("73", page.getWebResponse().getResponseHeaderValue(HttpHeader.CONTENT_LENGTH));
}
/**
* @throws Exception if the test fails.
*/
@Test
@Alerts(DEFAULT = {"4", "200", "options_headers", "x-ping,x-pong"},
IE = {"4", "200", "options_headers", "null"})
public void preflight_many_header_values() throws Exception {
expandExpectedAlertsVariables(new URL("http://localhost:" + PORT));
final String html = "<html><head>\n"
+ "<script>\n"
+ "var xhr = new XMLHttpRequest();\n"
+ "function test() {\n"
+ " try {\n"
+ " var url = 'http://' + window.location.hostname + ':" + PORT2 + "/preflight2';\n"
+ " xhr.open('GET', url, false);\n"
+ " xhr.setRequestHeader('X-PING', 'ping');\n"
+ " xhr.setRequestHeader('X-PONG', 'pong');\n"
+ " xhr.send();\n"
+ " } catch(e) { alert('exception') }\n"
+ " alert(xhr.readyState);\n"
+ " alert(xhr.status);\n"
+ " alert(xhr.responseXML.firstChild.childNodes[3].tagName);\n"
+ " alert(xhr.responseXML.firstChild.childNodes[3].firstChild.nodeValue);\n"
+ "}\n"
+ "</script>\n"
+ "</head>\n"
+ "<body onload='test()'></body></html>";
PreflightServerServlet.ACCESS_CONTROL_ALLOW_ORIGIN_ = "http://localhost:" + PORT;
PreflightServerServlet.ACCESS_CONTROL_ALLOW_METHODS_ = "POST, GET, OPTIONS";
PreflightServerServlet.ACCESS_CONTROL_ALLOW_HEADERS_ = "X-PING, X-PONG";
final Map<String, Class<? extends Servlet>> servlets2 = new HashMap<>();
servlets2.put("/preflight2", PreflightServerServlet.class);
startWebServer2(".", null, servlets2);
loadPageWithAlerts2(html, new URL(URL_FIRST, "/preflight1"));
}
public static AuthenticationBootstrap createTypicalAuthBootstrap() {
final UserDAO userDAO = mock(UserDAO.class);
final Server s = new Server(0);
final Servlet se = new ServletContainer();
final JerseyEnvironment env = new JerseyEnvironment(new JerseyContainerHolder(se), new DropwizardResourceConfig());
return new AuthenticationBootstrap(env, userDAO);
}
/**
* Perform work as a particular </code>Subject</code>. Here the work
* will be granted to a <code>null</code> subject.
*
* @param methodName the method to apply the security restriction
* @param targetObject the <code>Servlet</code> on which the method will
* be called.
* @param targetType <code>Class</code> array used to instantiate a
* <code>Method</code> object.
* @param targetArguments <code>Object</code> array contains the runtime
* parameters instance.
*/
public static void doAsPrivilege(final String methodName,
final Servlet targetObject,
final Class<?>[] targetType,
final Object[] targetArguments)
throws java.lang.Exception{
doAsPrivilege(methodName,
targetObject,
targetType,
targetArguments,
null);
}
public void addServlet(
ServletContextHandler context,
String url,
Class<? extends Servlet> servletClass) {
try {
context.addServlet(new ServletHolder(servletClass), url);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Construct a new InstanceEvent with the specified parameters. This
* constructor is used for processing servlet lifecycle events.
*
* @param wrapper Wrapper managing this servlet instance
* @param servlet Servlet instance for which this event occurred
* @param type Event type (required)
* @param exception Exception that occurred
*/
public InstanceEvent(Wrapper wrapper, Servlet servlet, String type,
Throwable exception) {
super(wrapper);
this.filter = null;
this.servlet = servlet;
this.type = type;
this.exception = exception;
}
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
throws ServletException {
Servlet s = new CustomDefaultServlet();
ServletRegistration.Dynamic r = ctx.addServlet(servletName, s);
r.addMapping("/");
}
@Override
public InstanceHandle<Servlet> createInstance() throws InstantiationException {
return new InstanceHandle<Servlet>() {
@Override
public Servlet getInstance() {
return new DispatcherServlet(wac);
}
@Override
public void release() {
}
};
}
@Override
public void onStartup(Set<Class<?>> c, ServletContext ctx)
throws ServletException {
Servlet s = new TesterServlet();
ServletRegistration.Dynamic r = ctx.addServlet("TesterServlet1", s);
r.addMapping("/TesterServlet1");
}
@Override
public ServletRegistration.Dynamic addServlet(String servletName,
Servlet servlet) {
if (SecurityUtil.isPackageProtectionEnabled()) {
return (ServletRegistration.Dynamic) doPrivileged("addServlet",
new Class[]{String.class, Servlet.class},
new Object[]{servletName, servlet});
} else {
return context.addServlet(servletName, servlet);
}
}
@NotNull
public Collection<Holder> addServlets(@NotNull Map<String, Servlet> servletMap) {
List<Holder> servletInfos = new ArrayList<>();
for (Map.Entry<String, Servlet> entry : servletMap.entrySet()) {
log.info("Registered servlet for path: {}", entry.getKey());
final Holder servletInfo = new Holder(entry.getKey(), entry.getValue());
servletInfos.add(servletInfo);
}
servlets.addAll(servletInfos);
updateServlets();
return servletInfos;
}
PrivilegedGetPageContext(JspFactoryImpl factory, Servlet servlet,
ServletRequest request, ServletResponse response, String errorPageURL,
boolean needsSession, int bufferSize, boolean autoflush) {
this.factory = factory;
this.servlet = servlet;
this.request = request;
this.response = response;
this.errorPageURL = errorPageURL;
this.needsSession = needsSession;
this.bufferSize = bufferSize;
this.autoflush = autoflush;
}
@Override
@Nullable
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
((Servlet) handler).service(request, response);
return null;
}
@Override
public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {
servlets.put(servletName, servlet);
MockServletRegistration registration = new MockServletRegistration();
registrations.put(servletName, registration);
return registration;
}
@Test
public void testServletContextAttributes_added() {
this.webApplicationContextRunner
.run(context -> {
ServletRegistrationBean<FacesServlet> facesServletRegistrationBean = (ServletRegistrationBean<FacesServlet>) context.getBean("facesServletRegistrationBean");
ServletContext servletContext = mock(ServletContext.class);
when(servletContext.addServlet(anyString(), any(Servlet.class))).thenReturn(mock(ServletRegistration.Dynamic.class));
facesServletRegistrationBean.onStartup(servletContext);
verify(servletContext, times(2)).setAttribute(any(), any());
});
}