Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.

Slides:



Advertisements
Similar presentations
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Advertisements

 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Technology Overview JAVA Servlets CS-611 S. Witherspoon.
J.Sant Servlets Joseph Sant Sheridan Institute of Technology.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
Servlets and a little bit of Web Services Russell Beale.
An introduction to Java Servlet Programming
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
1 CS6320 – Servlet Structure and Lifecycle L. Grewe.
Introduction to Servlet & JSP
Java Server and Servlet CS616 Team 9 Kim Doyle, Susan Kroha, Arunima Palchowdhury, Wei Xu.
All You Ever Wanted To Know About Servlets But Were Afraid to Ask.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
SE-2840 Dr. Mark L. Hornick1 Java Servlet-based web apps Servlet Architecture.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Server-side Technologies
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
Introduction Servlets and JSP Celsina Bignoli
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
Java Omar Rana University of South Asia. Course Overview JAVA  C/C++ and JAVA Comparison  OOP in JAVA  Exception Handling  Streams  Graphics User.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
Objectives Java Servlet Web Components
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Servlet Lifecycle Lec 28. Servlet Life Cycle  Initialize  Service  Destroy Time.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Java Servlets & Java Server Pages Lecture July 2013.
1 CS122B: Projects in Databases and Web Applications Spring 2015 Notes 03: Web-App Architectures Professor Chen Li Department of Computer Science CS122B.
Chapter 2 Web app architecture. High-level web app architecture  When a client request coming in and needs servlet to serve dynamic web content, what.
S ERVLETS Hits Counter 21-Nov-15. S ERVLETS - H ITS C OUNTER Many times you would be interested in knowing total number of hits on a particular page of.
Java Servlet API CGI / HTTP Concepts Java Servlet API.
All You Ever Wanted To Know About Servlets But Were Afraid to Ask.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
JavaServer Page by Antonio Ko. Overview ► Introduction ► What is a servlet? ► What can servlets do? ► Servlets Vs JSP ► Syntax ► Samples ► JavaBean ►
Java Servlets and Java Server Pages Norman White Stern School of Business.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
Servlets.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
Java Servlets Java Server Pages (JSP)
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
Java Servlets and Java Server Pages
Introduction To HTML Dr. Magdi AMER. HTML elements.
How CGI and Java Servlets are Run By David Stein 14 November 2006.
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
Distributed Web Systems Java Servlets Lecturer Department University.
CS122B: Projects in Databases and Web Applications Spring 2017
Introduction to Servlets
CS122B: Projects in Databases and Web Applications Winter 2017
Introduction Servlets and JSP
Servlets.
Java Servlets.
Servlet Fudamentals.
HTTP Servlet Overview Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might.
Chapter 26 Servlets.
CS122B: Projects in Databases and Web Applications Winter 2018
Introduction to Servlets
CS122B: Projects in Databases and Web Applications Spring 2018
CS122B: Projects in Databases and Web Applications Winter 2019
Basic servlet structure
Presentation transcript:

Java Servlets

What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic web pages Creates dynamic web pages

What Do They Do? Handle data/requests sent by users (clients) Handle data/requests sent by users (clients) Create and format results Create and format results Send results back to user Send results back to user

Who Uses Servlets? Servlets are useful in many business oriented websites Servlets are useful in many business oriented websites … and MANY others … and MANY others

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

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

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

What Servlets Need JavaServer Web Development Kit (JSWDK) JavaServer Web Development Kit (JSWDK) Servlet capable server Servlet capable server Java Server Pages (JSP) Java Server Pages (JSP) Servlet code Servlet code

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

Servlet capable server Apache Popular, open-source server Popular, open-source server Tomcat Tomcat A “servlet container” used with Apache A “servlet container” used with Apache Other servers are available

Java Server Pages Lets you mix regular, static HTML pages with dynamically-generated HTML Lets you mix regular, static HTML pages with dynamically-generated HTML Does not extend functionality of Servlets Does not extend functionality of Servlets Allows you to separate “look” of the site from the dynamic “content” Allows you to separate “look” of the site from the dynamic “content” Webpage designers create the HTML Webpage designers create the HTML Servlet programmers create the dynamic content Servlet programmers create the dynamic content Changes in HTML don’t effect servlets Changes in HTML don’t effect servlets

<% // jsp sample code out.println(" JSP, ASP, CF, PHP - you name it, we support it!"); %> JSP, ASP, CF, PHP - you name it, we support it!

<% // jsp sample code out.println(" JSP, ASP, CF, PHP - you name it, we support it!"); %> JSP, ASP, CF, PHP - you name it, we support it!

<% // jsp sample code out.println(" JSP, ASP, CF, PHP - you name it, we support it!"); %> JSP, ASP, CF, PHP - you name it, we support it!

<% // jsp sample code out.println(" JSP, ASP, CF, PHP - you name it, we support it!"); %> JSP, ASP, CF, PHP - you name it, we support it!

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

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; }

Main Concepts of Servlet Programming Life Cycle Life Cycle Client Interaction Client Interaction Saving State Saving State Servlet Communication Servlet Communication Calling Servlets Calling Servlets Request Attributes and Resources Request Attributes and Resources Multithreading Multithreading

Life Cycle Initialize Initialize Service Service Destroy Destroy

Life Cycle: Initialize Servlet is created when servlet container receives a request from the client Servlet is created when servlet container receives a request from the client Init() method is called only once Init() method is called only once

Life Cycle: Service Any requests will be forwarded to the service() method Any requests will be forwarded to the service() method doGet() doGet() doPost() doPost() doDelete() doDelete() doOptions() doOptions() doPut() doPut() doTrace() doTrace()

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

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

Thin clients (minimize download) Thin clients (minimize download) Java all “server side” Java all “server side” Client Server Servlets

Saving State Session Tracking 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. A mechanism that servlets use to maintain state about a series of requests from the same user (browser) across some period of time. Cookies Cookies A mechanism that a servlet uses to have clients hold a small amount of state- information associated with the user. A mechanism that a servlet uses to have clients hold a small amount of state- information associated with the user.

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. 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.

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

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

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. 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. The easiest way to guarantee that the code is thread safe is to avoid instance variables altogether and instead use synchronized blocks.

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

MultiThread Problems Problem - Synchronization between threads 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! Solution - Use Synchronized Block! Synchronized Block Synchronized Block Lock(Monitor) Lock(Monitor)

Better Approach The approach would be to synchronize only the section of code that needs to be executed automically: 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.

Example: On-line Phone Book Design Design

Example: On-line Phone Book

Search Form Search Phonebook Search Company Phone Book Search by First Name AND/OR Last Name Search Phonebook Search Company Phone Book Search by First Name AND/OR Last Name Java server Page Search_phone_book.jsp

Example: On-line Phone Book

Display Results Phone Book Search Results Search Results "NO RESULTS FOUND" First Name Last Name Phone Number Phone Book Search Results Search Results "NO RESULTS FOUND" First Name Last Name Phone Number Java Server Page Display_search_results.jsp

Servlet

Java Bean & Database linked

Conclusion

Questions? Comments?

References cit /Lectures/21-servlets.ppt cit /Lectures/21-servlets.ppt