下面列出了怎么用javax.servlet.http.HttpServlet的API类实例代码及写法,或者点击链接到github查看源代码。
private void configure(final ServletEnvironment environment, final HttpServlet servlet,
final Class<? extends HttpServlet> type, final String name, final WebServlet annotation) {
final ServletRegistration.Dynamic mapping = environment.addServlet(name, servlet);
final Set<String> clash = mapping
.addMapping(annotation.urlPatterns().length > 0 ? annotation.urlPatterns() : annotation.value());
if (clash != null && !clash.isEmpty()) {
final String msg = String.format(
"Servlet registration %s clash with already installed servlets on paths: %s",
type.getSimpleName(), Joiner.on(',').join(clash));
if (option(DenyServletRegistrationWithClash)) {
throw new IllegalStateException(msg);
} else {
logger.warn(msg);
}
}
if (annotation.initParams().length > 0) {
for (WebInitParam param : annotation.initParams()) {
mapping.setInitParameter(param.name(), param.value());
}
}
mapping.setAsyncSupported(annotation.asyncSupported());
}
@Test
public void testUseContentTypeWithoutCharsetExpiresConfiguration()
throws Exception {
HttpServlet servlet = new HttpServlet() {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/xml; charset=iso-8859-1");
response.getWriter().print("Hello world");
}
};
validate(servlet, Integer.valueOf(5 * 60));
}
@Test
public void testUseDefaultConfiguration2() throws Exception {
HttpServlet servlet = new HttpServlet() {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("image/jpeg");
response.addHeader("Cache-Control", "private");
response.getWriter().print("Hello world");
}
};
validate(servlet, Integer.valueOf(1 * 60));
}
/**
* Starts server with Login Service and create a realm file.
*
* @param port Port number.
* @param cfg Configuration.
* @param igniteInstanceName Ignite instance name.
* @param servlet Servlet.
* @return Server.
* @throws Exception In case of error.
*/
private Server startServerWithLoginService(
int port, @Nullable String cfg, @Nullable String igniteInstanceName, HttpServlet servlet
) throws Exception {
Server srv = new Server(port);
WebAppContext ctx = getWebContext(cfg, igniteInstanceName, keepBinary(), servlet);
HashLoginService hashLoginService = new HashLoginService();
hashLoginService.setName("Test Realm");
createRealm();
hashLoginService.setConfig("/tmp/realm.properties");
ctx.getSecurityHandler().setLoginService(hashLoginService);
srv.setHandler(ctx);
srv.start();
return srv;
}
private String sendRedirect(final String location) throws ServletException, IOException {
Filter filter = new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
FilterChain chain) throws IOException {
res.sendRedirect(location);
}
};
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = new MockFilterChain(mock(HttpServlet.class), this.filter, filter);
filterChain.doFilter(request, response);
return response.getRedirectedUrl();
}
/**
* Add an internal servlet in the server, specifying whether or not to
* protect with Kerberos authentication.
* Note: This method is to be used for adding servlets that facilitate
* internal communication and not for user facing functionality. For
* servlets added using this method, filters (except internal Kerberized
* filters) are not enabled.
*
* @param name The name of the servlet (can be passed as null)
* @param pathSpec The path spec for the servlet
* @param clazz The servlet class
*/
public void addInternalServlet(String name, String pathSpec,
Class<? extends HttpServlet> clazz, boolean requireAuth) {
ServletHolder holder = new ServletHolder(clazz);
if (name != null) {
holder.setName(name);
}
webAppContext.addServlet(holder, pathSpec);
if(requireAuth && UserGroupInformation.isSecurityEnabled()) {
LOG.info("Adding Kerberos filter to " + name);
ServletHandler handler = webAppContext.getServletHandler();
FilterMapping fmap = new FilterMapping();
fmap.setPathSpec(pathSpec);
fmap.setFilterName("krb5Filter");
fmap.setDispatches(Handler.ALL);
handler.addFilterMapping(fmap);
}
}
@Test
void testExceptionCapturingShouldContainUserInformationRecordedOnTheTransaction() throws IOException, ServletException {
filterChain = new MockFilterChain(new HttpServlet() {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
tracer.currentTransaction().setUser("id", "email", "username");
tracer.getActive().captureException(new RuntimeException("Test exception capturing"));
}
});
filterChain.doFilter(new MockHttpServletRequest("GET", "/foo"), new MockHttpServletResponse());
assertThat(reporter.getTransactions()).hasSize(1);
assertThat(reporter.getErrors()).hasSize(1);
assertThat(reporter.getFirstError().getContext().getUser().getId()).isEqualTo("id");
assertThat(reporter.getFirstError().getContext().getUser().getEmail()).isEqualTo("email");
assertThat(reporter.getFirstError().getContext().getUser().getUsername()).isEqualTo("username");
}
@BeforeEach
void setUp() {
webConfiguration = tracer.getConfig(WebConfiguration.class);
coreConfiguration = tracer.getConfig(CoreConfiguration.class);
doReturn(CoreConfiguration.EventType.ALL).when(coreConfiguration).getCaptureBody();
filterChain = new MockFilterChain(new HttpServlet() {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
final ServletInputStream is = req.getInputStream();
int read;
do {
read = streamConsumer.read(is);
} while (read != -1);
streamCloser.close(is);
}
});
streamConsumer = is -> is.readLine(BUFFER, 0, BUFFER.length);
streamCloser = InputStream::close;
}
@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;
}
private void configureAndStartServer(HttpServlet servlet, int maxFormContentSize) throws Exception {
serverUnderTest = new Server();
localConnector = new LocalConnector(serverUnderTest);
localConnector.setIdleTimeout(SERVER_IDLE_TIMEOUT);
serverUnderTest.addConnector(localConnector);
contextUnderTest = new ServletContextHandler(serverUnderTest, "/");
if (maxFormContentSize > 0) {
contextUnderTest.setMaxFormContentSize(maxFormContentSize);
}
contextUnderTest.addServlet(new ServletHolder(servlet), "/*");
// This only adds the ContentLengthFilter if a valid maxFormContentSize is not provided
if (maxFormContentSize < 0) {
FilterHolder holder = contextUnderTest.addFilter(ContentLengthFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
holder.setInitParameter(ContentLengthFilter.MAX_LENGTH_INIT_PARAM, String.valueOf(MAX_CONTENT_LENGTH));
}
serverUnderTest.start();
}
void runTomcat(HttpServlet servlet, Callable<Void> doWithTomcat) throws Exception {
Tomcat server = new Tomcat();
try {
StandardHost host = new StandardHost();
host.setName("localhost");
server.setHost(host);
server.setPort(0);
server.start();
this.port = server.getConnector().getLocalPort();
Context context = server.addContext("", null);
server.addServlet("", "servletname", servlet);
context.addServletMappingDecoded("/", "servletname");
doWithTomcat.call();
} finally {
server.stop();
server.destroy();
}
}
@Test
public void testRequestsWithMissingContentLengthHeader() throws Exception {
configureAndStartServer(new HttpServlet() {
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletInputStream input = req.getInputStream();
while (!input.isFinished()) {
input.read();
}
resp.setStatus(HttpServletResponse.SC_OK);
}
}, -1);
// This shows that the ContentLengthFilter allows a request that does not have a content-length header.
String response = localConnector.getResponse("POST / HTTP/1.0\r\n\r\n");
Assert.assertFalse(StringUtils.containsIgnoreCase(response, "411 Length Required"));
}
@Test
public void testSkipBecauseExpiresIsDefined() throws Exception {
HttpServlet servlet = new HttpServlet() {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/xml; charset=utf-8");
response.addDateHeader("Expires", System.currentTimeMillis());
response.getWriter().print("Hello world");
}
};
validate(servlet, null);
}
@Test
public void testSkipBecauseCacheControlMaxAgeIsDefined() throws Exception {
HttpServlet servlet = new HttpServlet() {
private static final long serialVersionUID = 1L;
@Override
protected void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
response.setContentType("text/xml; charset=utf-8");
response.addHeader("Cache-Control", "private, max-age=232");
response.getWriter().print("Hello world");
}
};
validate(servlet, Integer.valueOf(232));
}
/**
* Handles a request for a JSP page. It checks to see if a servlet is mapped
* for the JSP URL. If one is found, request handling is passed to it. If no
* servlet is found, a 404 error is returned.
*
* @param pathInfo the extra path info.
* @param request the request object.
* @param response the response object.
* @throws ServletException if a servlet exception occurs while handling the
* request.
* @throws IOException if an IOException occurs while handling the request.
*/
private void handleJSP(String pathInfo, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Strip the starting "/" from the path to find the JSP URL.
String jspURL = pathInfo.substring(1);
HttpServlet servlet = servlets.get(jspURL);
if (servlet != null) {
servlet.service(request, response);
return;
}
else {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
}
ServletWrapperDelegatorServlet(
Class<? extends HttpServlet> servletClass,
ImmutableList<Class<? extends Filter>> filterClasses,
Queue<FutureTask<Void>> requestQueue) {
this.servletClass = servletClass;
this.filterClasses = filterClasses;
this.requestQueue = checkNotNull(requestQueue, "requestQueue");
}
public synchronized void undeployServlet(HttpServlet servlet)
{
try
{
// there is no removeServlet method so we need to do it manually
ServletHandler handler = servletHandler.getServletHandler();
// first collect servlets we want to keep
List<ServletHolder> servlets = new ArrayList<ServletHolder>();
String nameToRemove = null;
for( ServletHolder holder : handler.getServlets() )
{
if (holder.getServlet() != servlet)
servlets.add(holder);
else
nameToRemove = holder.getName();
}
if (nameToRemove == null)
return;
// also update servlet path mappings
List<ServletMapping> mappings = new ArrayList<ServletMapping>();
for (ServletMapping mapping : handler.getServletMappings())
{
if (!nameToRemove.contains(mapping.getServletName()))
mappings.add(mapping);
}
// set the new configuration
handler.setServletMappings( mappings.toArray(new ServletMapping[0]) );
handler.setServlets( servlets.toArray(new ServletHolder[0]) );
}
catch (ServletException e)
{
log.error("Error while undeploying servlet", e);
}
}
/**
* Add an internal servlet in the server, with initialization parameters.
* Note: This method is to be used for adding servlets that facilitate
* internal communication and not for user facing functionality. For
* servlets added using this method, filters (except internal Kerberos
* filters) are not enabled.
*
* @param name The name of the servlet (can be passed as null)
* @param pathSpec The path spec for the servlet
* @param clazz The servlet class
* @param params init parameters
*/
public void addInternalServlet(String name, String pathSpec,
Class<? extends HttpServlet> clazz, Map<String, String> params) {
// Jetty doesn't like the same path spec mapping to different servlets, so
// if there's already a mapping for this pathSpec, remove it and assume that
// the newest one is the one we want
final ServletHolder sh = new ServletHolder(clazz);
sh.setName(name);
sh.setInitParameters(params);
final ServletMapping[] servletMappings =
webAppContext.getServletHandler().getServletMappings();
for (ServletMapping servletMapping : servletMappings) {
if (servletMapping.containsPathSpec(pathSpec)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Found existing " + servletMapping.getServletName() +
" servlet at path " + pathSpec + "; will replace mapping" +
" with " + sh.getName() + " servlet");
}
ServletMapping[] newServletMappings =
ArrayUtil.removeFromArray(servletMappings, servletMapping);
webAppContext.getServletHandler()
.setServletMappings(newServletMappings);
break;
}
}
webAppContext.addServlet(sh, pathSpec);
}
ServletDefinition(String pattern, Class<? extends HttpServlet> servletClass, UriPatternMatcher patternMatcher,
Map<String, String> initParams, HttpServlet servletInstance) {
this.pattern = pattern;
this.servletClass = servletClass;
this.patternMatcher = patternMatcher;
this.initParams = Collections.unmodifiableMap(Maps.newHashMap(initParams));
this.servletInstance = servletInstance;
}
@Before
public void setUp() {
when(environment.servlets()).thenReturn(servletEnvironment);
when(environment.lifecycle()).thenReturn(lifecycleEnvironment);
when(bootstrap.getMetricRegistry()).thenReturn(mock(MetricRegistry.class));
when(servletEnvironment.addServlet(anyString(), any(HttpServlet.class))).thenReturn(servlet);
when(jaxwsEnvironment.buildServlet()).thenReturn(mock(HttpServlet.class));
when(jaxwsEnvironment.getDefaultPath()).thenReturn("/soap");
}
@Before
@SuppressWarnings("serial")
public void setup() throws Exception {
this.request = new MockHttpServletRequest();
this.request.setScheme("http");
this.request.setServerName("localhost");
this.request.setServerPort(80);
this.filterChain = new MockFilterChain(new HttpServlet() {});
}
@Before
@SuppressWarnings("serial")
public void setup() throws Exception {
this.request = new MockHttpServletRequest();
this.request.setScheme("http");
this.request.setServerName("localhost");
this.request.setServerPort(80);
this.filterChain = new MockFilterChain(new HttpServlet() {});
}
@Before
public void setUp() {
req = EasyMock.createMock(HttpServletRequest.class);
res = EasyMock.createMock(HttpServletResponse.class);
registry = EasyMock.createMock(DestinationRegistry.class);
serviceListGenerator = EasyMock.createMock(HttpServlet.class);
}
private void servletPath(final String requestPath, String mapping,
final String expectedServletPath) throws IOException, ServletException {
ObjectGraph objectGraph = createMock(ObjectGraph.class);
HttpServletRequest request = createMock(HttpServletRequest.class);
HttpServletResponse response = createMock(HttpServletResponse.class);
final boolean[] run = new boolean[1];
//get an instance of this servlet
expect(objectGraph.get(HttpServlet.class))
.andReturn(new HttpServlet() {
@Override
protected void service(HttpServletRequest servletRequest,
HttpServletResponse httpServletResponse) throws ServletException, IOException {
final String path = servletRequest.getServletPath();
assertEquals(path, expectedServletPath,
String.format("expected [%s] but was [%s]", expectedServletPath, path));
run[0] = true;
}
});
expect(request.getServletPath())
.andReturn(requestPath);
replay(objectGraph, request);
ServletDefinition servletDefinition = new ServletDefinition(mapping, HttpServlet.class,
UriPatternType.get(UriPatternType.SERVLET, mapping), new HashMap<String, String>(), null);
servletDefinition.init(null, objectGraph,
Sets.newSetFromMap(Maps.<HttpServlet, Boolean>newIdentityHashMap()));
servletDefinition.doService(request, response);
assertTrue(run[0], "Servlet did not run!");
verify(objectGraph, request);
}
@Test
void testExceptionCapturingShouldContainContextInformation() throws IOException, ServletException {
filterChain = new MockFilterChain(new HttpServlet() {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
tracer.getActive().captureException(new RuntimeException("Test exception capturing"));
}
});
filterChain.doFilter(new MockHttpServletRequest("GET", "/foo"), new MockHttpServletResponse());
assertThat(reporter.getTransactions()).hasSize(1);
assertThat(reporter.getErrors()).hasSize(1);
assertThat(reporter.getFirstError().getContext().getRequest().getUrl().getPathname()).isEqualTo("/foo");
assertThat(reporter.getFirstError().getTraceContext().isChildOf(reporter.getFirstTransaction().getTraceContext())).isTrue();
}
/**
* Add a servlet to the servlet registry. This servlet will be attached to the
* specified URL pattern when the server is started up.
*
* @param urlPattern the URL pattern for paths. Eg, '/foo', '/foo/*'.
* @param servlet the servlet class to bind to the specified paths.
* @param initParams the map with init params, can be null or empty.
* @return the {@link ServletHolder} that holds the servlet.
*/
public ServletHolder addServlet(String urlPattern, Class<? extends HttpServlet> servlet,
@Nullable Map<String, String> initParams) {
ServletHolder servletHolder = new ServletHolder(servlet);
if (initParams != null) {
servletHolder.setInitParameters(initParams);
}
servletRegistry.add(Pair.of(urlPattern, servletHolder));
return servletHolder;
}
protected String getServletParameter(HttpServlet servlet, String parameterName) {
String parameterValue = servlet.getInitParameter(parameterName);
if (parameterValue == null) {
parameterValue = servlet.getServletContext().getInitParameter(parameterName);
}
return parameterValue;
}
/** 加载带有 @MappingTo 注解的类。 */
public default WebApiBinder loadMappingTo(Class<?> mappingType, final TypeSupplier typeSupplier) {
Objects.requireNonNull(mappingType, "class is null.");
int modifier = mappingType.getModifiers();
if (AsmTools.checkOr(modifier, Modifier.INTERFACE, Modifier.ABSTRACT) || mappingType.isArray() || mappingType.isEnum()) {
throw new IllegalStateException(mappingType.getName() + " must be normal Bean");
}
MappingTo[] annotationsByType = mappingType.getAnnotationsByType(MappingTo.class);
if (annotationsByType == null || annotationsByType.length == 0) {
throw new IllegalStateException(mappingType.getName() + " must be configure @MappingTo");
}
//
if (HttpServlet.class.isAssignableFrom(mappingType)) {
final Class<? extends HttpServlet> httpServletType = (Class<HttpServlet>) mappingType;
Arrays.stream(annotationsByType).peek(mappingTo -> {
}).forEach(mappingTo -> {
if (!isSingleton(mappingType)) {
throw new IllegalStateException("HttpServlet " + mappingType + " must be Singleton.");
}
if (typeSupplier != null) {
jeeServlet(mappingTo.value()).with(() -> typeSupplier.get(httpServletType));
} else {
jeeServlet(mappingTo.value()).with(httpServletType);
}
});
} else {
final Class<Object> mappingObjType = (Class<Object>) mappingType;
Arrays.stream(annotationsByType).peek(mappingTo -> {
}).forEach(mappingTo -> {
if (typeSupplier != null) {
mappingTo(mappingTo.value()).with(mappingObjType, () -> typeSupplier.get(mappingObjType));
} else {
mappingTo(mappingTo.value()).with(mappingType);
}
});
}
return this;
}
public void destroy() {
Set<HttpServlet> destroyedSoFar
= Sets.newSetFromMap(Maps.<HttpServlet, Boolean>newIdentityHashMap());
for (ServletDefinition servletDefinition : servletDefinitions) {
servletDefinition.destroy(destroyedSoFar);
}
}
@Test
void mbeansAvailableAfterBinder() throws Exception {
TomcatMetrics.monitor(registry, null);
CountDownLatch latch = new CountDownLatch(1);
registry.config().onMeterAdded(m -> {
if (m.getId().getName().equals("tomcat.global.received"))
latch.countDown();
});
HttpServlet servlet = new HttpServlet() {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
IOUtils.toString(req.getInputStream());
sleep();
resp.getOutputStream().write("yes".getBytes());
}
};
runTomcat(servlet, () -> {
assertThat(latch.await(10, TimeUnit.SECONDS)).isTrue();
checkMbeansInitialState();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost post = new HttpPost("http://localhost:" + this.port + "/");
post.setEntity(new StringEntity("you there?"));
CloseableHttpResponse response1 = httpClient.execute(post);
CloseableHttpResponse response2 = httpClient.execute(
new HttpGet("http://localhost:" + this.port + "/nowhere"));
long expectedSentBytes = response1.getEntity().getContentLength()
+ response2.getEntity().getContentLength();
checkMbeansAfterRequests(expectedSentBytes);
}
return null;
});
}