1 of 49

Java Servlets

2 of 49

What Are Servlets?

  • Basically, a java program that runs on the server
  • Creates dynamic web pages

3 of 49

What Do They Do?

  • Handle data/requests sent by users (clients)
  • Create and format results
  • Send results back to user

4 of 49

Who Uses Servlets?

  • Servlets are useful in many business oriented websites

  • … and MANY others

5 of 49

History

  • Dynamic websites were often created with CGI
  • CGI: Common Gateway Interface
  • Poor solution to today’s needs
  • A better solution was needed

6 of 49

Servlets vs. CGI

  • Servlet Advantages
    • Efficient
      • Single lightweight java thread handles multiple requests
      • Optimizations such as computation caching and keeping connections to databases open
    • Convenient
      • Many programmers today already know java
    • Powerful
      • Can talk directly to the web server
      • Share data with other servlets
      • Maintain data from request to request
    • Portable
      • Java is supported by every major web browser (through plugins)
    • Inexpensive
      • Adding servlet support to a server is cheap or free

7 of 49

Servlets vs. CGI

  • The Common Gateway Interface is the first technology used to generate dynamic contents.
  • It allows a web client to pass data to the application running on the web server so that a dynamic web page can be returned to the client according to the input data.

  • CGI Advantages
    • CGI scripts can be written in any language
    • Does not depend on servlet-enabled server

8 of 49

What Servlets Need

  • JavaServer Web Development Kit (JSWDK)
  • Servlet capable server
  • Java Server Pages (JSP)
  • Servlet code

9 of 49

Java Server Web Development Kit

  • JSWDK
    • Small, stand-alone server for testing servlets and JSP pages
  • The J2EE SDK
    • Includes Java Servlets 2.4

10 of 49

Servlet capable server

Apache

    • Popular, open-source server
  • Tomcat
    • A “servlet container” used with Apache

Other servers are available

11 of 49

Java Server Pages

  • Static HTML pages with dynamically-generated HTML
  • Does not extend functionality of Servlets
  • Allows you to separate “look” of the site from the dynamic “content”
    • Webpage designers create the HTML
    • Servlet programmers create the dynamic content
    • Changes in HTML don’t effect servlets

12 of 49

<head>

</head>

<body>

<%

// jsp sample code

out.println(" JSP, ASP, CF, PHP - you name it, we support it!");

%>

</body>

</html>

13 of 49

Servlet Code

  • Written in standard Java
  • Implement the javax.servlet.Servlet interface

14 of 49

package servlet_tutorials.PhoneBook;�import javax.servlet.*;�import javax.servlet.http.*;�import java.io.*;�import java.util.*; �import java.sql.*; �import java.net.*;��public class SearchPhoneBookServlet extends HttpServlet { ��public void doGet(HttpServletRequest req, HttpServletResponse res) �throws ServletException, IOException { ��String query = null; �String where = null; �String firstname = null; �String lastname = null; �ResultSet rs = null;��res.setContentType("text/html"); �PrintWriter out = res.getWriter();��// check which if any fields in the submitted form are empty �if (req.getParameter("FirstName").length() > 0) �firstname = req.getParameter("FirstName"); �else firstname = null;�} �

15 of 49

Life Cycle

  • Servlet class is loaded.
  • Servlet instance is created.
  • init method is invoked.
  • service method is invoked.
  • destroy method is invoked.

16 of 49

Servlet Class Loading

  • The classloader is responsible to load the servlet class.
  • The servlet class is loaded when the first request for the servlet is received by the web container.

17 of 49

Servlet instance creation

  • The web container creates the instance of a servlet after loading the servlet class.
  • The servlet instance is created only once in the servlet life cycle.

18 of 49

Init method invoking

  • The web container calls the init method only once after creating the servlet instance.
  • The init method is used to initialize the servlet.
  • It is the life cycle method of the javax.servlet.Servlet interface.
  • Syntax of the init method is given below:
    • public void init(ServletConfig config) throws ServletException  

19 of 49

Service method invoking

  • The web container calls the service method each time when request for the servlet is received.
  • If servlet is not initialized, it follows the first three steps as described above then calls the service method.
  • If servlet is initialized, it calls the service method.
  • servlet is initialized only once.
  • The syntax of the service method of the Servlet interface is given below:
  • public void service(ServletRequest request, ServletResponse response)     throws ServletException, IOException  

20 of 49

Service - Request

  • Any requests will be forwarded to the service() method
    • doGet()
    • doPost()
    • doDelete()
    • doOptions()
    • doPut()
    • doTrace()

21 of 49

Destroy

  • destroy() method is called only once
  • Occurs when
    • Application is stopped
    • Servlet container shuts down
  • Allows resources to be freed

  • public void destroy()  

22 of 49

Client Interaction

  • Request
    • Client (browser) sends a request containing
      • Request line (method type, URL, protocol)
      • Header variables (optional)
      • Message body (optional)
  • Response
    • Sent by server to client
      • response line (server protocol and status code)
      • header variables (server and response information)
      • message body (response, such as HTML)

23 of 49

  • Thin clients (minimize download)
  • Java all “server side”

Client

Server

Servlets

24 of 49

Saving State

  • Session Tracking
    • A mechanism that servlets use to maintain state about a series of requests from the same user (browser) across some period of time.
  • Cookies
    • A mechanism that a servlet uses to have clients hold a small amount of state-information associated with the user.

25 of 49

Servlet Communication

  • To satisfy client requests, servlets sometimes need to access network resources: other servlets, HTML pages, objects shared among servlets at the same server, and so on.

26 of 49

Calling Servlets

  • Typing a servlet URL into a browser window
    • Servlets can be called directly by typing their URL into a browser's location window.
  • Calling a servlet from within an HTML page
    • Servlet URLs can be used in HTML tags, where a URL for a CGI-bin script or file URL might be found.

27 of 49

Request Attributes and Resources

  • Request Attributes
    • getAttribute
    • getAttributeNames
    • setAttribute
  • Request Resources - gives you access to external resources
    • getResource
    • getResourceAsStream

28 of 49

Multithreading

  • Concurrent requests for a servlet are handled by separate threads executing the corresponding request processing method (e.g. doGet or doPost). It's therefore important that these methods are thread safe.
  • The easiest way to guarantee that the code is thread safe is to avoid instance variables altogether and instead use synchronized blocks.

29 of 49

30 of 49

import java.io.*; �import javax.servlet.*; �import javax.servlet.http.*;

  • public class SimpleCounter extends HttpServlet {
  • int count = 0;
  • public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
  • res.setContentType("text/plain");
  • PrintWriter out = res.getWriter();
  • count++;
  • out.println("This servlet has been accessed " + count + " times since loading");
  • }
  • }

Simple Counter Example

31 of 49

MultiThread Problems

  • Problem - Synchronization between threads

count++; // by thread1

count++; // by thread2

out.println.. // by thread1

out.println.. // by thread2

Two Requests will

get the same

value of counter

  • Solution - Use Synchronized Block!
    • Synchronized Block
    • Lock(Monitor)

32 of 49

Better Approach

  • The approach would be to synchronize only the section of code that needs to be executed automically:

PrintWriter out = res.getWriter(); �synchronized(this) �{�    count++; �    out.println("This servlet has been accessed " + �             count + "times since loading");�}�This reduces the amount of time the servlet spends in its synchronized block, and still maintains a consistent count.

33 of 49

Example: On-line Phone Book

  • Design

34 of 49

Example: On-line Phone Book

35 of 49

Search Form

<html>�<head> �<title>Search Phonebook</title> �</head> �<body bgcolor="#FFFFFF"> <p><b>�Search Company Phone Book</b></p> �<form name="form1" method="get" action="servlet/servlet_tutorials.PhoneBook.SearchPhoneBookServlet"> �<table border="0" cellspacing="0" cellpadding="6"> <tr> <td >Search by</td> <td>�</td> </tr> <tr> <td><b>�First Name �</b></td> <td> �<input type="text" name="FirstName"> AND/OR</td> </tr> <tr> <td ><b>�Last Name�</b></td> <td >�<input type="text" name="LastName"></td> </tr> <tr> <td ></td> <td >�<input type="submit" name="Submit" value="Submit">�</td> </tr> </table>�</form>�</body>�</html>

Java server Page

Search_phone_book.jsp

36 of 49

Example: On-line Phone Book

37 of 49

Display Results

<html>�<%@page import ="java.sql.*" %>�<jsp:useBean id="phone" class="servlet_tutorials.PhoneBook.PhoneBookBean"/> �<%@ page buffer=35 %>�<%@ page errorPage="error.jsp" %>�<html>�<head>�<title>Phone Book Search Results</title>�<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head>�<body bgcolor="#FFFFFF"> <b>Search Results</b> <p> �<% String q = request.getParameter("query"); �ResultSet rs = phone.getResultSet(q); �%>�<% if (rs.wasNull()) { �%> �"NO RESULTS FOUND" �<% �} else �%>�<table> <tr> <td> <div align="center">First Name</b></div> </td> <td> <div align="center">Last Name</font></b></div> </td> <td> <div align="center">Phone Number</font></b></div> </td> <td> <div align="center">Email</font></b></div> </td> </tr>��<% while(rs.next()) { %> <tr> <td>�<%= rs.getString("first_name") %></td> <td><%= rs.getString("last_name") %></td> <td><%= rs.getString("phone_number") %>�</td> <td>�<%= rs.getString("e_mail") %>�</td> </tr> �<% } %> �</table>

Java Server Page

Display_search_results.jsp

38 of 49

Servlet

39 of 49

Java Bean & Database linked

40 of 49

Java Server Page -JSP

JSP technology is used to create web application just like Servlet technology. It can be thought of as an extension to Servlet because it provides more functionality than servlet such as expression language, JSTL-(Java Standard Tag Library), etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than Servlet because we can separate designing and development. It provides some additional features such as Expression Language, Custom Tags, etc.

41 of 49

Advantages of JSP over Servlet

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the features of the Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in JSP, that makes JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with presentation logic. In Servlet technology, we mix our business logic with the presentation logic.

42 of 49

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet code needs to be updated and recompiled if we have to change the look and feel of the application.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the code. Moreover, we can use EL, implicit objects, etc.

43 of 49

The Lifecycle of a JSP Page

The JSP pages follow these phases:

  • Translation of JSP Page
  • Compilation of JSP Page
  • Classloading (the classloader loads class file)
  • Instantiation (Object of the Generated Servlet is created).
  • Initialization ( the container invokes jspInit() method).
  • Request processing ( the container invokes _jspService() method).
  • Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

44 of 49

JSP page is translated into Servlet by the help of JSP translator. The JSP translator is a part of the web server which is responsible for translating the JSP page into Servlet. After that, Servlet page is compiled by the compiler and gets converted into the class file. Moreover, all the processes that happen in Servlet are performed on JSP later like initialization, committing response to the browser and destroy.

45 of 49

Creating a simple JSP Page

To create the first JSP page, write some HTML code as given below, and save it by .jsp extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the web-apps directory in apache tomcat to run the JSP page.

index.jsp

46 of 49

Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the JSP page. We will learn scriptlet tag later.

  1. <html>  
  2. <body>  
  3. <% out.print(2*5); %>  
  4. </body>  
  5. </html>  

It will print 10 on the browser.

47 of 49

How to run a simple JSP Page?

Follow the following steps to execute this JSP page:

  • Start the server
  • Put the JSP file in a folder and deploy on the server
  • Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example, http://localhost:8888/myapplication/index.jsp

48 of 49

Do I need to follow the directory structure to run a simple JSP?

No, there is no need of directory structure if you don't have class files or TLD files. For example, put JSP files in a folder directly and deploy that folder. It will be running fine. However, if you are using Bean class, Servlet or TLD file, the directory structure is required.

The Directory structure of JSP

The directory structure of JSP page is same as Servlet. We contain the JSP page outside the WEB-INF folder or in any directory.

49 of 49