To be a Servlet, a Java class just has to implement the Servlet interface. A full implementation would be Tomcat or Websphere. We are just interested in overwriting that … and that’s possible with an abstract class called Generic Servlet.
Servlet knows nothing about the HTTP protocol, just the Servlet API. Another class extends info on the HTTP protocol, it is called HttpServlet.
Servlet (Interface) javax.servlet.Servlet
|
ServletConfig javax.servlet.ServletConfig
|
Java.io.Serializable |
GenericServlet javax.servlet.GenericServlet |
||
HttpServlet javax.servlet.http |
Serializable – allows objects to be written to disk. Important for memory utilization with Tomcat
Servlet (Interface)
javax.servlet.Servlet
- Init()
- Service()
- Destroy()
Defines the servlet’s lifecycle.
When someone requests myServlet, Tomcat will look in memory. If it’s not there, Tomcat will load the Servlet and leave it there. When you shut down Tomcat, it will call destroy on all servlets in memory. That means it has a chance to do things as it’s loaded and as it’s destroyed.
We don’t have to worry about Init() because it will inherit an empty method from the HttpServlet.
Service() is the main worker method within the Servlet. It is called for each service on the thread. Each user is being treated concurrently, like they are the only user.
Only time that is not true – when you violate the multi-thread environment. That’s why it’s important to be thread-safe. Implement it or mark it as abstract
Service method receives the information from the HttpServlet. Looks at the method name to determine what happens. Will need to respond appropriately to how the information is being passed from the HTML form.
QUERY STRING – doGet {}
FORM – doPost {}
When service method is called by Tomcat, either doGet() or doPost() is called by the Servlet. Servlets typically extend HttpServlet and override doGet or doPost, depending on whether the data is being sent by GET or by POST. Both doGet and doPost take two arguments: an HttpServletRequest and an HttpServletResponse. The HttpServletRequest lets you get at all of the incoming data; the class has methods by which you can find out about information such as form (query) data, HTTP request headers, and the client’s hostname. The HttpServletResponse lets you specify outgoing information such as HTTP status codes (200, 404, etc.) and response headers (Content-Type, Set-Cookie, etc.). Most importantly, HttpServletResponse lets you obtain a PrintWriter that you use to send document content back to the client.
Two requirements for your servlet
- Extend HttpServlet
- Provide doGet() or doPost()
Web application cannot call a Java class. It has to call a Servlet. Inside these methods you can read or write from a database, output to a text file, etc.
Servlets are the entry point for Java applications.
HttpServlet is the only one that we will deal with directly, but we might deal with the GenericServlet through inheritance.
Part of the platform-independent calls are in the GenericServlet, the part that is tied to HTTP protocol is in the HttpServlet. This is to allow for the flexibility if someone wants to create a Servlet that uses a different protocol.
Common Servlet Classes
Servlet (Interface) |
Javax.servlet
GenericServlet |
ServletConfig |
ServletContext |
RequestDispatcher |
ServletRequest |
ServletResponse |
Javax.servlet.http – Abstract Class
HttpServlet |
HttpServletRequest |
HttpServletResponse |
|
HttpSession |
Everything that is posted goes through HttpServletRequest. Everything that gets sent back is handled through HttpServletResponse. Use HttpSession to maintain state in a session object.
Tomcat gets that data as an ASCII text file and loads it up.
JAVA CODE
package edu.collin.frost
–Always use a package. Otherwise, you will have problems with the class loaders.
import javax.servlet.*;
import javax.servlet.http.*;
–Import both packages of the servlet API
–Use an asterisk here, but normally list packages individually.
import java.io.*;
public class TemplateServlet extends HttpServlet {
–No naming requirement, don’t need to name it Servlet
public void doGet (HttpServletRequest request, HttpServletReponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost (HttpServletRequest request, HttpServletReponse response)
throws ServletException, IOException {
doGet(request, response);
}
Call doGet() and pass it the two objects request and response.
Response is empty when it is passed in, but Tomcat wants it there so it can account for it. Tomcat is a container and has to keep track of all objects. Request is full of objects, but response is empty until you send back a response object.
When the web page starts…
Full response object, empty request object
Method throws the exception back to Tomcat. Will only affect that thread and not bring down the web server.
Servlet should only deal with the request and response. It should not deal with business logic. The C in the MVC architecture is the Servlet. The M is the business logic.
We will initially create “thick Servlets” until we progress to that point where we delegate it out to another class.
Here we print into the response object.
Response.setContentType (“text/html”);
–Set MIME type, everything after this should be treated as HTML
PrintWriter out = response.getWriter();
–PrintWriter is a Java class that writes to a buffer.
–Get PrintWriter from response object so Tomcat knows about it
out.println(“<html>”);
out.println(“<head><title>Example Output</title></head>”);
out.println(“<body>”);
–Java just sees this as strings. Does not care about the HTML tags.
out.println(“</body></html>”);
out.close();
}
doPost() called by Tomcat. Takes response object and sends the file back. Have to have a doPost() and / or a doGet(). But, you can have other methods in your Servlet.
Invoking a Servlet
Wrong Way: To invoke it without registering it in the web.xml file.
1.) Uncomment the invoker servlet and mapping
2.) If servlet full name is ‘com.frost.MyServlet’ then call it ‘servlet/com.frost.MyServlet’
Right Way: Invoke a servlet that is registered in the web.xml file:
1) Register servlet such as:
<servlet>
<servlet-class>com.frost.MyServlet<servlet-class
<servlet-mapping>
<servlet-name>Name</servlet-name>
<url-pattern>/Name</url-pattern>
</servlet-mapping>
2) Call the servlet by ‘Name’
FirstApp
First step is to create the First App folder under Webapps. We need two folders under WEB-INF – classes and lib. Classes that are deployed need to be in nested package folders (i.e. classes – cc –frost).
Housekeeping Note: Drop in Customized Versions of the context.xml and web.xml files into Tomcat’s conf directory.
Address of First App
http://localhost:8080/FirstApp/servlet/cc.ronday.FirstAppServlet
Second Exercise
Add the
String name = request.getParameter(“theName”);
Then modify the following ..
out.println(“<h2>Hello ” + name +”.</h2>”);
Hello null.
When you append the parameter to the Address Line, it shows up on the page
http://localhost:8080/FirstApp/servlet/cc.ronday.FirstAppServlet?theName=Chris
Hello Chris.
Third Exercise
Create the Following HTML Form
<html>
<head>
<title>FirstAppForm</title></head>
<body>
<h2>Please enter your name.</h2>
<form method=”GET” action=”servlet/cc.frost.FirstAppServlet”>
<input type=”text” name=”theName”/><br><br>
<input type=”submit” value=”Submit”/>
</form>
</body>
</html>
Save the HTML Form under the webapps/FirstApp folder and Run It
http://localhost:8080/FirstApp/FirstAppForm.html
Using Eclipse
Set Workspace to c:javarun. Automatically creates a .metadata folder. Ant Script will take classes and put them in the proper folders.
.classpath – Writes list of things
.project
build.xml – Standard name for an Ant build script
build.properties – Has the variables that you can change for your project
- Have to define the name of your app
- Define the location of Tomcat on your machine
Expects these folders
src
- Only Java Files – It’s the Source Tree
war
- If you zip up your application, it becomes a WAR file
- Laid out like your app would be under the webapp folder
- Classes folder needs to be empty so Ant can populate it
ExternalLib
- Need the servlet-api.jar file in the build path
To Build with the Properties File
Right click on build.xml > Choose Run as… > Ant Script