Servlets CEN 4010 11/28/2018 Copyright 2001 Ege Consulting, Inc.

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.
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 Stoney Jackson
Servlets and a little bit of Web Services Russell Beale.
An introduction to Java Servlet Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
Java database Programming JDBC Trademarked name of a Java API that supports Java programs that access relational databases Stand for Java DataBase Connectivity.
Servlet Session Tracking II Session API All material and examples are from
Chapter 4 Servlets Concept of Servlets (What, Why, and How) Servlet API Third-party tools to run servlets Examples of Using Servlets HTML tag with GET.
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.
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.
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
Servlets, Sessions, and Cookies Lecture 8 cs193i – Internet Technologies Summer 2004 Kelly Shaw, Stanford University.
Java Servlet Technology. Introduction Servlets are Java programs that run on a Web server, handle HTTP requests and build Web pages Servlet specification.
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.
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
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
COMP 321 Week 7. Overview HTML and HTTP Basics Dynamic Web Content ServletsMVC Tomcat in Eclipse Demonstration Lab 7-1 Introduction.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
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.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
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.
Li Tak Sing COMPS311F. A web page that counts the number of times that you have visited the page. You can try the page at:
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.
Slides © Marty Hall, book © Sun Microsystems Press 1 Session Tracking Core Servlets & JSP book: More.
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
Session Tracking Parts of this presentation was provided by SSE.
Java Web Applications. WAR Web Archive Introduced with servlet 2.2 specification Portable deployment mechanism for web applications Defines directory.
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.
Introduction to Servlets
CS3220 Web and Internet Programming Introduction to Java Servlets
Servlet Fudamentals.
Java Servlets By: Tejashri Udavant..
Net-centric Computing
JDBC & Servlet CSE 4504/6504 Lab.
Course Outcomes of Advanced Java Programming AJP (17625, C603)
Session Tracking in Servlets
Sessions.
Java Servlets II: Session Tracking
Servlet.
Chapter 26 Servlets.
Servlets and Java Server Pages
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Cookies Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when later visiting the.
Web Search Interfaces.
Java Servlets and JSP.
Web Search Interfaces by Ray Mooney
CS3220 Web and Internet Programming Introduction to Java Servlets
Servlets.
Java Servlets Servlet Overview Servlets and HTML Forms Servlet Basics
Presentation transcript:

Servlets CEN 4010 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Servlets overview Servlet Technology Handling requests Session tracking Handling Cookies JDBC Servlet 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Webserver web site files html files: text, multi-media and links Common Gateway Interface (CGI): cgi scripts: sh, csh, Perl, … Servlets: Java program that runs on webserver JavaServer pages (JSP): Contains html and Java Compiled into a servlet and run on webserver 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Servlet Supports request/response model Different types of servlets client send request server responds (with html page) Different types of servlets GenericServlet not protocol specific HttpServlet Serves http requests 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Servlet tasks process html forms middle-tier processing connect to sources behind firewall (e.g. DB) maintain session information between requests serve as concentration point for multiple clients 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Servlet runs on webserver requested via URL by client requires special webserver Tomcat, IBM application server, JRun, Oracle … can start with webserver permanent: if startup effort is high can be started on client request temporary: if rarely used servlet is unaware of when it was started 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Basic modes of operation Multi threaded Single servlet instance runs in many threads Servlet fields shared Must consider field contention Single threaded Multiple instances, each in one thread Servlet fields are not shared 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Servlet interfaces and classes Java Servlet packages javax.servlet javax.servlet.http Part of J2EE to compile include into CLASSPATH (tomcat)... common\lib\servlet-api.jar 11/28/2018 Copyright 2001 Ege Consulting, Inc.

HttpServlet service method invoked for “get” and “post” method in html form 11/28/2018 Copyright 2001 Ege Consulting, Inc.

HttpServlet class 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Servlet example: HelloWorld.java package mypackage; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(“<html><head><title>Hello</title></head>”); out.println(“<body>”); out.println("Hello World“); out.println(“</body></html>”); } 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Make the servlet known as web application: web.xml <display-name>HelloWorld example</display-name> <description>Welcome to HelloWorld</description> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>mypackage.HelloWorld</servlet-class> </servlet> <servlet-mapping> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app> 11/28/2018 Copyright 2001 Ege Consulting, Inc.

html example: hello.html <head> <title>Hello World Servlet Example</title> <body> <form action=“http://localhost:8080/HelloExample/hello” method=“get”> <input type=“submit”> </form> </body> </html> 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Servlet deployment on Tomcat Create directory ...\webapps\HelloExample Copy hello.html into this directory as index.html Create subdirectory WEB-INF Create subdirectory WEB-INF\classes Compile HelloWorld.java to WEB-INF\classes\mypackage\HelloWorld.class Copy web.xml into directory: WEB-INF Open “http://localhost:8080/HelloExample” 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Process Form parameters html form defines fields with name type value(s) received by servlet via request parameter HttpServletRequest class defines helper methods 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Helper methods getParameter(“name”) getParameterValues(“name”) Returns string (maybe empty) or null if parameter does not exist getParameterValues(“name”) Returns array of strings getParameterNames() Returns enumeration of parameter names 11/28/2018 Copyright 2001 Ege Consulting, Inc.

html example <html> <body> <head> <title>Request Parameters Example</title> </head> <h3>Request Parameters Example</h3> Please enter <p><form action="params" method=POST> First Name: <input type=text size=20 name=firstname> <br> Last Name: <input type=text size=20 name=lastname> <br> <input type=submit> </form> </body> </html> 11/28/2018 Copyright 2001 Ege Consulting, Inc.

doPost method String first = request.getParameter("firstname"); String last = request.getParameter("lastname"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>Answer</title></head>"); out.println("<body>Welcome " + first + " " + last); out.println("</body></html>"); 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Keep track of session http is a stateless protocol but there is need to maintain session information username, password shopping cart … possible: use hidden field(s) better: HttpSession 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Keep track of session session can remember values for attributes across servlet invocations methods: session = request.getSession(true); session.setAttribute(“name”, object); session.getAttribute(“name”); 11/28/2018 Copyright 2001 Ege Consulting, Inc.

getSession session = request.getSession(true); retrieves current session from request “true” parameter causes new session to be created if it does not exist session remains alive until: it times out (reaches time maximum) explicit cancellation 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Attributes getAttribute(“name”) setAttribute(“name”, value) value can be any object removeAttribute(“name”) getAttributeNames() 11/28/2018 Copyright 2001 Ege Consulting, Inc.

HttpSession methods getID() isNew() getCreationTime() getLastAccessedTime() invalidate() setMaxInactiveInterval() getMaxInactiveInterval() 11/28/2018 Copyright 2001 Ege Consulting, Inc.

SessionServlet: doPost (1/3) HttpSession session = request.getSession(true); String heading; if (session.isNew()) { heading = "Welcome, Newcomer"; } else { heading = "Hello Again"; } 11/28/2018 Copyright 2001 Ege Consulting, Inc.

SessionServlet: doPost (2/3) Integer accessCount = (Integer)session.getAttribute("accessCount"); if (accessCount != null) { accessCount = new Integer(accessCount.intValue() + 1); } else { accessCount = new Integer(0); } session.setAttribute("accessCount", accessCount); 11/28/2018 Copyright 2001 Ege Consulting, Inc.

SessionServlet: doPost (3/3) response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>Answer</title></head>"); out.println("<body> " + heading + "<br>"); out.println("Number of previous accesses " + accessCount ); out.println("</body></html>"); 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Handle Cookies allow to store information in the browser can be retrieved by servlet 2 types temporary cookies lasts as long as the browser instance permanent cookies must have expiration date can be deleted Note: browsers can disable cookies 11/28/2018 Copyright 2001 Ege Consulting, Inc.

To establish a Cookie create instance of class Cookie Cookie mine = new Cookie(“name”, “value”); permanent has max age mine.setMaxAge(seconds); can have domain and path mine.setDomain(“.aul.fiu.edu”); mine.setPath(“/catalog”); 11/28/2018 Copyright 2001 Ege Consulting, Inc.

To access Cookies through request parameter find your cookie Cookie all[] = request.getCookies(); find your cookie for (int i=0; i<all.length; i++) { out.println(“Cookie name: “ + all[i].getName()); out.println(“ value: “ + all[i].getValue()); } 11/28/2018 Copyright 2001 Ege Consulting, Inc.

To save Cookie through response header Example: response.addCookie(singleCookie); Example: Cookie mine = new Cookie(“user”, “ege”); mine.setMaxAge(60 * 60 * 24 * 365); response.addCookie(mine); 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Access database servlet may access database using JDBC load driver get connection formulate statement execute statement process result set 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Example: database access Class.forName("com.sybase.jdbc.SybDriver"); conn = DriverManager.getConnection("jdbc:sybase:Tds:ocelot.aul.fiu.edu:7100", “student", “student"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>Customers</title></head><body>"); String s1 = "select * from Customers;"; Statement s = conn.createStatement(); ResultSet result = s.executeQuery(s1); out.println("<table border=1><tr><th>ID<th>name<th>city<th>street</tr>"); while (result.next()) { out.println("<tr><td>" + result.getInt(1)); out.println("<td>" + result.getString(2)); out.println("<td>" + result.getString(3)); out.println("<td>" + result.getString(4) + "</tr>"); } out.println("</table></body></html>"); 11/28/2018 Copyright 2001 Ege Consulting, Inc.

Performance considerations new connection is created for every request to servlet other choices place connection into session 11/28/2018 Copyright 2001 Ege Consulting, Inc.