From the course: Learning Apache Tomcat

Servlet overview - Tomcat Tutorial

From the course: Learning Apache Tomcat

Start my 1-month free trial

Servlet overview

- [Instructor] We have already talked a bit about servlets, but let's get down to more details. To understand what a servlet is, let's start with what a servlet isn't. A servlet isn't a server, despite having a similar sounding name. Servlets don't know how to handle HTTP requests, how to route different URLs. They don't know how to secure connections with SSL. They don't even really know how to serve flat files. All of that work is handled for the servlet by the web container. In the case of Tomcat, that program is called Catalina. You'd like to look at a web page for some important business research, so you open a browser and you go to the website. In a static web server, there's a file sitting on the hard drive that matches that directory in the URL. The server interprets your results, finds the file, and sends that file as a response with the important business content you'd been looking for. With a servlet, there's no static file at that URL. The web container receives that request from the browser, and pulls out various pieces of information. First, it figures out which servlet is the right one for that request. Then, it creates a request object with all of the information that was in the HTTP request, and it creates what is essentially an empty response object that it's going to send back to the browser. The web container hands off both of these objects to the servlet. Since the servlet isn't a server, it doesn't need to understand anything about how to interact correctly with the browser. So, in a simple case it might receive a request, look up a response in a database, and put that in the response object and return that to the web container. From there, the web container sends the response back to the browser in the same way that it would with a flat JPEG file that it had just retrieved from the hard drive. This isn't a Java programming course, but I want to highlight one thing about writing web apps with servlets. They generally aren't very good at creating HTML. They can of course, a servlet can do pretty much anything that you can do with Java. But they aren't very user friendly about it. That job is better handled by JSP, Java Server Pages. Servlet code looks like regular Java code. JSP looks a lot like HTML, with some bits of Java thrown in. It's mostly focused on presentation but is able to support some programmatic logic. The nice thing is that Tomcat actually compiles JSP into servlets, so you don't pay a performance penalty for this convenience.

Contents