Professional Documents
Culture Documents
Understand the Servlet Architecture. Compare Servlet & Other Similar technologies. Understand the Servlet Life Cycle. Handle Request & Response. Generate Dynamic HTML. Handle Sessions.
Common Gateway Interface (CGI) ColdFusion (Allaire) Active Server Pages (ASP) Server-Side JavaScript (SSJS) Personal Home Page tools (PHP) Java Servlets JavaServer Pages
Java Servlet A Java program that extends the functionality of a Web server, generating dynamic content and interacting with Web clients using a request response paradigm. An extensible Web technology that uses template data, custom elements, scripting languages, and server-side Java objects to return dynamic content to a client. Typically the template data is HTML or XML elements. The client is often a Web browser.
Advantages of Servlets
Java objects which extend the functionality of a HTTP server(a big plus). Dynamic customization of content Platform and server independent No CGI limitations better performance Easier to write than CGI code no need to parse headers and get info (all that is done by the HttpServlet class ) No Networking restrictions (like applets) Do not create a new process (or Servlet for every request) Servlets can persist over time
Server Extensions
Enhance or Change the base functionality of the server, allowing the server to handle tasks that were once relegated to external CGI programs.
Request for Servlet1 Servlet initialized once; reused until destroyed and
garbage collected.
init() Method
Called by server immediately after servlet is instantiated Called only once Servlet creates and initializes the resources needed for handling requests
service() Method
It is the heart of the servlet. It handles all requests sent by a client. Each request message from a client results in a single call to the servlet's service() method. It reads the request and produces the response message public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;
destroy() Method
This signifies the end of a servlets life. Its also a good place to save any persistent information that will be used the next time the servlet is loaded. It is called to allow the servlet to clean up any resources. Public void destroy();
destroy()
each client request creates a new thread with service
Servlet Interface
Servlets Classes / Interfaces are available in packages (in java servlet development kit) javax.servlet.http javax.servlet
GenericServlet Class
Server GenericServlet subclass
request response
service()
KEY :
implemented by subclass
Web Server
doGet()
service()
doPost() doHead()
Implementation of doGet() doPost() is to return an error to the calling client if servlet does not override these methods. KEY : implemented by subclass
service
HttpServlet
client
GET /index.html HTTP/1.0
http://www.mcp.com/index.html
service()
doPost()
Web server uses logic: doHead() myHelloServlet is loaded. If not , then load the servlet. call service method (already implemented in HttpServlet) (it checks the request type and correspondingly calls the doGet() or doPost() method )
java.io InputStream
OutputStream Serializable
Servlet
ServletConfig
ServletContext
ServletRequest java.lang
ServletResponse
Object GenericServlet SingleThreadModel
Exception
ServletException
UnavailableException
extends implements
KEY Class
ABSTRACT CLASS
Interface
service(req, res)
ServletConfig
Serializable
ServletRequest
ServletResponse
ServletInputStream
ServletOutputStream
Class
ABSTRACT CLASS
Interface
implements
ServletContext / ServletConfig
ServletConfig used to get initialization parameters getServletContext() String getInitParameter(String) Enumeration getInitParameterNames() ServletContext useful for logging & finding out about the other servlets Servlet getServlet(String) Enumeration getServlets() Enumeration getServletNames() void log(String) void log(Exception, String)
GenericServlet
Serializable
javax.servlet.http.*
HTTPServlet
Class
ABSTRACT CLASS
Interface
extends
implements
Servlet Architecture
Servlet
Methods for managing a servlet and communicating with clients
HTTPServlet
Interface
class
extends
GET request
Servlet
response
ServletResponse Encapsulates communication from server to client
package codecamp; A Simple Code Example import javax.servlet.*; import javax.servlet.http.*; import java.io.*; Public class ServletGet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<title>First Servlet</title>"); out.println("<big>Hello Code Camp! </big>"); } }
Example
Write the following html file: mydisplay.html
<HTML> <HEAD> <TITLE> calling servlets </TITLE> </HEAD> <BODY> <form method=get action="http://localhost:8080/servlet/servletGet"> <input type=submit value="call servletGet"> </form> </BODY> </HTML>
Click on the button call servletGet and note that the earlier servlet is called.
NOTE:User clicked on button, and the browser then Eg:method based on action settings. mydisplay.html generated the GET
client
GET /mydisplay.html HTTP/1.0 /servlet/servletGet HTTP/1.0
http://localhost//mydisplay.html
call servletGet
Example
Modify only the following line in html file: mydisplay.html
<form method=post action="http://localhost:8080/servlet/servletGet">
NOTE:User clicked on button, and the browser then generated the POST method based on action settings. NOTE: the servlet servletGet did not contain a doPost method and hence got the error. Rename doGet() to doPost() and it would then work.
Example
Write a html with three text fields for name, id and location, with a submit button. Set the form method as GET, and action as servlet/servletGetParam
Eg: servlet_get_HTML.html
Write a servlet with doGet() method. In the doGet() method read the parameters and then send it back to the browser for display
Eg: servletGetParam.java
Example
Write a html with three text fields for name, id and location, with a submit button. Set the form method as POST, and action as servlet/servletGetParam
Eg: servlet_post_HTML.html
Write a servlet with doPost() method. In the doPost() method read the parameters and then send it back to the browser for display
Eg: servletPost.java
Interface ServletRequest
information about the client name of the host and the IP address of client parameters sent from the client browser scheme used by the browser to communicate to servlet (eg. http; https; ftp;..) protocol used by client (eg. ftp) access to the ServletInputStream (which allows servlet to read binary data from the client ) information about server name of the server port used by the server
ServletRequest
Subclass ServletRequest to provide protocol specific information
Example: HTTPServletRequest (extends ServletRequest )supports methods to retrieve more protocol specific headers (getMethod() to identify the type of request)
javax.servlet.ServletRequest
class Name public abstract methods
ServletRequest
String getContentType() ServletInputStream getInputStream() String getParameter(String) Enumeration getParameterNames() String getProtocol() BufferedReader getReader() String getRemoteAddr() String getServerName() int getServerPort() String getScheme() String getRealPath() String getCharacterEncoding() Object getAttribute()
interface HTTPServlet
Information from client additional path info (sent along with request) eg /servlet/myservlet/dict/defn.txt /dict/defn.txt is the additional info to the servlet myservlet within your servlet use getPathInfo() (null if no such data is available) what was requested (file/ servlet/) HTTP headers sent by the client Connection, User-Agent, host, Accept, Acceptlanguage, Accept-Charset
HTTP Headers
General : Information not related to Client, Server or HTTP protocol. Request : Preferred Document formats and server parameters. Response : Information about the server. Entity : Information on the data that is being sent between the client and server.
javax.servlet.http.HttpServletRequest
Class Name public abstract methods
Example
Write a servlet that implements the doGet() method. Capture the information encapsulated in the request object (in ServletRequest and HTTPServletRequest), and send this info back to the client.
Eg: helloservletGet.java
ServletResponse Interface
Allows the servlet to reply to the client Allows the servlet to set the content length and MIME type Provides a handle to ServletOutputStream (or Writer) to send data to the client Subclass HTTPServletResponse supports methods to set more protocol specific headers
javax.servlet.ServletResponse
Class Name ServletResponse public void setContentLength(int) abstract void setContentType(String); ServletOutputStream getOutputStream() methods PrintWriter getWriter() String getCharacterEncoding(String)
javax.servlet.http. HttpServletResponse
Class Name public abstract methods
HTTPServletResponse
void addCookie(http.Cookie) boolean containsHeader(String); String encodeURL(String) String encodeRedirectURL(String) String encodeUri(String) String encodeRedirectUri(String) void setHeader(String,String) void setIntHeader(String,int) void setDateHeader(String,long) void setStatus(int,String) void sendError(int,String) void sendRedirect(String)
Redirecting
Redirection can be set using the following methods in the HttpServletResponse class
setStatus(status code) status codes available in the HttpServletResponse class as static variables setHeader(Location, give new site location here) the new location must be an absolute url path setHeader(Refresh, 3) will tell the browser for 3 seconds before refreshing the page setHeader(Refresh, 3; URL=..) will tell the browser for 3 seconds before going to the new location specified in the command.
Generating HTML
Hardcoded in the program (servletGet.java) Using an HTML generator (require additional software; html generation classes) Using an HTML generator creatively
Eg : ServletGet.java
Redirecting a Request
Servlet can use status codes and headers to inform a client to use another URL. It is useful when document (html file) has moved. load balancing is required. (one machine can distribute the load to many machines)
Serializable
protected void doGet(HttpServletRequest, HttpServletResponse) methods long getLastModified(HttpServletRequest);
void doPost(HttpServletRequest, HttpServletResponse) void method supports HttpServletResponse) The service doPut(HttpServletRequest, HTTP 1.0 void doDelete(HttpServletRequest, HttpServletResponse) protocol.void doOptions(HttpServletRequest, HttpServletResponse) This method dispatches each request void doTrace(HttpServletRequest, HttpServletResponse) to the method designed to handle it. void service(HttpServletRequest, HttpServletResponse) public void service(ServletRequest, ServletResponse)
Overriding Methods
Servlet writer who wants to handle the GET and the HEAD (HTTP protocol) must override the doGet() method in the servlet. Similarly override doPost() method to handle POST request doPut() method to handle PUT requests doDelete() method to handle DELETE requests
Notes
Servlets are fundamentally multithreaded, hence can run multiple service() methods. Therefore the code for service method must be thread safe. If you do not want a multithreaded server then one must implement the SingleThreadedModel interface.
Example
Write a counter servlet that counts the number of clients served.
Eg: MyCounterServ.java
Modify the above servlet so that if many users are accessing the variable count, it should be synchronized.
Eg: MyCounterServSyn.java
Example
Write a servlet that informs the client that the site has moved, and allow let the browser go to the new url automatically after 9 seconds.
Eg: RelocateServlet.java
Request Dispatcher
The basic use of a RequestDispatcher: One can effectively use the RequestDispatcher to call a JSP from a servlet or a servlet from another servlet. RequestDispatcher rd = getServletContext().getRequestDispatcher(" /welcome.jsp");
rd.include(request, response);
Example
Write a serlvet that sends an image to the browser. Image file must be on the server system.
Eg: servletImage.java
Problem: If we write 2 images to the application, it will read only the first one. Hence, one can send only one image at a time.
Example
Write a serlvet that sends 2 <img src=> tags to the client. The client would load one image after another and display both of them.
Eg: servletImageHTML.java
Note: All send the html tag is stored in a Solution: the data to be sent<img src=>, and the byteArrayOutputStream and sent all the information browser will open connection and get at once. This is buffering but could slow down when images can be from server. This way any number oflot of information is being sent passed. to the client.
User Authentication
Specify in the resource list servlet resource/ and what type of authentication once set, then the browser gives a dialog box and then sends the name and password to the servlet
Eg: secureServlet.java
Session Tracking
Mechanism to maintain a state about a series of requests from the same user (request originating from same browser) Sessions are shared across servlets HttpSession Object Can Store (name, value) Pairs. Persistence and disk swapping through Object Serialization. Works across protocols (HTTP/HTTPS). Session validity, Creation time etc.
Eg: SessionDemo.java
Ways of Session-Tracking
Hidden Form Fields Persistent Cookies Servlet API
Security Issues
The Servlet Sandbox Access Control Lists (ACLs)
Servlet Sandbox
It is an area where Servlets are given restricted authority on the server. They may not have access to the file system or network, or they may have been granted a more trusted status. It is up to the web server administrator to decide which servlets are granted this status.
Servlet Environment
Inter-Servlet Communication How to call a method of another Servlet
Formatted results thru DataInputStream object created by URLConnection object SQL Query ResultSet Object
Exercise (contd..)
20. Due to the implementation of the application on the AWT framework it is required to install the JRE software & the required application components on each machine which needs to communicate with the application. A better alternative would be to implement the same in a http based server architecture,(repeat exercises 1 to 5 here)[20]
ThankQ