Created
December 29, 2017 21:34
-
-
Save bsandhu/1f95ec14efaabef85a63611c09fb857d to your computer and use it in GitHub Desktop.
Tomcat Servlet with blocking op
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
public static void main(String[] args) throws Exception { | |
String webappDirLocation = "src/main/webapp/"; | |
Tomcat tomcat = new Tomcat(); | |
tomcat.setPort(8080); | |
StandardContext ctx = (StandardContext) tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath()); | |
Executor[] executors = tomcat.getEngine().getService().findExecutors(); | |
StandardThreadExecutor executor = new StandardThreadExecutor(); | |
executor.setName("DefaultThreadPool"); | |
executor.setMaxThreads(1000); | |
tomcat.getService().addExecutor(executor); | |
File additionWebInfClasses = new File("target/classes"); | |
WebResourceRoot resources = new StandardRoot(ctx); | |
resources.addPreResources(new DirResourceSet(resources, "/WEB-INF/classes", additionWebInfClasses.getAbsolutePath(), "/")); | |
ctx.setResources(resources); | |
tomcat.start(); | |
tomcat.getServer().await(); | |
} | |
} | |
@WebServlet( | |
name = "MyServlet", | |
urlPatterns = {"/"} | |
) | |
public class HelloServlet extends HttpServlet { | |
ObjectMapper mapper = new ObjectMapper(); | |
@Override | |
protected void doGet(HttpServletRequest req, HttpServletResponse resp) | |
throws ServletException, IOException { | |
resp.setStatus(200); | |
resp.setHeader("content-type", "text/html"); | |
try { | |
Thread.sleep(100); | |
ServletOutputStream out = resp.getOutputStream(); | |
String body = "<!DOCTYPE html><html><body>" + | |
"<h1>Tomcat Servlet thread " + Thread.currentThread().getName() + "</h1>" + | |
"<hr/>" + | |
"<h2>" + mapper.writeValueAsString(new User("First", "Last", "122-100-1221")) + "</h2>" + | |
"</body></html>"; | |
out.write(body.getBytes()); | |
out.flush(); | |
out.close(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
resp.setStatus(500); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment