Article
Java Servlets - Part 2
Summary and Further Reading
In the second part of this introductory article on Java Servlets, I introduced some of the more involved concepts of writing Servlets. First, I showed how to handle POST requests with a doPost method, and demonstrated how that method could simply call doGet to have all your request-handling code in one place. Next I showed how the HttpServletRequest object could be used to retrieve request parameters such as the values entered into HTML form fields, or passed as part of the URL query string. The HttpUtils class came in handy when we wanted to create a form that submitted back to the same Servlet that generated it. Finally, I showed how initialization parameters could be used to configure a Servlet when it is deployed. By setting parameters in the web.xml file and checking their values in the init method of the Servlet, we could control how our Servlet behaved without having to change its code and recompile it.
We then took all this knowledge and developed a Web-based quiz Servlet. If you're looking for some practice, consider how you might expand this Servlet to allow more or less than 4 answers to the question. If you're really ambitious, consider how you might support a whole quiz with multiple questions, perhaps one per page with a mechanism for tracking the user's score as he procedes through the quiz!
With the full power of the Java language behind them, Servlets can be very powerful things. What's more, we've only scratched the surface of what the Servlet API has to offer. From session tracking and cookies to password protection and cache control, Servlets are a complete and powerful technology. Their only apparent weakness is the fact that the static HTML portions of a page must be embedded deep in amongst Java code, or stashed as properties in a web.xml file. Either way, it makes life difficult for design staff who are not neccessarily hip to the intricacies of Java Servlets but who want to modify an image or some static text on a page. Technologies such as JavaServer Pages (JSP) seek to remedy this situation by wrapping the Servlet API in a convenient framework that lets you write Java-powered Web pages with Java code appearing in an otherwise normal-looking HTML file. This makes JSP very similar to ASP, PHP, Cold Fusion, and other popular Web Scripting technologies.
For a complete and thorough look at the world of Servlets and everything they're capable of, I recommend Jason Hunter and William Crawford's excellent book, Java Servlet Programming 2nd Edition. Not only does it cover everything there is to know about Servlets with an incredible level of detail, but it does so while supporting every point with practical examples and lucid, and sometimes humorous discussion. The book also delves into many of the technologies surrounding the Servlets framework, such as JavaServer Pages (JSP).