A Servlet’s Job Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit.

Slides:



Advertisements
Similar presentations
Servlets. Servlets are modules that extend Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry.
Advertisements

4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Java Server Pages (JSP)
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Introduction to Servlets Based on: Hall, Brown, Core Servlets and JavaServer Pages.
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.
10-Jun-15 Servlets. 2 Servers A server is a computer that responds to requests from a client Typical requests: provide a web page, upload or download.
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.
JSP Java Server Pages Reference:
Core Servlets Chapter 3 Link for Core Servlets code: om/archive/ om/archive/
1 CS6320 – Servlet Structure and Lifecycle L. Grewe.
Servlets Replace Common Gateway Interface Scripts Extend Server Functionality Modules (software components) Like applets to browsers No GUI.
Introduction to Java Servlets Vijayan Sugumaran School of Business Administration Oakland University Note: Some of the slides were imported from
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
13-Jul-15 Servlets. 2 Servers A server is a computer that responds to requests from a client Typical requests: provide a web page, upload or download.
1 Servlets and HTML Form Data Parts of this presentation was provided by Vijayan Sugumaran Department of DIS Oakland University Rochester,
Server Side Programming Web Information Systems 2012.
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.
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.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
1 Databases & Web-based Applications JDBC & Java Servlets A. Benabdelkader ©UvA, 2002/2003.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
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.
SKT-SSU IT Training Center Servlet and JSP. Chapter Three: Servlet Basics.
111 Java Servlets Dynamic Web Pages (Program Files) Servlets versus Java Server Pages Implementing Servlets Example: F15 Warranty Registration Tomcat Configuration.
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. Servlets When we run small Java programs within a browser these are referred to as Applets... And when we run small Java programs within.
Mark Dixon 1 09 – Java Servlets. Mark Dixon 2 Session Aims & Objectives Aims –To cover a range of web-application design techniques Objectives, by end.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
Slides © Marty Hall, book © Sun Microsystems Press 1 Handling the Client Request: Form Data Core Servlets & JSP book:
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
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.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
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.
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.
Mark Dixon 1 11 – Java Servlets. Mark Dixon 2 Session Aims & Objectives Aims –To cover a range of web-application design techniques Objectives, by end.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
Introduction To HTML Dr. Magdi AMER. HTML elements.
Chapter 4 Request and Response. Servlets are controlled by the container.
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
Distributed Web Systems Java Servlets Lecturer Department University.
Programming with Java Lecture 6 Elements of a Java Servlet
Introduction to Servlets
Servlets.
Chapter 26 Servlets.
Servlets and Java Server Pages
Servlets and JSP 20-Nov-18 servletsJSP.ppt.
Servlets.
Handling FORM Data using Servlets
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Web Search Interfaces.
Servlets 7-Apr-19.
Basic servlet structure
Servlets: Servlet / Web Browser Communication I
Presentation transcript:

A Servlet’s Job Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit data back to client (HTML) Send the implicit data to client (status codes and response headers)

A Servlet That Generates Plain Text (HelloWorld.java) package testPackage; // Always use packages. import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println("Hello World"); }

doGet – Code for an HTTP GET request. doPost also common. HttpServletRequest – Contains anything that comes from the browser HttpServletResponse – Used to send stuff to the browser. Most common is getWriter for a PrintWriter that points at browser.

A Servlet That Generates HTML Tell the browser that you’re sending it HTML – response.setContentType("text/html"); Modify the println statements to build a legal Web page – Print statements should output HTML tags

A Servlet That Generates HTML (Code) public class TestServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter();

out.println (" \n" + " \n" + " A Test Servlet \n" + " \n" + " Test \n" + " Simple servlet for testing. \n" + " "); }

public class TestServlet2 extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Test Servlet with Utilities";

out.println (ServletUtilities.headWithTitle(title) + " \n" + " " + title + " \n" + " Simple servlet for testing. \n" + " "); }

The Servlet Life Cycle init – Executed once when the servlet is first loaded. Not called for each request. service – Called in a new thread by server for each request. Dispatches to doGet, doPost, etc. Do not override this method! doGet, doPost (do override) – Handles GET, POST, etc. requests. – Override these to provide desired behavior. destroy – Called when server deletes servlet instance. Not called after each request.

Why You Should Not Override service The service method does other things besides just calling doGet – You can add support for other services later by adding doPut, doTrace, etc. – You can add support for modification dates by adding a getLastModified method – The service method gives you automatic support for: HEAD requests OPTIONS requests TRACE requests

Debugging Servlets Use print statements; run server on desktop Integrated debugger in IDE – Right-click in left margin in source to set breakpoint (NetBeans) – “Debug” menu in NetBeans Look at the HTML source Return error pages to the client – Plan ahead for missing or malformed data Use the log file – log("message") or log("message", Throwable) Separate the request and response data. – Request: see EchoServer at – Response: see WebClient at Make sure browser is not caching – Internet Explorer: use Shift + F5 – Firefox & Chrome: use Control + F5 Stop and restart the server

The Role of Form Data Example URL at online travel agent – – Names come from HTML author; values from end user Parsing form (query) data in traditional CGI – Read the data one way (QUERY_STRING) for GET requests, another way (standard input) for POST requests – Chop pairs at ampersands, then separate parameter names (left of the =) from parameter values (right of the =) – URL decode values (e.g., "%7E" becomes "~") Greatly simplified in servlets – Use request.getParameter in all cases. – Gives URL-decoded result

Creating Form Data: HTML Forms A Sample Form Using GET A Sample Form Using GET First name: Last name:

Sending POST Data A Sample Form Using POST A Sample Form Using POST <FORM ACTION=" METHOD="POST"> First name: Last name:

GET vs. POST Advantages of POST – URL is simpler – Data is hidden from people looking over your shoulder – Larger amounts of data can be sent – Can send special characters (e.g., in uploaded files) – Browsers will not cache results – Should always be used if the requests changes data on server Advantages of GET – Can bookmark results page – Browsers can cache results – Easier to test interactively

Reading Form Data In Servlets request.getParameter("name") – Returns URL-decoded value of first occurrence of name in query string – Works identically for GET and POST requests – Returns null if no such parameter is in query data request.getParameterValues("name") – Returns an array of the URL-decoded values of all occurrences of name in query string – Returns a one-element array if param not repeated – Returns null if no such parameter is in query

An HTML Form With Three Parameters First Parameter: Second Parameter: Third Parameter:

public class ThreeParams extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { … out.println(docType + " \n" + " "+title + " \n" + " \n" + " " + title + " \n" + " \n" + " param1 : " + request.getParameter("param1") + "\n" + " param2 : " + request.getParameter("param2") + "\n" + " param3 : " + request.getParameter("param3") + "\n" + " \n" + " "); }}

Reading All Parameters public class ShowParameters extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n";

String title = "Reading All Request Parameters"; out.println(docType + " \n" + " "+title + " \n"+ " \n" + " " + title + " \n" + " \n" + " Parameter Name Parameter Value(s)“ );

Enumeration paramNames = request.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement(); out.print(" " + paramName + "\n "); String[] paramValues = request.getParameterValues(paramName); if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0) out.println(" No Value "); else out.println(paramValue); } else { out.println(" ");

for(int i=0; i<paramValues.length; i++) { out.println(" " + paramValues[i] + “ ”); } out.println(" "); } out,.println(“ ”); } out.println(" \n ");

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }

Checking for Missing and Malformed Data Missing – Field missing in form getParameter returns null – Field blank when form submitted getParameter returns an empty string (or possibly a string with whitespace in it) – Must check for null before checking for empty string String param = request.getParameter("someName"); if ((param == null) || (param.trim().equals(""))) { doSomethingForMissingValues(...); } else { doSomethingWithParameter(param); }

Malformed – Value is a nonempty string in the wrong format Principles – Assume user data could be missing or in wrong format – Users should never see Java error messages Only error messages you create, aimed at end users

Use default values – Replace missing values with application-specific standard values

Redisplay the form – Show the form again, with missing values flagged – Previously-entered values should be preserved – Best option for implementing this: use framework like JSF or Struts

– Four options to implement this directly Have the same servlet present the form, process the data, and present the results. Have one servlet present the form; have a second servlet process the data and present the results. Have a JSP page present the form; have a servlet or JSP page process the data and present the results. Have a JSP page present the form, automatically filling in the fields with values obtained from a data object. Have a servlet or JSP page process the data and present the results.