Session 9 Introduction to Servlets Lecture Objectives Understand - - PDF document

session 9
SMART_READER_LITE
LIVE PREVIEW

Session 9 Introduction to Servlets Lecture Objectives Understand - - PDF document

Internet Programming Session 9 Servlet Intro Session 9 Introduction to Servlets Lecture Objectives Understand the foundations for client/server Web interactions Understand the servlet life cycle 2 Robert Kelly, 2018 1


slide-1
SLIDE 1

Session 9 – Servlet Intro 10/11/2018 1 Internet Programming Robert Kelly, 2018

Session 9

Introduction to Servlets

Robert Kelly, 2018

Lecture Objectives

Understand the foundations for client/server Web interactions Understand the servlet life cycle

2

slide-2
SLIDE 2

Session 9 – Servlet Intro 10/11/2018 2 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018

Reading & Reference

Reading

Java Servlet

en.wikipedia.org/wiki/Java_servlet

Java Annotation

en.wikipedia.org/wiki/Java_annotation docs.oracle.com/javase/tutorial/java/annotations/

Excellent tutorial, explaining how to set up a servlet in NetBeans

www.studytonight.com/servlet/creating-servlet-in-netbeans.php

Reference

Use the on-line Servlet API documentation at:

http://docs.oracle.com/javaee/7/api/

3

Use the J2EE 7 Tutorial as a Reference

Robert Kelly, 2018

Java Servlet Releases

Servlet 3.0 – 2009 Servlet 3.1 – May 2013 (consistent with Java EE 7) Servlet 4.0 – September 2017 (consistent with Java EE 8 and HTTP/2)

4

Java EE now maintained by the Eclipse foundation, and renamed as Jakarta EE

slide-3
SLIDE 3

Session 9 – Servlet Intro 10/11/2018 3 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018 5

Typical Client/Server Interaction

Browser

HTML, CSS, MIME Type Display Static Component HTTP interface

Web Container Database

URL / Query string / HTTP data, cookies, etc.

HTML, Images, cookies, etc.

req

res JDBC

WWW resources, each named with a URL Standard content formats (e.g., HTML) Standard network protocols connecting any browser with any server

Web Server Web container is also referred to as a servlet container

Robert Kelly, 2018

Server Strategies

Generation of HTML/CSS

Server responds with a dynamically generated page that includes HTML, CSS, and data (inserted in the page) Data insertion usually performed by a server-side scripting engine

Web services

Server responds with data (no HTML and CSS) Data structured based on some coordination between client and server (e.g., JSON, XML, text)

6

slide-4
SLIDE 4

Session 9 – Servlet Intro 10/11/2018 4 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018

Servlets

Conforms to the Java Servlet API Superseded by JAX-RS (Java API for RESTful Web Services) API A servlet:

Is a Java class that can be loaded dynamically to expand the capability of the Web server Runs inside the Java Virtual Machine on the server (safe and portable) Is able to access all Java APIs supported in the server Does not have a main method

7 Robert Kelly, 2018

Servlet Implementation

Web Server (Web Container) Market Share1 of active sites

8

Developer March 2018 Percent Apache 76M 43.0% nginx 37M 21.0% Google 12M 7.7% Microsoft 12M 6.8%

  • 1. Data from NetCraft
slide-5
SLIDE 5

Session 9 – Servlet Intro 10/11/2018 5 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018 9

Servlet / Web Server Interface

Static Interface

request response

Web Container

HttpServlet subclass Service methods (doGet and doPost) The Web Server static interface primarily serves resources, and passes complex request to the Web Container http method MIME files Frequently both servers are packaged together, but it is good to think of them as separate systems

Robert Kelly, 2018

Servlet Interface

Objects are used to pass information to the server and to return information from the server Service methods:

10

Request data include HTTP version, URL, browser software, client MIME type preferences, data, etc. Response data includes HTTP version, status code, MIME type of data, document size, document

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException protected void doPost( HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException

slide-6
SLIDE 6

Session 9 – Servlet Intro 10/11/2018 6 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018 11

Server Generation of an HTML page

The following HTML can be returned to the browser directly by the Web server (static file on the Web Server) – or the same html page can be generated (on the fly) by the Web Container

<html> <head> <title>Hello World</title> </head> <body> <p>Hello World</p> </body></html>

Robert Kelly, 2018 12

<!doctype html> <html> <head> <title>Link to Hello World Servlet</title> </head> <body> <p> <a href="http://localhost:8080/CSE336-2017/HelloWorld"> Click here to say hello to the world</a> </p> </body> </html>

Invoking the Hello World Servlet

The URL in this link maps to the servlet Name of the Web application This is not really a file – it maps to your servlet Verify the port number used by your test server Port 8080 is typical for a test http server

slide-7
SLIDE 7

Session 9 – Servlet Intro 10/11/2018 7 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018 13

Hello World Servlet Method

protected void processRequest( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String docTyp= "<!DOCTYPE html >";

  • ut.println(docType);
  • ut.println("<html>");
  • ut.println("<head><title>"

+ "Hello World</title></head>");

  • ut.println("<meta charset=\"UTF-8\">");
  • ut.println("<body>");
  • ut.println("<h1>Hello World</h1>");
  • ut.println("</body></html>");
  • ut.close(); }

Robert Kelly, 2018

HelloWorld Servlet Class

package lectures; import java.io.*;import java.net.*;import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }

14

The Web container calls either doGet or doPost, which then calls processRequest processRequest is a method used by convention in NetBeans

slide-8
SLIDE 8

Session 9 – Servlet Intro 10/11/2018 8 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018

Web Application

Your Web application contains all the servlets, JSPs, files, etc. associated with your application. Your Web application is stored in a directory (and deployed as a war file) Top level directory of the Web application is the document root of the application, containing JSP pages and static Web resources (or subdirectories of JSP, etc.) Document root contains a sub-directory called WEB-INF, containing

web.xml – the deployment descriptor Sub-directories containing classes Meta data for the Web Application

15

Take a look at your Web App in your NetBeans or Eclipse project pane

Robert Kelly, 2018

How to Specify the Servlet in Your HTML

A URL is used to request that the container run your servlet (in an anchor tag or form tag) URL contains the host name, port (optional), and path In a servlet container, the path can be mapped (what you see is not always what you get)

16

http://localhost:8080/CSE336-2017/HelloWorld

There is no HelloWorld resource

slide-9
SLIDE 9

Session 9 – Servlet Intro 10/11/2018 9 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018

How URLs Run Servlets

The servlet container evaluates the URL request to see if the first part of the path matches a context name If the path matches a context name, the context name is mapped to a Web application root directory (using the web.xml deployment descriptor)

17

http://localhost:8080/CodeCSE336/helloWorld

Context name (Web Application or Project name)

Robert Kelly, 2018

Mapping Requests to Servlets

Two approaches

Web.xml (Deployment Descriptor) Annotation

18

slide-10
SLIDE 10

Session 9 – Servlet Intro 10/11/2018 10 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018

You can annotate classes, methods, fields, and local variables

Annotation Recap …

Part of Java language, starting with Java 5 Annotations are tags that you insert into source code so that some tool can process it (not part of the normal execution of the program) Proper style places the annotation on a line preceding the statement it relates to

19

@Entity public class Team implements Serializable {

Think of it as a modifier for the declaration

Robert Kelly, 2018

… Annotation recap

Annotations can be defined to have elements

20

@ManyToOne(cascade=CascadeType.PERSIST) public Team getTeam() { … }

Examples Unit testing (JUnit) Java Persistence API (JPA) Servlets Java Beans

slide-11
SLIDE 11

Session 9 – Servlet Intro 10/11/2018 11 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018

Annotation Example - JPA

Java Persistence allow you to specify the DB design in your code

21 Robert Kelly, 2018

Servlet Mapping with Annotations

New with Java EE 5 Keeps information about mapping a URL pattern to a servlet class in one place – servlet code Example

22

@WebServlet(name = "HelloWorld", urlPatterns = {"/HelloWorld"}) public class HelloWorld extends HttpServlet {

slide-12
SLIDE 12

Session 9 – Servlet Intro 10/11/2018 12 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018

Servlet Annotations

23

Modifier and Type Optional Element and Description

boolean asyncSupported - Declares whether the servlet supports asynchronous operation mode. String description - The description of the servlet String displayName - The display name of the servlet WebInitParam[] initParams The init parameters of the servlet String largeIcon - The large-icon of the servlet int loadOnStartup - The load-on-startup order of the servlet String name - The name of the servlet String smallIcon - The small-icon of the servlet String[] urlPatterns - The URL patterns of the servlet String[] value - The URL patterns of the servlet

Robert Kelly, 2018

Deployment Descriptor (web.xml)

Alternate (older) technique to deploy your Web application (i.e., servlets, JSPs, etc.) NetBeans display of Deployment Descriptor (below)

24

You can use a URL pattern that is different from the servlet name

slide-13
SLIDE 13

Session 9 – Servlet Intro 10/11/2018 13 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018 25

web.xml

<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <description>A Hello World servlet </description> <servlet-name>HelloWorld</servlet-name> <servlet-class>lectures.HelloWorld</servlet-class> </servlet> ... <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping> ... <session-config> <session-timeout> 30 </session-timeout> </session-config> </web-ap>

Robert Kelly, 2018

Are We on Track?

Create a HelloWorld servlet that displays Hello World in your browser Invoke it from your IDE Invoke it from your browser

26

This is just to discover anomalies in your lab or personal implementation of your IDE Be sure you have installed the Web components of your IDE

slide-14
SLIDE 14

Session 9 – Servlet Intro 10/11/2018 14 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018

Were We on Track?

@WebServlet(name = "HelloWorld", urlPatterns = {"/HelloWorld"}) public class HelloWorld extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) {

  • ut.println("<!DOCTYPE html>");
  • ut.println("<html>"); out.println("<head>");
  • ut.println("<title>Servlet HelloWorld</title>");
  • ut.println("</head>"); out.println("<body>");
  • ut.println("<h1>Hello World</h1>");
  • ut.println("</body>");
  • ut.println("</html>"); } }

27 Robert Kelly, 2018

Request Message Format

The http request is specified by the request line, a variable number

  • f header fields, and the entity body

28

method sp URL sp Version cr lf header field name sp value cr lf header field name sp value cr lf header field name sp value cr lf cr lf

request line (like a method call) header lines (like a parameter list

  • f Strings)

Entity body (like a single object parameter

slide-15
SLIDE 15

Session 9 – Servlet Intro 10/11/2018 15 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018 29

Calling Sequence

service(req, res) doGet(req, res) doPost(req, res) doOptions()

Etc.

Browser Web Server Includes all name value pairs in the form field plus server data in the URL query strings, header data, and cookies Includes header data and all name value pairs in the request

  • bject

NetBeans uses a processRequest method (not a standard) processRequest(req, res)

HTTP method becoming much more important with RESTful services

Robert Kelly, 2018

Some HttpServletRequest Methods

ServletRequest

getParameter(String s) getScheme() getProtocol() getRemoteAddress() isSecure() getContentType() getRequestedSessionID()

HttpServletRequest

getRequestURI isRequestedSessionValid() getQueryString() getRemoteUser getMethod() getCookies() getHeader()

30

slide-16
SLIDE 16

Session 9 – Servlet Intro 10/11/2018 16 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018

HttpServletResponse

Some methods:

getWriter - from ServletResponse sendError(int sc) addCookie(Cookie cookie) sendRedirect(String location)

Some fields:

SC_GONE SC_INTERNAL_SERVER_ERROR SC_NOT_FOUND

31 Robert Kelly, 2018

Why doGet and doPost?

HTTP – a simple stateless protocol (Web browser makes a request and the server responds) The request from the browser specifies an HTTP method, along with client data HTTP methods – GET, POST, HEAD, PUT, DELETE, etc. Method called (doGet or doPost) corresponds to the HTTP method requested by the browser

32

slide-17
SLIDE 17

Session 9 – Servlet Intro 10/11/2018 17 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018

doGet / doPost Practice

A servlet usually does not distinguish between a GET and a POST method call One of the methods usually invokes the other

33

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

Or NetBeans generates a processRequest method

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }

Web services takes a stricter view of the http method used

Robert Kelly, 2018

Servlet Generation of HTML

A servlet will generate 2 kinds of output

Information about the transmission to the browser – this is stored in the http header of the response Data (e.g., HTML) that is stored in the http body of the response

34

Servlet buffer

http packet

slide-18
SLIDE 18

Session 9 – Servlet Intro 10/11/2018 18 Internet Programming Robert Kelly, 2018

Robert Kelly, 2018 35

Server Stream Caching

Header data – headers can be set in any order and are not sent until the first buffer fills

Response header data includes age, cache control, language, message digest, MIME type, expiration date, last modified date, etc. isCommitted method – returns boolean indicating that headers have been sent

Buffered stream data

setBufferSize flushBuffer

Robert Kelly, 2018

Have You Satisfied the Lecture Objectives?

Understand the foundations for client/server Web interactions Understand the servlet life cycle

36