Servlets Demystified (write, deploy, run)

Just so those new to servlets can stop holding their breath, here’s a quick guide to writing, deploying, and running a servlet. This might create more questions than it answers—don’t panic, you don’t have to do this right now. It’s just a quick demonstration for those who can’t wait. The next chapter includes a more thorough tutorial.

  1. Build this directory tree (somewhere not under tomcat).

    image with no caption
  2. Write a servlet named Ch1Servlet.java and put it in the src directory (to keep this example simple, we aren’t putting the servlet in a package, but after this, all other servlet examples in the book will be in packages).

    image with no caption
  3. Create a deployment descriptor (DD) named web.xml, put it in the etc directory

    image with no caption
  4. Build this directory tree under the existing tomcat directory...

  5. From the project1 directory, compile the servlet...

    image with no caption

    (the Ch1Servlet.class file will end up in project1/classes)

  6. Copy the Ch1Servlet.class file to WEB-INF/classes, and copy the web.xml file to WEB-INF.

    image with no caption
  7. From the tomcat directory, start Tomcat...

    %bin/startup.sh
  8. Launch your browser and type in:

    image with no caption

    it should display:

    image with no caption
  9. For now, every time you update either a servlet class or the deployment descriptor, shutdown Tomcat:

    %bin/shutdown.sh
image with no caption
image with no caption

Actually, trying to format HTML inside a servlet’s out.println() pretty much sucks.

This is one of the worst parts (no, the worst part) of servlets. Stuffing properly formatted HTML tags into the println(), just so that you can insert variables and method calls, is just brutal. Don’t even think about doing anything the least bit sophisticated.

image with no caption
image with no caption

A JSP page looks just like an HTML page, except you can put Java and Java-related things inside the page.

So it really is like inserting a variable into your HTML.

Get Head First Servlets and JSP, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.