Download presentation
Presentation is loading. Please wait.
Published byHarold Wade Modified over 9 years ago
1
Java Servlets
2
Servlets When we run small Java programs within a browser these are referred to as Applets... And when we run small Java programs within a server these are “Servlets” A servlet is a program designed to process a client request (which requires interactivity). It processes arguments and formats its results as a short lived document. HTML servlets are becoming a popular mechanism for creating interactive servers.
3
Servlets versus CGI (1) Traditionally programs were run on web servers using Common Gateway Interface (CGI) scripts written in languages such as Perl. Must create a new interpreter process for each client request Comparatively slow to start Expensive of memory resources when serving several clients at the same time Interpreted programs are CPU intensive
4
Servlets versus CGI (2) Servlets use Java objects which persist between requests to the server Low latency since requests run in threads Offer performance advantages since programs are compiled and can take advantage of JITs and/or Hotspot JVMs. Servlet groups can share a JVM leading to smaller memory footprints. Servlets run in a Sandbox offering protection from malicious (or accidental) damage
5
Creating a simple servlet Servlets are written in a similar fashion to applets Write a new servlet class which extends javax.servlet.http.HttpServlet (or just implements javax.servlet.Servlet ) Override certain methods to deal with requests Get your methods to create an HTML document to return information to the client’s browser Load the servlet byte codes onto your web server (for example apache/jserv)
6
Import servlet methods (1) When the servlet is first loaded it makes a single call to the method public void init(ServletConfig config) This may optionally be overridden to initialise the state of the servlet (for example loading state information from a file). When a servlet is finally unloaded it makes a single call to the method public void destroy() If you wish to save servlet state to a file (or using JDBC) this is the method to override
7
Import servlet methods (2) To handle an HTTP GET request implement protected void doGet(HttpServletRequest request, HttpServletResponse response) If a browser visits your servlet this is where you get to create a document for it to display To handle an HTTP POST request provide protected void doPost(HttpServletRequest request, HttpServletResponse response) If your document contains an HTML form and the user posts the results this is where you can extract and process them Also methods for HTTP OPTIONS, TRACE and DELETE (more exotic options)
8
Import servlet methods (3) Two objects are passed as parameters to all these handler methods: javax.servlet.http.HttpServletRequest Represents the information that was passed to the server when the user submitted the request by visiting/posting to the servlets URL. javax.servlet.http.HttpServletResponse Used to construct a response document that is returned to the user Each has a raft of methods so check the Javadoc for details
9
Example: a simple chat server A web based chat room server A number of users can connect to the servlet using browsers Read a list of the previous messages Optionally append new messages to the list Messages are attributed to a specific author and are time stamped Messages do not persist after the chat server is stopped (easy enough to rectify)
10
ChatServer (1) public class ChatServlet extends HttpServlet { Vector messages = new Vector(); public void init(ServletConfig config) throws ServletException { super.init(config); } public void destroy() { // Currently does nothing }.... }
11
ChatServer (2) protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { createDocument(response); } protected void createDocument(HttpServletResponse response) throws IOException { response.setContentType("text/html"); response.setHeader("pragma", "no-cache"); PrintWriter writer = response.getWriter(); writer.println(" "); writer.println(" Chat Servlet "); writer.println(" "); Date now = new Date(); writer.println("Current server time is " + now + " ");.... writer.println(" "); writer.close(); }
12
ChatServer (3) for (int i = 0; i < messages.size(); i++) { writer.println(" "); String messageString = (String) messages.elementAt(i); writer.println(messageString); } writer.println(" "); writer.println("Enter your name: “ + “ "); writer.println("Enter your message: ” + “ ” + “Type your message here "); writer.println( " "); writer.println(" ");
13
ChatServer (4) protected synchronized void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = request.getParameter("name"); String message = request.getParameter("message"); if (name != null && message != null) { Date timeStamp = new Date(); String messageString = " Message " + messages.size() + " from " + name + " at " + timeStamp + ": " + message + " "; messages.add(messageString); } createDocument(response); }
14
Performance (1) Servlets offer better performance than most of the previous CGI like technologies But CGI/Servlets concentrate the load on the server When designing high throughput servers only use servlets where you really need interactivity Searches/Shopping carts Data that is very short lived (stock quotes) This also applies to low throughput servers that might need to scale later
15
Performance (2) Consider using periodic programs to generate static documents on disk The cost of serving fixed documents will always be less than the cost of server side execution Disk space is cheap! Consider using some client side technologies when possible This places the load on the client machines rather than the server
16
Pull versus Push transports How can a chat reader find out when a new message has been posted by another author? Only by repeatedly hitting the Reload button! HTTP (& TCP/IP services in general) transfer documents on the user’s request To push updates automatically from the server you will need to: Start a reverse server within each client Use a remote procedure call system such as RMI or CORBA
17
Servlets and JSP Java Server Pages is an extension to the servlets API. With conventional servlets you embed the HTML that you need inside a Java program. With JSP you embed your Java program within a HTML document (by using special tags). Works rather like JavaScript but the JSP script runs on the server before the page is dispatched to the user’s browser.
18
Useful sources of information For information about HTML try http://www.w3schools.com You can download Sun’s servlet development kit from their web site at the http://java.sun.com/products/servlet You can download apache’s Tomcat server from http://jakarta.apache.org For other information about Servlet development try http://www.servlets.com
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.