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.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

J0 1 Marco Ronchetti - Basi di Dati Web e Distribuite – Laurea Specialitica in Informatica – Università di Trento.
Servlets. Applets Special Java programs (without a main) callable from HTML and executed in a graphic context. They can be executed by: a Java enabled.
J0 1 Marco Ronchetti - Servlets e JSP.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
1 Web Search Interfaces. 2 Web Search Interface Web search engines of course need a web-based interface. Search page must accept a query string and submit.
Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Apache Tomcat as a container for Servlets and JSP
Java Server Pages (JSP)
Java Servlets 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.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 24: Servlets Outline 24.1 Introduction 24.2 Servlet Overview and Architecture Interface.
Multivalued parameters Some type of parameters may have more than one value. This is the case for the checkbox. What IDEs do you use? NetBeans Eclipse.
Server Side Programming Common Gateway Interface (CGI): Scripts generate Web pages or other files dynamically by processing form data and returning documents.
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.
CS320 Web and Internet Programming Handling HTTP Requests Chengyu Sun California State University, Los Angeles.
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.
Servlets Replace Common Gateway Interface Scripts Extend Server Functionality Modules (software components) Like applets to browsers No GUI.
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
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.
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.
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.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
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)
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.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
CS320 Web and Internet Programming Handling HTTP Requests Chengyu Sun California State University, Los Angeles.
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.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
Java Servlet API CGI / HTTP Concepts Java Servlet API.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
L.MARIA MICHAEL VISUWASAM UNIT-4
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.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
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.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
How CGI and Java Servlets are Run By David Stein 14 November 2006.
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.
Java Servlets References: Karen Anewalt, Mary Washington College.
Distributed Web Systems Java Servlets Lecturer Department University.
Introduction to Servlets
Servlets.
Servlets.
JDBC & Servlet CSE 4504/6504 Lab.
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.
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
COP 4610L: Applications in the Enterprise Spring 2005
Servlets.
Presentation transcript:

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 form and applying the business logic used to update a company's order database. Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface. For a full tutorial, see

Applets vs. Servlets AppletServlet Runs on:ClientServer Has a main:NO Extends:java.applet.Appletjavax.servlet.http. HttpServlet GraphicsSINO Hearth:handleEvent()service()

Servlet Lifecycle init() destroy() service(HttpServletRequest r, HttpServletResponse p) Called only the first time a servlet is loaded into memory! doGet() doPost() doXXX() Used only when memory is freed If the Servlet implements SingleThreadModel there will be no mutithreading

Get vs Post What are "Get" and "Post"? Get and Post are methods used to send data to the server: With the Get method, the browser appends the data onto the URL. With the Post method, the data is sent as "standard input. Why Do I Care? It's important for you to know which method you are using. The Get method is the default, so if you do not specify a method, the Get method will be used automatically. The Get method has several disadvantages: There is a limit on the number of characters which can be sent to the server, generally around characters. Your user will see the "messy codes" when the data is sent.

service() This code is part of the class HttpServlet protected void service (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod (); if (method.equals ("GET")) { longifModifiedSince; longlastModified; longnow; ifModifiedSince = req.getDateHeader ("If-Modified-Since"); lastModified = getLastModified (req); maybeSetLastModified (resp, lastModified); if (ifModifiedSince == -1 || lastModified == -1) doGet (req, resp); else { now = System.currentTimeMillis (); if (now < ifModifiedSince || ifModifiedSince < lastModified) doGet (req, resp); else resp.sendError (HttpServletResponse.SC_NOT_MODIFIED); }

service() This code is part of the class HttpServlet protected void service (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod (); if (method.equals ("GET")) { longifModifiedSince; longlastModified; longnow; ifModifiedSince = req.getDateHeader ("If-Modified-Since"); lastModified = getLastModified (req); maybeSetLastModified (resp, lastModified); if (ifModifiedSince == -1 || lastModified == -1) doGet (req, resp); else { now = System.currentTimeMillis (); if (now < ifModifiedSince || ifModifiedSince < lastModified) doGet (req, resp); else resp.sendError (HttpServletResponse.SC_NOT_MODIFIED); }

service() } else if (method.equals ("HEAD")) { longlastModified; lastModified = getLastModified (req); maybeSetLastModified (resp, lastModified); doHead (req, resp); } else if (method.equals ("POST")) { doPost (req, resp); } else if (method.equals ("PUT")) { doPut(req, resp); } else if (method.equals ("DELETE")) { doDelete(req, resp); } else if (method.equals ("OPTIONS")) { doOptions(req,resp); } else if (method.equals ("TRACE")) { doTrace(req,resp); } else { resp.sendError (HttpServletResponse.SC_NOT_IMPLEMENTED, "Method '" + method + "' is not defined in RFC 2068"); }

A taste of servlet programming-1 public class SimpleServlet extends HttpServlet { /** Handle the HTTP GET method by building a simple web page. */ public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out; String title = "Simple Servlet Output";

A taste of servlet programming-2 // set content type and other response header fields first response.setContentType("text/html"); // then write the data of the response out = response.getWriter(); out.println(" "); out.println(title); out.println(" "); out.println(" " + title + " "); out.println(" This is output from SimpleServlet."); out.println(" "); out.close(); }

Forms (a quick overview) See also:

Forms Give to the user the possibility to di send information to the Web server The FORM tag defines a form and has the following attributes: ACTION identifies the processing engine ENCTYPE specificies the MIME type used to pass data to the server (Es. Text/html) FORM contains the sub-tag: several tags for collecting data An INPUT tag must be of type SUBMIT for sending the data An INPUT can be of tye RESET to cancel all the gathered data

Form - input Scrivi il tuo nome Sends a url of type

Form – input type=radio Fai la tua scelta: <Input type="radio" name="tipo" value="auto" checked>Auto <Input type="radio" name="tipo" value="bus">Bus <Input type="radio" name="tipo" value="camion">Camion <Input type="radio" name="colore" value="rosso">Rosso <Input type="radio" name="colore" value="argento" checked>Argento

Form – input type=checkbox - select Fai la tua scelta: <Input type="checkbox" name="tipo" value="auto" checked>Auto <Input type="checkbox" name="tipo" value="bus">Bus <Input type="checkbox" name="tipo" value="camion">Camion Rosso Argento

Form – textarea Scrivi i tuoi commenti: <Textarea name="commenti" rows="4" columns="14"> Spiega in questo spazio la tua opinione Notare gli spazi

Example

Esempio: ShowParameters package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ShowParameters extends HttpServlet { public void doGet(HttpServletRequest request HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading All Request Parameters"; out.println (" " +title+ " + " \n" + " " + title + " \n" + " \n" + " Parameter Name Parameter Value(s)");

Esempio: ShowParameters 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[i]); } out.println(" "); } out.println(" \n "); }

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

Esempio: ShowParameters A Sample FORM using POST A Sample FORM using POST Item Number: Quantity: Price Each: First Name: Last Name: Middle Initial: Shipping Address:

Esempio: ShowParameters Credit Card: Visa <INPUT TYPE="RADIO" NAME="cardType" VALUE="Master Card">Master Card <INPUT TYPE="RADIO" NAME="cardType" VALUE="Amex">American Express Discover <INPUT TYPE="RADIO" NAME="cardType" VALUE="Java SmartCard">Java SmartCard Credit Card Number: Repeat Credit Card Number:

WebApps (Tomcat configuration)

Static pages To let Tomcat serve static pages, we must define a Web Application. That is, in the Tomcat Document Root (by default $CATALINA_HOME/webapps/) we must create a folder named after our Web Application (e.g. myApp). In that myApp folder, we MUST create a WEB-INF folder (that can be empy). In the myApp folder we can then depost the static html files. On our Tomcat server, the URL for the hello.html file becomes: To actually see the webapp, we might have to restart Tomcat myApp hello.html WEB-INF webapps web.xml

Static pages A web.xml file MUST be provided: <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN " myApp hello.html WEB-INF webapps web.xml

JSP pages To let Tomcat serve JSP pages, we follow the same procedure that we described for static pages. In the myApp folder we can depost the JSP files. On our Tomcat server, the URL for the hello.jsp file becomes: The WEB-INF directory is still empty. To actually see the webapp, you might have to restart Tomcat (depending on the version you have) The same web.xml file as in the static case must be provided. myApp hello.jsp WEB-INF webapps web.xml

Servlets To let Tomcat serve servlet, we need add some info. The compiled servlets (.class) must be stored in a classes directory in WEB-INF. Moreover, the web.xml file MUST contain at least: <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" " invoker /magic/* The magic word is the servlet activation keyword (you can of course customize this word). To execute the servlet called MyServlet.class, the URL will be:

Servlets The web.xml file CAN contain many additional info. For instance, it can contain a section defining an alias name for the servlet: … pippo Servlet1 … In such case, the servlet called MyServlet.class Can be activated ALSO by the URL: myApp web.xml WEB-INF webapps classes MyServlet.class

Accessibility

See for accessibility when using forms for accessibility in general. cc.pdf What is Section 508? The legislation referred to as "Section 508" is actually an amendment to the Workforce Rehabilitation Act of The amendment was signed into law by President Clinton on August 7, Section 508 requires that electronic and information technology that is developed or purchased by the Federal Government is accessible by people with disabilities.

Accessibility in Italy Testo della legge: - Vedi anche: - Commissioni_e_Gruppi_di_Lavoro_interministeriali/Accessibilit%C3%A0/ Rapporto 2004 della commissioneCommissione interministeriale permanente per limpiego delle ICT a favore delle categorie deboli o svantaggiate - Legge Stanca 9 gennaio 2004, n. 4 Disposizioni per favorire l'accesso dei soggetti disabili agli strumenti informatici