Web-based Client-Server Application Server-side programming - Servlet 1.

Slides:



Advertisements
Similar presentations
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
Advertisements

1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
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
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 CS-328 Dick Steflik. What is a servlet A Java application run on a thread of the webserver in response to an HTTP GET or POST request. The servlet.
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.
Java Server and Servlet CS616 Team 9 Kim Doyle, Susan Kroha, Arunima Palchowdhury, Wei Xu.
Definition Servlet: Servlet is a java class which extends the functionality of web server by dynamically generating web pages. Web server: It is a server.
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.
Michael Brockway Application Integration Servlets l Introduction & Overview l HTTP Servlets l HTTP get Requests l HTTP post Requests l Multi-tier Applications.
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.
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.
1 Chapter 2 The Web Tier  Web Applications and Web ContainersWeb Applications and Web Containers  Dynamic Content CreationDynamic Content Creation 
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
1 Servers A server is a computer that responds to requests from a client – Typical requests: provide a web page, upload or download a file, send .
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
Copyright, 1996 © Dale Carnegie & Associates, Inc. Presented by Hsiuling Hsieh Christine Liu.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
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.
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.
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.
Introduction to Servlets. Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop.
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)
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
K. K. Wagh Polytechnic, Nashik
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
SERVLET THETOPPERSWAY.COM
How CGI and Java Servlets are Run By David Stein 14 November 2006.
1 Web Programming with Servlets & JSPs WEB APPLICATIONS – AN OVERVIEW.
Java Servlets References: Karen Anewalt, Mary Washington College.
CS122B: Projects in Databases and Web Applications Spring 2017
Introduction to Servlets
CS122B: Projects in Databases and Web Applications Winter 2017
Servlets.
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Web Programming Course
Pre-assessment Questions
Servlet.
Chapter 26 Servlets.
CS122B: Projects in Databases and Web Applications Winter 2018
Servlets.
CS122B: Projects in Databases and Web Applications Spring 2018
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
Servlets Servlets are modules that extend the functionality of a “java-enabled” web-server They normally generate HTML code and web content dynamically.
CS122B: Projects in Databases and Web Applications Winter 2019
Presentation transcript:

Web-based Client-Server Application Server-side programming - Servlet 1

SERVLET

Where are we? 1. Intro to Java, Course 2. Java lang. basics 3. Arrays 5. Encapsulation 4. Object Classes 7. Inheritance 8. Polymorphism 10. JDBC 6. Exception Handling Introduction Object-oriented design Advanced topics NewbieProgrammersDevelopersProfessionalsDesigners JAVA 9. Abstract classes and Interfaces 13. Servlets 14. JSP Server-side coding 12. Networking 11.Streams

Concepts Features javax.servlet.Servlet javax.servlet.http.HttpServlet Example: get and send a page to client Example: post Image generating Session tracking –Cookie, HttpSession, URL-rewriting Practical examples Outline

Today’s buzzwords Applets –Java programs capable of running within a web browser Servlets –Java code running on server side Session tracking –Keeping context information during a session of browsing related web pages

What is java servlet ? A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol. Servlet is an opposite of applet as a server-side applet. Applet is an application running on client while servlet is running on server.

What is Java Servlets? Servlet –module run inside request/response-oriented server Browser Java-enabled Web Server Servlet Database HTML form Server Servlet = Browser Applet Servlets are to Servers what Applets are to Browsers Substitute for CGI scripts easier to write and fast to run Not part of the core Java Framework

Example use of servlet Processing data POST over HTTPs using HTML form as purchase order or credit card data Allowing collaborative between people such as on-line conferencing Many servlet can chain together among Web servers to reduce load on one Web server.

Why Use Servlets ? One of the reasons that Java became popular is Applets. –but there are problems with Applets Browser compatibility Download bandwidth Server-side Java –the code is executed on the server side not the client side –a dynamically loaded module that services requests from a Web server

Servlets (contd.) –vs. Common Gateway Interface (CGI) create new process for each request –most platform independent CGI language - Perl start a new instance of interpreter for every request CGI runs in a completely separate process from the Web server –vs. Server-Side JavaScript only available on certain web servers –vs. Active Server Pages (ASP) only available on certain web servers

CGI Communication (traditional approach) 1. Web browser requset a response from CGI program. 2. Web server create CGI profile file that was contain information about CGI variable, server and CGI output file. 3. Web server starts CGI application and wait for its termination. 4. CGI program runs and writes the result to CGI output file and then terminates. 5. Web server reads from CGI output file and send back to Web browser.

Servlet Communication Web browser request servlet by specified URL as me Web server call service() method in ServletLoader class which will dynamically load a specified servlet name from a special directory call servlet.

Servlet vs CGI Servlet run as light weight thread in process. CGI run as heavy weight process.

Advantage of servlet over CGI PlatForm Independence Servlets can run on any platform. PERL also can be moved from platform to platform while CGI such as C are not portable. Performance Servlets only needs be loaded once, while CGI programs needs to be load for every request so that servlet should performs faster than CGI Security While CGI can do many insecure things, java provided security in language level.

Three Tier Applications.

Java Servlet Development Kit installation

Requirement for running java servlet Java Servlet API A set of java classes. This is a Java Servlet Development Kit(JSDK) that can be download from JSDK allows most standard Web server such as Netscape servers, IIS, Apache and others to load servlets Java-enabled Web server There are many web server that support java virtual machine such as Java Web server by SUN, WebSite Pro V2.0 by O’Reilly and the latest version of World Wide Web Consortium’s free jigsaw Web Server.

Java Web Server (JWS) Java Web Server Servlet request response

Servlet Lifecycle Server loads Servlets - run init method Servlets Accept Request from Clients and return Data back - run service method Server removes Servlets - run destroy method No Concurrency Issue Server runs init only once, not per request service must be thread-safe - multiple service method at a time if that is impossible, servlet must implement SingleThreadModel interface Server reloads Servlets - run init method destroy must be thread-safe - when server runs destroy, other threads might be accessing shared resources

A Typical Servlet Lifecycle from Servlet Essential by Stefan Zeiger

Servlet class Example Interface Servlet Define the standard way in which a network server will access a servlet. All servlet classes must (fundamentally) implement this interface. GenericServlet Defines a generic, protocol- independent servlet. For servlet that is not intended to use with Web server. To write an HTTP servlet for use on the Web, extend HttpServlet insteadHttpServlet For Servlet that is intended to use with Web server. This class adds HTTP- specific to work with a Web server context

Servlet Structure All servlet classes and interfaces that form the API are found in the javax.servlet package. All servlets, no matter what type of server they are destined to be used with, implement the javax.servlet.Servlet interface. This interface defines the basic functionality that a servlet must possess

ServletConfig When the servlet first starts up, the system can pass specific initialization information to the servlet for possible processing via the init(...) method. Parameters are passed in using a key/value pairing, and two methods are provided to access this data: getInitParameter(...) and getInitParameterName().

ServletContext allows the servlet to interrogate the server about various pieces of environmental data Example : –Many servers, particularly web servers, refer to files and resources as virtual files. –However, this makes opening up files difficult, as the virtual file or alias needs to be mapped onto a real file. –The ServletContext interface, for example, provides a method to convert an alias and real path file names.

ServletContext

GenericServlet The base class on which the majority of servlets are based is the GenericServlet class.

Interface Servlet class void init(ServletConfig) Initialized the servlet when it is loaded into server (system). abstract void service(ServletRequest, ServletResponse) This is an abstract class so that it must be implemented by a subclass of GenericServlet class. A method that the servlet processes each client request destroy() This method is called when the server remove a servlet from memory.

ServletRequest

ServletRequest If, on the other hand, data is coming from a non-HTTP client, then the data may be coming in as a stream. The ServletInputStream can be used to read this stream. Additional information about the client that may be useful is the home network address from which it is sending. This information can be made available through the getRemoteAddr() and getRemoteHost() methods.

ServletResponse The most important method of this interface is the getOutputStream() method. This returns the ServletOutputStream, which can be used to provide any other preferred output stream class from the java.io package.

GenericServlet : Example

GenericServlet

Web-Based Servlet The developers at Java recognized the fact that the majority of servlets would be employed in the field of the Internet, with particular emphasis on the world wide web. The servlet API offers you a direct alternative to using CGI and Microsoft's Active Server Pages (ASP) to implement server-side solutions. To make coding servlets for the web relatively easy, a special HttpServlet class was developed. This provided methods to access the more common header fields found in the HTTP protocol.

HttpServlet class void doGet(HttpServletRequest, HttpServletResponse) This method handle HTTP GET requests. void doPost(HttpServletRequest, HttpServletResponse) This method handle HTTP POST requests. The Form parameter are read via HttpServletRequest parameter. void service(HttpServletRequest, HttpServletResponse) This method can handle both GET and POST method. Normally, service() method used to overide one or both of the previous method void service(servletRequest,ServeletResponse) This method overides service() method of GenericServlet class

HttpServlet The HttpServlet, based on the GenericServlet class. It provides an improved interface for dealing with HTTP-specific client requests. In addition to the service(...) method that is used to deal with all requests, seven additional methods exist for processing requests; doGet(...), doPost(...), doHead(...), doPut(...), doTrace(...), doOptions(...), and doDelete(...).

Servlet Architecture Overview - HTTP servlets IS-A Servlet interface Servlet Client GET POST Servlet doGet(ServletRequest req, ServletResponse res); ServletRequest ServletResponse ServletResponnse ServletRequest doPost(ServletRequest req, ServletResponse res); parameters, protocol, remote host, ServerInputStream(binary data etc..) mime type to reply,reply data, ServletOutputStream

HttpServlet Interface

ServletRequest Interface This interface return information about parameter sent with the request. int getContentLength() String getContentType() String getProtocol() String getScheme() String getServerName() int getServerPort() String getRemoteAddr()

HttpServletRequest :

ServletRequest Interface(continued) String getRemoteHost() String getRealPath(String path) ServletInputStream getInputStream() String getParameter(String name) String[] getParameterValues(String name) Enumeration getParameterNames() Object getAttribute(String name)

ServletResponse Interface This interface defined method for sending information back to Web browser. void setContentLength(int len) void setContentType(String type) ServletOutputStream getOutputStream()

HttpServletRequest Interface The method of HttpServletRequest interface inherits the method in ServletRequest interface. GET, POST, and HEAD in HTTP are also supported.

Servlets (contd.) –HttpServletRequest information sent from the client –getParameter() –getParameterValues() –getParameterNames() will discuss in detail later in FormPost –HttpServletResponse information sent to the client –getWriter() return an instance of PrintWriter you can use print and println with a PrintWriter see SimpleServlet

HttpServletResponse Interface(continued) boolean containHeader(String name) void setStatus(int statusCode, String statusMessage) void sendError(int statusCode, String Message) void sendError(int statusCode) void setDateHeader(String name, long date) void sendRedirect(String location)

HttpServletResponse Interface String getMethod() String getServletPath() String getPathInfo() String getPathTranslated() String getQueryString() String getRemoteUser() String getAuthType String getHeader(String name) String getIntHeader(String name) long getDateHeader() Enumeration getHeaderNames()

Writing the Servlet Implement the javax.servlet.Servlet interface –HTTP: extends javax.servlet.http.HttpServlet class public class SurveyServlet extends HttpServlet { /* typical servlet code, with no threading concerns * in the service method. */... }

Interacting with Clients(1) - HTTP servlets doGet doPost doPut doDelete Client Get Post Put Delete u HttpServletRequest - argument & HTTP header data String[] getParameterValues(String name) - get user parameter For GET method - String getQueryString() For POST, PUT, DELETE method - BufferedReader getReader() - text data - ServletInputStream getInputStream() - binary data methods

Interacting with Clients(2) - HTTP servlets HttpServletResponse - return the response data to the user –PrintWriter getWriter() - text data –ServletOutputStream getOutputStream() - binary data –Before accessing the Writer or OutputStream, HTTP header data should be set

Example of an HTTP Servlet - GET/HEAD methods public class SimpleServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { // set header field first res.setContentType("text/html"); // then get the writer and write the response data PrintWriter out = res.getWriter(); out.println (" SimpleServlet " ); out.println (" SimpleServlet Output " ); out.println (" " ); out.close(); } public String getServletInfo() { return " A simple servlet "; } }

Example (2) use of HttpServlet

Accessing web-based servlets Assume the servlets' class file has been placed in the server's servlets directory. The servlet can be called by including /servlet/ before the servlet name in the URL. For example, if you set the class name of the sample servlet to TestServlet, then it could be accessed using /servlet/TestServlet

Apache-Tomcat Directory Structure

Starting Tomcat

database example : db.html DB Example Nama WebSite Address

HTML Form Example

Saving data to db – inserttodb servlet /* Servlet to JDBC - save into database */ import java.io.*; import java.util.Enumeration; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.net.*; public class inserttodb extends HttpServlet{ static final String dbURI = "jdbc:mysql:/// db"; String str = "INSERT INTO list VALUES(?, ?, ?)"; Connection theConnection = null; private ServletConfig config; public void init(ServletConfig config) throws ServletException{ this.config=config; }

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String nameS = request.getParameter("name"); String S = request.getParameter(" "); String websiteS = request.getParameter("website"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(" List. "); out.println(" "); out.println(" Save these data to database. "); out.println(" ");

try { // Load database driver try { Class.forName("org.gjt.mm.mysql.Driver"); } catch (ClassNotFoundException cnfe){ System.out.println("ClassNot found error"); }; // Create a Connection to db Data source try { theConnection = DriverManager.getConnection(dbURI); //Connect to db Data source } catch (SQLException sqle) { System.out.println(sqle); }; // prepare statement for inserting data into table try { PreparedStatement theStatement=theConnection.prepareStatement(str); //Set parameters for INSERT statement and execute it theStatement.setString(1, nameS); theStatement.setString(2, S); theStatement.setString(3, websiteS); theStatement.executeUpdate(); } catch (SQLException sqle) { System.out.println(sqle); }; theConnection.close(); //Close database Connection } catch(Exception e){ out.println(e.getMessage());//Print trapped error. }

Saving to database and use a button to retrieve data back

Retrieve List from db

Retrieve data from db database /* Servlet to retrieve data from database using JDBC */ import java.io.*; import java.util.Enumeration; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; import java.net.*; public class dbServlet extends HttpServlet{ static final String dbURI = "jdbc:mysql:/// db"; Connection theConnection; private ServletConfig config; public void init(ServletConfig config) throws ServletException{ this.config=config; }

Continued public void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpSession session = req.getSession(true); res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println(" List. "); out.println(" "); out.println(" List of addresses. "); out.println(" "); out.println(" "); out.println(" Name "); out.println(" "); out.println(" Website ");

try{ Class.forName("org.gjt.mm.mysql.Driver");//Loading mysql Driver theConnection = DriverManager.getConnection(dbURI); //Connect to db Statement theStatement=theConnection.createStatement(); ResultSet theResult=theStatement.executeQuery("select * from list"); while(theResult.next()) { //Fetch all the records and print in table out.println(); out.println(" "); out.println(" " + theResult.getString(1) + " "); out.println(" " + theResult.getString(2) + " "); String s=theResult.getString(3); out.println(" " + s + " "); out.println(" "); } theResult.close();//Close the result set theStatement.close();//Close statement theConnection.close(); //Close database Connection }catch(Exception e){ out.println(e.getMessage());//Print trapped error. } out.println(" "); out.println(" "); } public void destroy(){ }