javax.servlet.http.HttpServlet类的使用及代码示例

x33g5p2x  于2022-01-19 转载在 其他  
字(10.5k)|赞(0)|评价(0)|浏览(241)

本文整理了Java中javax.servlet.http.HttpServlet类的一些代码示例,展示了HttpServlet类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpServlet类的具体详情如下:
包路径:javax.servlet.http.HttpServlet
类名称:HttpServlet

HttpServlet介绍

[英]Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:

  • doGet, if the servlet supports HTTP GET requests
  • doPost, for HTTP POST requests
  • doPut, for HTTP PUT requests
  • doDelete, for HTTP DELETE requests
  • init and destroy, to manage resources that are held for the life of the servlet
  • getServletInfo, which the servlet uses to provide information about itself

There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doMethod methods listed above).

Likewise, there's almost no reason to override the doOptions and doTrace methods.

Servlets typically run on multithreaded servers, so be aware that a servlet must handle concurrent requests and be careful to synchronize access to shared resources. Shared resources include in-memory data such as instance or class variables and external objects such as files, database connections, and network connections. See the Java Tutorial on Multithreaded Programming for more information on handling multiple threads in a Java program.
[中]提供要子类化的抽象类,以创建适用于网站的HTTP servlet。HttpServlet的子类必须重写至少一个方法,通常是以下方法之一:
*doGet,如果servlet支持HTTP GET请求
*doPost,用于HTTP POST请求
*doPut,用于HTTP PUT请求
*doDelete,用于HTTP删除请求
*initdestroy,以管理在servlet生命周期内保留的资源
*getServletInfo,servlet使用它来提供关于自身的信息
几乎没有理由重写service方法。service通过将标准HTTP请求分派给每个HTTP请求类型的处理程序方法(上面列出的do方法)来处理这些请求。
同样,几乎没有理由重写doOptionsdoTrace方法。
servlet通常在多线程服务器上运行,因此请注意servlet必须处理并发请求,并小心同步对共享资源的访问。共享资源包括内存中的数据(如实例或类变量)和外部对象(如文件、数据库连接和网络连接)。有关在Java程序中处理多个线程的更多信息,请参见{$0$}。

代码示例

代码示例来源:origin: javamelody/javamelody

/** {@inheritDoc} */
@Override
public void init(ServletConfig config) throws ServletException {
  super.init(config);
  Parameters.initialize(config.getServletContext());
  if (!Parameter.LOG.getValueAsBoolean()) {
    // si log désactivé dans serveur de collecte,
    // alors pas de log, comme dans webapp
    LOGGER.setLevel(Level.WARN);
  }
  // dans le serveur de collecte, on est sûr que log4j est disponible
  LOGGER.info("initialization of the collector servlet of the monitoring");
  httpAuth = new HttpAuth();
  try {
    collectorServer = new CollectorServer();
  } catch (final IOException e) {
    throw new ServletException(e.getMessage(), e);
  }
}

代码示例来源:origin: igniterealtime/Openfire

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  // add CORS headers for all HTTP responses (errors, etc.)
  if (boshManager.isCORSEnabled())
  {
    if (boshManager.isAllOriginsAllowed()) {
      // Set the Access-Control-Allow-Origin header to * to allow all Origin to do the CORS
      response.setHeader("Access-Control-Allow-Origin", HttpBindManager.HTTP_BIND_CORS_ALLOW_ORIGIN_DEFAULT);
    } else {
      // Get the Origin header from the request and check if it is in the allowed Origin Map.
      // If it is allowed write it back to the Access-Control-Allow-Origin header of the respond.
      final String origin = request.getHeader("Origin");
      if (boshManager.isThisOriginAllowed(origin)) {
        response.setHeader("Access-Control-Allow-Origin", origin);
      }
    }
    response.setHeader("Access-Control-Allow-Methods", HttpBindManager.HTTP_BIND_CORS_ALLOW_METHODS_DEFAULT);
    response.setHeader("Access-Control-Allow-Headers", HttpBindManager.HTTP_BIND_CORS_ALLOW_HEADERS_DEFAULT);
    response.setHeader("Access-Control-Max-Age", HttpBindManager.HTTP_BIND_CORS_MAX_AGE_DEFAULT);
  }
  super.service(request, response);
}

代码示例来源:origin: googleapis/google-cloud-java

@Override
 public void destroy() {
  executor.shutdownNow();
  super.destroy();
 }
}

代码示例来源:origin: javax.servlet/servlet-api

throws ServletException, IOException
  long lastModified = getLastModified(req);
  if (lastModified == -1) {
  doGet(req, resp);
  } else {
  long ifModifiedSince = req.getDateHeader(HEADER_IFMODSINCE);
  if (ifModifiedSince < (lastModified / 1000 * 1000)) {
    maybeSetLastModified(resp, lastModified);
    doGet(req, resp);
  } else {
    resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
  long lastModified = getLastModified(req);
  maybeSetLastModified(resp, lastModified);
  doHead(req, resp);
  doPost(req, resp);
  doPut(req, resp);	
  doDelete(req, resp);
  doOptions(req,resp);
  doTrace(req,resp);

代码示例来源:origin: net.lizhaoweb.spring.mvc/spring-mvc-core

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  logger.info("service('%s', '%s')", request, response);
  request.setCharacterEncoding(Constant.Charset.UTF8);
  response.setCharacterEncoding(Constant.Charset.UTF8);
  response.setContentType("text/html;charset=" + Constant.Charset.UTF8);
  super.service(request, response);
  session = request.getSession();
}

代码示例来源:origin: org.apache.cxf/cxf-rt-transports-http

public boolean invoke(HttpServletRequest request, HttpServletResponse res, boolean returnErrors)
  throws ServletException {
  try {
    String pathInfo = request.getPathInfo() == null ? "" : request.getPathInfo();
    AbstractHTTPDestination d = destinationRegistry.getDestinationForPath(pathInfo, true);
      if (!isHideServiceList && (request.getRequestURI().endsWith(serviceListRelativePath)
        || request.getRequestURI().endsWith(serviceListRelativePath + "/")
        || StringUtils.isEmpty(pathInfo)
        serviceListGenerator.service(request, res);
      } else {
        d = destinationRegistry.checkRestfulRequest(pathInfo);
    throw new ServletException(e);

代码示例来源:origin: konsoletyper/teavm

@Override
public void init(ServletConfig config) throws ServletException {
  super.init(config);
  wsFactory = WebSocketServletFactory.Loader.load(config.getServletContext(), wsPolicy);
  wsFactory.setCreator((req, resp) -> {
    ProxyWsClient proxyClient = (ProxyWsClient) req.getHttpServletRequest().getAttribute("teavm.ws.client");
    if (proxyClient == null) {
      return new CodeWsEndpoint(this);
    wsFactory.start();
  } catch (Exception e) {
    throw new ServletException(e);

代码示例来源:origin: apache/oozie

@SuppressWarnings("unchecked")
  public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    Enumeration<String> names = (Enumeration<String>) httpRequest.getHeaderNames();
    while (names.hasMoreElements()) {
      String name = names.nextElement();
      String value = httpRequest.getHeader(name);
      OOZIE_HEADERS.put(name, value);
    }
    servlet.service(request, response);
  }
}

代码示例来源:origin: openmrs/openmrs-core

@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  log.debug("In service method for module servlet: " + request.getPathInfo());
  String servletName = request.getPathInfo();
  int end = servletName.indexOf("/", 1);
    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    return;
  servlet.service(request, response);

代码示例来源:origin: org.apache.cxf/cxf-rt-transports-http

/**
 * {@inheritDoc}
 *
 * javax.http.servlet.HttpServlet does not let to override the code which deals with
 * unrecognized HTTP verbs such as PATCH (being standardized), WebDav ones, etc.
 * Thus we let CXF servlets process unrecognized HTTP verbs directly, otherwise we delegate
 * to HttpService
 */
@Override
public void service(ServletRequest req, ServletResponse res)
  throws ServletException, IOException {
  HttpServletRequest      request;
  HttpServletResponse     response;
  try {
    request = (HttpServletRequest) req;
    response = (HttpServletResponse) res;
  } catch (ClassCastException e) {
    throw new ServletException("Unrecognized HTTP request or response object");
  }
  String method = request.getMethod();
  if (KNOWN_HTTP_VERBS.contains(method)) {
    super.service(request, response);
  } else {
    handleRequest(request, response);
  }
}

代码示例来源:origin: gocd/gocd

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String url = request.getRequestURI().replaceAll("^/go/rails/", "/go/");
  servletHelper.getRequest(request).setRequestURI(url);
  rackServlet.service(request, response);
}

代码示例来源:origin: javax.servlet/servlet-api

response = (HttpServletResponse) res;
} catch (ClassCastException e) {
  throw new ServletException("non-HTTP request or response");
service(request, response);

代码示例来源:origin: jamesagnew/hapi-fhir

@Override
protected void service(HttpServletRequest theReq, HttpServletResponse theResp) throws ServletException, IOException {
  theReq.setAttribute(REQUEST_START_TIME, new Date());
    method = RequestTypeEnum.valueOf(theReq.getMethod());
  } catch (IllegalArgumentException e) {
    super.service(theReq, theResp);
    return;

代码示例来源:origin: com.liferay.portal/com.liferay.portal.kernel

throws IOException, ServletException {
String uri = request.getPathInfo();
  response.sendError(
    HttpServletResponse.SC_NOT_FOUND,
    "Path information is not specified");
  response.sendError(
    HttpServletResponse.SC_NOT_FOUND,
    "Path " + uri + " is invalid");
  response.sendError(
    HttpServletResponse.SC_NOT_FOUND,
    "No servlet registred for context " + paths[1]);
  delegate.service(request, response);

代码示例来源:origin: com.semanticcms/semanticcms-news-rss

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  Object old = req.getAttribute(RESPONSE_IN_REQUEST_ATTRIBUTE);
  try {
    req.setAttribute(RESPONSE_IN_REQUEST_ATTRIBUTE, resp);
    super.service(req, resp);
  } finally {
    req.setAttribute(RESPONSE_IN_REQUEST_ATTRIBUTE, old);
  }
}

代码示例来源:origin: voldemort/voldemort

@Override
public void init() throws ServletException {
  super.init();
  // this.getServletContext().getAttribute("velocity");
}

代码示例来源:origin: org.apache.activemq/activemq-all

@Override
protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.addHeader("Accepts-Encoding", "gzip");
  super.doOptions(request, response);
}

代码示例来源:origin: org.ow2.petals/petals-bc-rest

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  if ("PATCH".equalsIgnoreCase(request.getMethod())) {
    doPatch(request, response);
  } else {
    super.service(request, response);
  }
}

代码示例来源:origin: com.atlassian.studio/studio-theme-fisheye-plugin

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
{
  if (!userIsSysadmin(request))
  {
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
      "Only system administrators can administrate Crucible");
    return;
  }
  super.service(request, response);
}

代码示例来源:origin: sakaiproject/sakai

/**
 * Override service, adding the setup for legacy.
 */
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException
{
  // parse the parameters of the request, considering Unicode issues, into a ParameterParser
  ParameterParser parser = new ParameterParser(req);
  // make this available from the req as an attribute
  req.setAttribute(ATTR_PARAMS, parser);
  // Setup.setup(req, resp);
  super.service(req, resp);
}

相关文章