17 Eylül 2023 Pazar

Embedded Tomcat

Giriş
Şu satırı dahil ederiz.
<dependency>
  <groupId>org.apache.tomcat.embed</groupId>
  <artifactId>tomcat-embed-core</artifactId>
  <version>${tomcat.version}</version>
</dependency>
Tomcat Sınıfı
addServlet metodu
Şöyle yaparız.
Tomcat tomcat = new Tomcat();
tomcat.setPort(8082);
tomcat.addContext("/", "/web");
Context ctx = tomcat.addContext("/", new File(".").getAbsolutePath());

Tomcat.addServlet(ctx, "Embedded", new HttpServlet() {
  @Override
  protected void service(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {

    Writer w = resp.getWriter();
    w.write("Embedded Tomcat servlet.\n");
    w.flush();
    w.close();
  }
});

ctx.addServletMappingDecoded("/*", "Embedded");

tomcat.start();
tomcat.getServer().await();
setBaseDir metodu
Örnek
Şöyle yaparız
import org.apache.catalina.Wrapper;
import org.apache.catalina.startup.Tomcat;

public class TomcatEmbedded {

  public static void main(String... args) throws Exception {
    File baseFolder = new File(System.getProperty("user.dir"));
    File appsFolder = new File(baseFolder, "apps");

    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir(baseFolder.getAbsolutePath());
    tomcat.setPort(8080);
    tomcat.getHost().setAppBase(appsFolder.getAbsolutePath());

    // Call the connector to create the default connector.
    tomcat.getConnector();

    tomcat.addWebapp("", ".");
    Wrapper wrapper = tomcat.addServlet(EMPTY, "hello", new HelloServlet());
    wrapper.setLoadOnStartup(1);
    wrapper.addMapping("/*");

    tomcat.start();
    tomcat.getServer().await();
  }

  private static class HelloServlet extends HttpServlet {
    ...
}

getService metodu
Elimizde şöyle bir kod olsun
public class CustomLoggerValve extends ValveBase {
  private static final Logger logger = LoggerFactory.getLogger(CustomLoggerValve.class);

  @Override
  public void invoke(Request request, Response response)
  throws IOException, ServletException {
    try {
      MDC.put("requestId", UUID.randomUUID().toString());
      logger.info("Received request");
      getNext().invoke(request, response);
    } finally {
      MDC.remove("requestId");
    }
  }
}
Şöyle yaparız
Tomcat tomcat = // ... your tomcat setup
tomcat.getService().getContainer().getPipeline().addValve(new CustomLoggerValve());

Hiç yorum yok:

Yorum Gönder

Bean Validation @GroupSequence Anotasyonu

Örnek Elimizde şöyle bir kod olsun public class SampleRequest {   @NotNull   LocalDate startDate;   @NotNull   LocalDate endDate;   @AssertT...