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.
Build this directory tree (somewhere not under tomcat).
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).
Create a deployment descriptor (DD) named web.xml, put it in the etc directory
Build this directory tree under the existing tomcat directory...
From the project1 directory, compile the servlet...
(the Ch1Servlet.class file will end up in project1/classes)
Copy the Ch1Servlet.class file to WEB-INF/classes, and copy the web.xml file to WEB-INF.
From the tomcat directory, start Tomcat...
%bin/startup.sh
Launch your browser and type in:
it should display:
For now, every time you update either a servlet class or the deployment descriptor, shutdown Tomcat:
%bin/shutdown.sh
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.
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.