J2EE Servlets Ch. 10 (Architecture) Ch. 12 (21 Days)

Slides:



Advertisements
Similar presentations
6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in 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.
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.
An introduction to Java Servlet Programming
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
June 1, 2000 Object Oriented Programming in Java (95-707) Advanced Topics 1 Lecture 10 Object Oriented Programming in Java Advanced Topics Servlets.
Introduction to Servlet & JSP
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.
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.
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.
Objectives Java Servlet Web Components
CSC 2720 Building Web Applications
111 Java Servlets Dynamic Web Pages (Program Files) Servlets versus Java Server Pages Implementing Servlets Example: F15 Warranty Registration Tomcat Configuration.
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,
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
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.
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.
@2008 Huynh Ngoc Tin Chapter #2 JAVA SERVLET PRGRAMMING.
Java Servlets and Java Server Pages Norman White Stern School of Business.
JSP Pages. What and Why of JSP? JSP = Java code imbedded in HTML or XML –Static portion of the page is HTML –Dynamic portion is Java Easy way to develop.
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.
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.
Introduction to Servlets. Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop.
Introduction to Servlets Allen Day. Notes This is a training NOT a presentation Please ask questions Prerequisites.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
©SoftMoore ConsultingSlide 1 Filters. Filters can be used in a web application to intercept, examine, and possibly transform requests or responses associated.
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.
J2EE T ECHNOLOGIES These are the technologies required to build large scale distributed applications, can be divided into – Component Technologies eg.
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
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.
Introduction To HTML Dr. Magdi AMER. HTML elements.
Java Programming: Advanced Topics 1 Building Web Applications Chapter 13.
1 Servlets – Part 2 Representation and Management of Data on the Web.
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.
1 Lecture 8 George Koutsogiannakis/Summer 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
1 Web Programming with Servlets & JSPs WEB APPLICATIONS – AN OVERVIEW.
Introduction to Servlets
Java Servlets By: Tejashri Udavant..
Java Servlets.
Pre assessment Questions
Servlets Hits Counter 20-Jul-18.
Session Tracking in Servlets
Pre-assessment Questions
Sessions.
Chapter 26 Servlets.
Servlets and Java Server Pages
Servlets & JSP.
Web Search Interfaces.
CS3220 Web and Internet Programming Introduction to Java Servlets
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.
Pre-assessment Questions
Presentation transcript:

J2EE Servlets Ch. 10 (Architecture) Ch. 12 (21 Days)

History of Interactive Web  Applets Long download times Long download times Code on client machines (maintenance) Code on client machines (maintenance)  CGI Custom code to interact with web server Custom code to interact with web server Security hole Security hole Resource hog for large sites Resource hog for large sites  Java Servlets Standard, easy interface to web server Standard, easy interface to web server Security/authentication Security/authentication Implements sessions Implements sessions

History (cont.)  Early use of Servlets Simple, easy to use for web applications Simple, easy to use for web applications MVC all implemented in one big servlet MVC all implemented in one big servlet Very complexVery complex Difficult to maintainDifficult to maintain Not scalableNot scalable  Current state of Servlet use Smaller is better. Smaller is better. Used only for: Used only for: Gathering and validating data input from the userGathering and validating data input from the user Coordinating outputCoordinating output Minimal business logicMinimal business logic Web page forwardingWeb page forwarding

Servlet Features  Tailored to interact with Web Server  Server and platform independent  Efficient and scalable  Container provides additional functionality (i.e., authentication, cookies, etc.)

Interacting with HTML Forms  Get – Request information from web server Simple Simplehttp://  Post – Send data to the server Submit button, etc. Submit button, etc. Data is sent in body of message Data is sent in body of message Safer than Get Safer than Get

HTML Forms (Cont.)  Put – Place a file on the server  Delete – Remove a web page from server

Servlet Class Diagram Class Diagram

Servlet Life Cycle Class Diagram State: Resident Processing Request START END init() doGet(), doPost, … destroy()

Servlet Sequence Diagram Fig

Model 1 - Servlets only Model/View/Control Servlet WebServer Data base doGet/doPost webpage Generate HTML submit Data

Servlets in the Enterprise Model View/Control EJB Entity Bean WebServer Servlet Input Control Output doGet/doPost webpage submit Data Performance and Flexibility Issues

publc class HtmlPage extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String name = request.getParameter(“name”); String telephone = request.getParameter(“tel”); response.setContentType(“text/html”); …. Business logic …. PrintWriter out = response.getWriter(): out.println(“ ”); out.println(“ First Servlet ”); out.println(“ ”); out.println(“ Hello “ + name + “, Telephone “ + telephone + “ ”); out.println(“ ”); out.println(“ ”); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { doGet(request, response); } } Example Servlet Get value of form parameters Sent output to web browser

Model 2 Architecture ModelView Data Access Objecs > WebServer Servlet JSP page input output doGet/doPost webpage Control Business Methods > Data submit >

JSPServlet Web Development Life Cycle Model 2 Architecture Get request Parameters Determine and call business function Determine next view Build view

Web Development Life Cycle protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); try { InitialContext context = new InitialContext(); BusinessRulesRemote businessRules = (BusinessRulesRemote) context.lookup(BusinessRules.REMOTE_JNDI_NAME); Long personId = businessRules.login(username,password); } catch (Exception e) { e.printStackTrace(); } HttpSession session = request.getSession(); session.setAttribute("personid", personId); RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp"); dispatcher.forward(request, response); } 1. Get request parameters 2.Call business function 3. Determine next view

Web Development Life Cycle JSP page Welcome to Home Town Bank! Logout 4.Build next view

How to use HTTPServlet HttpServletRequestHttpServlet doGet(request HttpServletRequest, response:HttpServletResponse) doPost(request HttpServletRequest, response:HttpServletResponse) doPut(request HttpServletRequest, response:HttpServletResponse) doDelete(request HttpServletRequest, response:HttpServletResponse) HttpServletResponse Contains Request Info (Input)Handles Response (Output)

RequestResponse Interface Forwarding a Response

RequestResponse Interface Including other Web Components

Deployment of Servlets  All Servlet files zipped together into a web archive (“war”) file  Requires specific directory structure  Deployment Descriptor (WSDL)

Deployment Descriptor A Simple Application Verify Data VerifyData maxValue 25 Verify Data /verifydata /error404.html

Customizing Deployment  Define initialization parameters Context parameters Context parameters Apply to entire web applicationApply to entire web application Servlet parameters Servlet parameters Apply to a specific servletApply to a specific servlet

A Simple Application location BYU-Idaho Site Location Verify Data VerifyData maxValue 25 Verify Data /verifydata /error404.html Deployment Descriptor Context Intialization Parameter Servlet Intialization Parameter

Retrieving Init. Parameters public void init() throws ServletException { super.init(); ServletContext context = this.getServletContext(); String location = context.getInitParameter(“location"); if (maxValue == null) { int maxValue = Integer.parseInt(this.getInitParameter(“maxValue"); } … }

Handling Errors  HTTP Error Codes Http Status code – set error code Http Status code – set error code Error page – set default error page Error page – set default error page  Send Redirect – redirect to another page  Servlet Exceptions – catch and handle all servlet exceptions

Set HTTP Status Code  Sets the error status code on default error page Import java.io.*; import javax.servlet.*; import javax.servlet.http.*; publc class HtmlPage extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String name = request.getParameter(“name”); if (name.length() < 1) response.sendError(9001, “Invalid name”); } } HttpServletResponse public void sendError(int statusCode) public void sendError(int statusCode, String msg)) …. public void sendRedirect(String url);

Default HTTP Error Page A Simple Application Verify data VerifyData maxValue 25 verifyData /verifyData /error9001.html Define output error page for error code Deployment Descriptor

Send Redirect  Redirect to another page to handle error Import java.io.*; import javax.servlet.*; import javax.servlet.http.*; publc class HtmlPage extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { String name = request.getParameter(“name”); if (name.length() < 1) response.sendRedirect(“/Servlets/invalidNamePage”); } } HttpServletResponse public void sendError(int statusCode) public void sendError(int statusCode, String msg)) …. public void sendRedirect(String url);

Servlet Session Management  Hidden fields in form Visible to client in source (not secure) Visible to client in source (not secure) Limited amount of data Limited amount of data  URL rewritting  Cookies Store on client browser Store on client browser May be disabled by some users May be disabled by some users  Server side session object Session info stored on Server Session info stored on Server Unlimited amount of spaceUnlimited amount of space More secureMore secure Automatic management Automatic management

Creating Cookies  Implement transactions with Cookies Store state data in Cookie Store state data in Cookie Cookie public void setValue(String value) public String getName() public String getValue() …. HttpServletResponse … public void addCookie(Cookie c) public Cookie[ ] getCookies() ….

Creating a Cookie Import java.io.*; import javax.servlet.*; import javax.servlet.http.*; publc class HtmlPage extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { Cookie cookie = new Cookie(“userAddress”, null); String url = this.getRequextURI(); cookie.addValue(url); response.addCookie(cookie); double quantity = Double.parseDouble(request.getParameter(“quantity”)); double totalQuantity += (Double) session.getAttribute(“totalQuantity”); } catch (RemoteException remex) { response.sendError(response.SC_INTERNAL_SERVER_ERROR); } } }

Retrieving a Cookie publc class HtmlPage extends HttpServlet { String userUrl = new UniqueID(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { Cookie cookie = null; Cookie[] cookies = response.getCookies(); if (cookies != null) { for (int i=0; i < cookies.length; i++) { cookie = cookies[i]; if (cookie.getName().equals(“userAddress”)) { String urlAddress = cookie.getValue(); break; } } } } catch (RemoteException remex) { response.sendError(response.SC_INTERNAL_SERVER_ERROR); } }

Sessions  Implement transactions with a HttpSession Retains state of data between page request Retains state of data between page request HttpSession public long getId() public long getLastAccessedTime() public long getCreationTime() public long getMaxInactiveInterval() public Object getAttribute() public boolean isNew() …. HttpServletRequest … public HttpSession getSession() ….

Getting a Session Import java.io.*; import javax.servlet.*; import javax.servlet.http.*; publc class HtmlPage extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { try { HttpSession session = request.getSession(); if (session.isNew()) { Long personId = (Long) session.getAttribute(“personId”); } double quantity = Double.parseDouble(request.getParameter(“quantity”)); session.setAttribute(“quantity”); } catch (RemoteException remex) { response.sendError(response.SC_INTERNAL_SERVER_ERROR); } } }

Filter Servlets  Acts as preprocessor to request/response for target servlet Authenticate Filter Servlet HttpPage Servlet VerifyData Servlet PageHits Filter Servlet …HttpPage …VerifyData

Filter Servlet Import java.io.*; import javax.servlet.*; import javax.servlet.http.*; publc class PageHits extends HttpServlet implements Filter { private FilterConfig filterConfig = null; public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } public void destroy( { this.filterConfig = null; } Must override init. method Must override destroy method Must implement Filter Interface

Filter Servlet (cont.) public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return; synchronized (this) { Integer counter =(Integer) filterConfig.getServletContext().getAttribute("Counter"); if (counter == null) counter = new Integer(0); counter = new Integer(counter.intValue()+1); filterConfig.getServletContext().log("Number of hits is " + counter); filterConfig.getServletContext().setAttribute("Counter", counter); } chain.doFilter(req, resp) } Must override doFilter method

Modify Deployment Descriptor A Simple Application VerifyData VerifyData maxValue 25 Verify Data /verifyData/ Page Hits Page Hits Count page hits PageHits PageHits VerifyData

Listener Servlet  Servlet is automatically executed when some external event occurs HTTPSessionActivationListener Session is activated/passivated HTTPSessionAttributeListener Session attribute is added/removed HTTPSessionListener Session attribute is created/destroyed HTTPSessionContextAttributeListener Servlet contextattribute is added/removed HTTPSessionContextListener Servlet context changes

Create Listener Servlet Import java.io.*; import javax.servlet.*; import javax.servlet.http.*; publc class Listener extends HttpServlet implements ServletContextListener { private ServletContext context = null; public void contextIntialized(ServletContextEvent event) { context = event.getServerContext(); Integer counter = new Integer(0); context.setAttribute(“Counter”, counter); context.log(“Created Counter”); } public void contextDestroyed(ServletContextEvent event) { event.getServletContext().removeAttribute(“Counter”); } } Must override contextInitialized method Must implement Listner Interface

Modify Deployment Descriptor A Simple Application Verify data VerifyData maxValue 25 Verify Data /verifyData/ Page Hits Page Hits Count page hitsdescription> PageHits PageHits Verify data Listener

Modify Filter Servlet public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return; synchronized (this) { Integer counter =( Integer) filterConfig.getServletContext().getAttribute(“Counter”); if (counter = null) counter = new Integer(1); counter = new Integer(counter.intValue()+1); filterConfig.getServletContext().log(“Number of hits is “ + counter); filterConfig.getServletContext().setAttribute(“Counter”, counter); counter); } chain.doFilter(request, response); } } No longer needed

Modified Filter Servlet public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (filterConfig == null) return; synchronized (this) { Integer counter =( Integer) filterConfig.getServletContext().getAttribute(“Counter”); counter = new Integer(counter.intValue()+1); filterConfig.getServletContext().log(“Number of hits is “ + counter); filterConfig.getServletContext().setAttribute(“Counter”, counter); counter); } chain.doFilter(request, response); } }