Servlet part 1 Servlets We previously learned php

  • Slides: 58
Download presentation
Servlet (part 1)

Servlet (part 1)

Servlets • We previously learned php, Java now replaces php on the server side

Servlets • We previously learned php, Java now replaces php on the server side and includes a lot of technology. Servlets are the most basic elements of this technology. • A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. • Servlets most common usages: – Create dynamic webpages – Handle forms (the form data is the request) • A servlet is a dynamically loaded module that services requests from a Web server • A servlet runs entirely inside the Java Virtual Machine • Servlet does not depend on browser compatibility

Java Servlet Diagram • example of a servlet handling a request and returning a

Java Servlet Diagram • example of a servlet handling a request and returning a response • 3. Servlet Engine runs the servlet • 1. Browser sends request to Web Server • 2. Web Server sends request to Servlet Engine • Servlet Container • Servlet • Web Server • Servlet • jdbc • 5. Servlet generates and returns HTML • Servlet • Top. Link • browser • 6. Web Server sends HTML to Browser • DB • 4. Servlet can access database

Example of Using Servlets • Developing e-commerce store fronts: – A Servlet can build

Example of Using Servlets • Developing e-commerce store fronts: – A Servlet can build an on-line catalog from database – The Servlets can present the catalog using dynamic HTML – A customer fills out order and submits it to the servlet – The Servlet processes the order and submits the result to the database

The Basic Web Architecture • All traffic between server and client is http based

The Basic Web Architecture • All traffic between server and client is http based HTTP Web Server n n Generic server component Can be customized to execute backend programs (program choice is based entirely on URL) – If so, it parses input stream and puts data into environment variables – Original version of this was CGI scripting • Sends ASCII streams via socket – Standard information about client machine (e. g. from using predefined fields) – “Form data” – “Cookie” information • Receives ASCII stream in response – Stores cookies – Renders based on mime type of response • Requires hardcoded addresses (URLs) • Completely generic

The HTTP Round Trip GET /welcome. html HTTP/1. 0 Accept: www/source Accept: text/html Accept:

The HTTP Round Trip GET /welcome. html HTTP/1. 0 Accept: www/source Accept: text/html Accept: image/gif User-Agent: Mozilla/4. 01 [en] If-Modified-Since: Fri Mar 12 16: 14: 55 1999 Referer: http: //www. cs. huji. ac. il/ From: solange@cs. huji. ac. il. . Web Server HTTP/1. 1 200 OK Date: Wed, 17 Mar 1999 03: 05: 16 GMT Server: Apache/1. 3. 1 (Unix) Last-Modified: Fri, 05 Feb 1999 21: 42 GMT ETag: "385 e 12 -127 a-36 bb 60 e 6" Accept-Ranges: bytes Content-Length: 4730 Connection: close Content-Type: text/html <!DOCTYPE HTML PUBLIC "-//Soft. Quad//DTD Ho. TMeta. L PRO 4. 0: : 1997091 <HTML>

The Structure of a Request • It’s a message, with a more specific structure

The Structure of a Request • It’s a message, with a more specific structure request = request-line request-header* CRLF [message-body] request-line = method request-uri http-version request-header = general-header | entity-header | request-header method = CONNECT | DELETE | PUT | GET | HEAD | OPTIONS | POST | TRACE

Example Requests OPTIONS /index. html HTTP/1. 0 GET /index. html HTTP/1. 1 Connection: keep-alive

Example Requests OPTIONS /index. html HTTP/1. 0 GET /index. html HTTP/1. 1 Connection: keep-alive User-Agent: Mozilla/4. 51 Gold (Win. NT; I) Accept: image/gif, image/jpeg, text/html Probably the most commonly used request header-specifies mime types that are acceptable to client

URL Mangling Suppose you type Used in establishing socket connection http: //www. hac. il/people/solange/index.

URL Mangling Suppose you type Used in establishing socket connection http: //www. hac. il/people/solange/index. html This becomes GET /people/solange/index. html HTTP/1. 0 [headers etcetera]

The Structure of a Response • It’s a message, with a more specific structure

The Structure of a Response • It’s a message, with a more specific structure • Status codes fall into 5 blocks: • • • 1 xx -- informational (will be superceded by later code) 2 xx -- success. 200 being “plain vanilla” and the others being variations on it. 3 xx -- redirection. frequently useful in GETS when last-modified is involved 4 xx -- client side failure. Things like bad urls, authentication failures 5 xx -- server side failure request = status-line response-header* CRLF [message-body] status-line = http-version status-code textual-description response-header = general-header | entity-header | response-header

Sample Responses Status line HTTP/1. 1 400 Bad Request Date: Wed, 24 Mar 1999

Sample Responses Status line HTTP/1. 1 400 Bad Request Date: Wed, 24 Mar 1999 04: 11: 23 GMT Server: Apache/1. 3. 1 (Unix) Connection: close Transfer-Encoding: chunked Content-Type: text/htmld 7 <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2. 0//EN"> <HTML> <HEAD> <TITLE>400 Bad Request</TITLE> </HEAD> <BODY> <H 1>Bad Request</H 1> Your browser sent a request thatthis server could not understand. <P> </BODY> </HTML> HTTP/1. 1 200 OK Date: Wed, 24 Mar 1999 04: 21: 42 GMT Server: Apache/1. 3. 1 (Unix) Content-Length: 0 Allow: GET, HEAD, OPTIONS, TRACE Connection: close Response headers Message Body Actual response to asking www. cs. huji. ac. il for OPTIONS

Common Response Headers These headers can be used by the servlet, for example: the

Common Response Headers These headers can be used by the servlet, for example: the contenttype may specify a response format (jpeg, html etc…)

HTML Forms • Interactive HTML: forms are used to send data (to servlets) for

HTML Forms • Interactive HTML: forms are used to send data (to servlets) for processing, for example a form used to register users to a website • Composed of input elements (buttons, text fields, check boxes) with <form> tag • On Submission, browser packages user input and sends to server (with submit button) • Server passes information to supporting application that formats reply (HTML page)

The FORM Tag • FORM is the HTML tag that allows users to enter

The FORM Tag • FORM is the HTML tag that allows users to enter data <FORM ACTION = url METHOD = method> contents </FORM> URL is a standard address Contents defined via ordinary HTML, with extra input specifications defined using the INPUT tag Method is always either GET or POST

The INPUT Tag • Inside a form, INPUT tags define fields for data entry

The INPUT Tag • Inside a form, INPUT tags define fields for data entry • <INPUT TYPE = input-type NAME = parameter-name [other, input-type specific, attributes] > • Standard input types include: buttons, checkboxes, password field, radio buttons, text fields, imagebuttons, text areas, pull-down menus • They all associate a single (string) value with a named parameter: the name of the parameter is used in Java to retrieve the form input values • Special input: <input type="submit"> When the user presses the submit button, all form data is sent to the server (according to the “action” attribute)

Form Parameters • action attribute give URL of application that receives and processes form’s

Form Parameters • action attribute give URL of application that receives and processes form’s data <form action=“http: //www. hadassah. ac. il/cs/listcourses”> … </form> • enctype attribute to change encryption (not useful for now…) • method attribute sets the method by which data sent to server (HTTP methods)

Forms Live examples • Form: http: //www. w 3 schools. com/html/tryit. asp? filename=t ryhtml_form_text

Forms Live examples • Form: http: //www. w 3 schools. com/html/tryit. asp? filename=t ryhtml_form_text • Radio buttons: http: //www. w 3 schools. com/html/tryit. asp? filename=t ryhtml_form_radio • The submit button: http: //www. w 3 schools. com/html/tryit. asp? filename=t ryhtml_form_submit • Full tutorial: http: //www. w 3 schools. com/html_forms. asp

HTTP Methods • When you write a FORM, you need to specify the METHOD.

HTTP Methods • When you write a FORM, you need to specify the METHOD. You have 2 choices. • POST: – Data sent in the body of request (hidden to user) – Designed for processing information • Browser contacts server • Sends data – Sending the request only through FORM (or Ajax) • GET: – Data sent in the header/URL (visible to user) – Appends data to action URL separated by question mark • example: http: //foo. com? a=1&b=2 – Designed to get information – URL can be saved and request can be automatically sent (by program or user)

Other Methods (unused in this course) • HEAD: Client sees only header of response

Other Methods (unused in this course) • HEAD: Client sees only header of response to determine size, etc… • PUT: Place documents directly on server • DELETE: Opposite of PUT • TRACE: Debugging aid returns to client contents of its request • OPTIONS: what options available on server

Form Example <HTML> … <form method=“GET” action=“http: //www. hac. il/register 2 course”> <input type=“text”

Form Example <HTML> … <form method=“GET” action=“http: //www. hac. il/register 2 course”> <input type=“text” name=“username”> …… </form> … </HTML> http: //www. hac. il/register 2 course? username=Lisa

Servlets, what for? • A servlet can handle several states: it can – Display

Servlets, what for? • A servlet can handle several states: it can – Display HTML with a form – Handle the submission of a form – Transfer a request to another servlet • In the next example, we create 2 separate elements: – A HTML page with a form – A servlet to handle the form submission

A book review example • We have a html page including a form, where

A book review example • We have a html page including a form, where the ACTION is the servlet • We have a servlet that will be called when the form is submitted – The servlet receives all form data (the request) – It processes the data – It returns a HTML page to the browser (the response)

Note that 1. the servlet class must extends Http. Servlet 2. There are 2

Note that 1. the servlet class must extends Http. Servlet 2. There are 2 methods, do. Post and do. Get that can be overriden to handle the request. Since the HTML form specified method=“post” we implement the do. Post method 3. We need to tell the browser what kind of data we are sending (it could be an image, not necessarily HTML) 4. It’s important to close the response to signal the browser all data was sent 5. The servlet sends a full HTML page: it is kind of ugly, don’t worry we will later learn how to avoid this output

What’s in the Servlet Package • javax. servlet • Servlet interface defines methods that

What’s in the Servlet Package • javax. servlet • Servlet interface defines methods that manage servlet and its communication with clients • Client Interaction: When it accepts call, receives two objects – Servlet. Request – Servlet. Response

What is Servlet? • servlet is simply an object that inherits from javax. servlet.

What is Servlet? • servlet is simply an object that inherits from javax. servlet. Generic. Servlet – Web servlets actually extend a subclass (javax. servlet. http. Http. Servlet) – It has a very different lifecycle from an application (no equivalent of main)

The Servlet Interface (base class) • All servlets must implement the Servlet interface –

The Servlet Interface (base class) • All servlets must implement the Servlet interface – void init(Servlet. Config config) • called every time the servlet is instantiated: the Servlet is instantiated ONCE for all (first time it is being called) – void service(Servlet. Request req, Servlet. Response res) • Servlet. Request: parameters from the client • Servlet. Response: contains an output stream used to return information to the client • needs to be thread-safe since multiple requests can be handled concurrently • not called until init() has finished execution

Basic of Servlets • • Override do. Post and do. Get parameter values from

Basic of Servlets • • Override do. Post and do. Get parameter values from request Set headers Write response to the stream – Normally HTML, using Print. Writer – But you have a stream. You can set the content type to be anything you like and then simply send bytes into the stream • set. Content(“image/gif”) works just fine

The Servlet Interface – These methods are part of the Servlet interface (therefore Http.

The Servlet Interface – These methods are part of the Servlet interface (therefore Http. Servlet as well) – void destroy() • called by the servlet engine when it removes the servlet (it is removed for example when it wasn’t used for long) • should free any resources (i. e. files or database connections) held by the servlet – String get. Servlet. Info() • Returns version and copyright information

The Http. Servlet Interface • Implements Servlet • Receives requests and sends responses to

The Http. Servlet Interface • Implements Servlet • Receives requests and sends responses to a web browser • Methods to handle different types of HTTP requests: – do. Get() handles GET requests – do. Post() handles POST requests – do. Put() handles PUT requests – do. Delete() handles DELETE requests

Handling Http. Servlet Requests • service() method not usually overridden – do. XXX() methods

Handling Http. Servlet Requests • service() method not usually overridden – do. XXX() methods handle the different request types • There is one instance of each Servlet (managed by the web server/servlet container) serving all clients. Multiple users simultaneously trigger the same one Servlet. • Needs to be thread-safe or must run on a STM (Single. Thread. Model) Servlet Engine – multiple requests can be handled at the same time – We will learn about Threads next lesson

Http. Servlet Request Handling Web GET request Server Http. Servlet subclass do. Get() response

Http. Servlet Request Handling Web GET request Server Http. Servlet subclass do. Get() response service() POST request do. Post() response

Servlet. Request Interface • Encapsulates communication from client to server – parameters passed by

Servlet. Request Interface • Encapsulates communication from client to server – parameters passed by client (form data for example), – protocol used by client, – names of remote host, and server • Servlet. Input. Stream for data transfer from client to server using HTTP POST and PUT • Http. Servlet. Request access HTTP header info

Servlet. Request Interface public abstract int get. Content. Length() public abstract String get. Content.

Servlet. Request Interface public abstract int get. Content. Length() public abstract String get. Content. Type() public abstract String get. Protocol() public abstract String get. Scheme() public abstract String get. Server. Name() int get. Server. Port() String get. Remote. Addr() String get. Remote. Host() public abstract String get. Parameter(String name) String[] get. Parameter. Values(String name) Enumeration get. Parameter. Names() Object get. Attribute(String name)

Http. Servlet. Request Interface public String get. Method() public String get. Request. URI() public

Http. Servlet. Request Interface public String get. Method() public String get. Request. URI() public Enumeration get. Header. Names() String get. Header(String name) int get. Int. Header(String name) long get. Date. Header(String name) public public Cookie[] get. Cookies() Http. Session get. Session(boolean create) String get. Requested. Session. Id() boolean is. Requested. Session. Id. Valid() boolean is. Requested. Session. Id. From. Cookie() boolean is. Requested. Session. Id. From. Url()

Information available in the request • Parameters, which are typically used to convey information

Information available in the request • Parameters, which are typically used to convey information between clients and servlets • Object-valued attributes, which are typically used to pass information between the web container and a servlet or between collaborating servlets (LATER) • Information about the protocol used to communicate the request and about the client and server involved in the request • Information relevant to localization

HTTPServlet. Response • This is the class you will use to send data back

HTTPServlet. Response • This is the class you will use to send data back to the browser (HTML) • Subclass of Servlet. Response specialized to web servers • Most of the time, you set content type and add information to it These are from public void set. Content. Length(int len) public void set. Content. Type(String type) Servlet. Response public Servlet. Output. Stream get. Output. Stream() throws IOException public Print. Writer get. Writer() throws IOException public String get. Character. Encoding()

Servlet. Response Interface • Contains methods for replying to client – Set content length

Servlet. Response Interface • Contains methods for replying to client – Set content length and MIME type of reply • Servlet. Output. Stream and a Writer to send data • Http. Servlet. Response protocol specific public void set. Content. Length(int len) public void set. Content. Type(String type) public Servlet. Output. Stream get. Output. Stream() throws IOException public Print. Writer get. Writer() throws IOException public String get. Character. Encoding()

Http. Servlet. Response Interface Static ints defined in public void send. Error(int sc, String

Http. Servlet. Response Interface Static ints defined in public void send. Error(int sc, String msg) throws IOException. Http. Servlet. Response are used as public void send. Error(int sc) throws IOException arguments here (and you can either use public void set. Status(int sc, String sm) the default message or substitute your public void set. Status(int sc) own). public boolean contains. Header(String name) public void set. Header(String name, String value) public void set. Int. Header(String name, int value) public void set. Date. Header(String name, long date) Doesn’t the sevlet already know all of these (didn’t it set them ? ). Not necessarily. Some headers come from other servlets (either from server-side includes or via servlet chaining) and others may be set by the web server before the servlet is called. public void send. Redirect(String location) throws IOException Argument must be an absolute URL public void add. Cookie(Cookie cookie) public String encode. Url(String url) public String encode. Redirect. Url(String url) These are useful for preserving state across page retrievals-- Encoding a url takes a URL and rewrites it to encode the session id (so that the web server will be able to retrieve state should the user click on it)

public class Simple. Servlet extends Http. Servlet { /** * Handle the HTTP GET

public class Simple. Servlet extends Http. Servlet { /** * Handle the HTTP GET method by building a simple web page. */ public void do. Get (Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { Print. Writer out; String title = "Simple Servlet Output"; // set content type and other response header fields first // here you could send binary data (image for example) and // set the content. Type to img/jpeg response. set. Content. Type("text/html"); // then write the data of the response out = response. get. Writer(); out. println("<HTML><HEAD><TITLE>"); out. println(title); out. println("</TITLE></HEAD><BODY>"); out. println("<H 1>" + title + "</H 1>"); out. println("<P>This is output from Simple. Servlet. "); out. println("</BODY></HTML>"); out. close(); } }

Developpig a Servlet: Steps • Subclass Http. Servlet • Override do. Get() or/and do.

Developpig a Servlet: Steps • Subclass Http. Servlet • Override do. Get() or/and do. Post() – These methods receive 2 parameters • User Request encapsulated in Http. Servlet. Request object • Response encapsulated in Http. Servlet. Response object – Use output stream from Http. Servlet. Response

What’s in the request? • Handle requests through service method (calls do. Get()) •

What’s in the request? • Handle requests through service method (calls do. Get()) • Http. Servlet. Request Objects – get. Parameter returns value of named parameter – get. Parameter. Values if more than one value – get. Parameter. Names for names of parameters – get. Query. String for HTTP GET returns string of raw data from client. Must parse. – HTTP POST, PUT, DELETE Requests • Text: get. Reader returns Buffered. Reader • Binary: get. Input. Stream returns Servlet. Input. Stream

What’s in the response? • Http. Servlet. Response Object – get. Writer returns a

What’s in the response? • Http. Servlet. Response Object – get. Writer returns a Writer for text – get. Output. Stream returns Servlet. Output. Stream for binary – Important: • Set header data before you start writing into the response stream!! – For example set. Content. Type to specifiy the text/html format • Why? Because once you have written into the response stream, headers are automatically sent, therefore you cannot change them!

Response Type • The browser needs to know what kind of data is received

Response Type • The browser needs to know what kind of data is received • Response type does not have to be a text • You can, for example, • set. Content(“image/gif”) – and send a stream of bits of an image • You can also return a HTML form that calls your servlet again as a response to a user action : one Servlet can handle multiple pages (states) of your website

How can you handle states? • Look at the method: POST or GET? For

How can you handle states? • Look at the method: POST or GET? For example – If GET, we just display a HTML form – If POST we process form data • Put hidden input field in your forms: their purpose is to send information about current state

Servlet Life Cycle • There is no main() method! • Server loads and initializes

Servlet Life Cycle • There is no main() method! • Server loads and initializes servlet (creates one instance) • servlet handles client requests (all clients execute the single servlet intance) • Server may remove servlet (we don’t know when!)

Servlet Lifecycle • Required by the spec: – The servlet is created via a

Servlet Lifecycle • Required by the spec: – The servlet is created via a call to a zero argument constructor – init(Servlet. Config) is called (and finishes) – Some number of requests are processed – destroy() is called • Implemented by almost everyone: – A single instance of the servlet persists until the. class file is altered – It handles all the requests

Life Cycle Schema

Life Cycle Schema

Starting and Destroying Servlets • Initialization: – Servlet’s init(Servlet. Config) method – Create I/O

Starting and Destroying Servlets • Initialization: – Servlet’s init(Servlet. Config) method – Create I/O to intensive resources (database) – Initialization parameters are server specific – Seen in servletrunner properties file • Destroying: – destroy() method – make sure all service threads complete

Servlet. Config • An object of Servlet. Config is created by the web container

Servlet. Config • An object of Servlet. Config is created by the web container for each servlet. This object can be used to get configuration information – from web. xml file (located in WEB-INF folder). The file can be easily edited so beware you can easily break it! – Or from annotations, which is preferred in this course. • When a servlet is created, it can have a set of initialization parameters (just like command line args to an application) – How these parameters are set is web-server specific (you need to configure the web server) – You can store for example DB credentials (server, user, password) • Servlet. Config lets the Servlet get at this initial configuration information public Servlet. Context get. Servlet. Context() public String get. Init. Parameter(String name) public Enumeration get. Init. Parameter. Names()

How to keep track of states? • HTTP is a stateless protocol – many

How to keep track of states? • HTTP is a stateless protocol – many web applications (i. e. shopping carts) are not – need to keep track of each user’s state (i. e. items in the shopping cart) • Common techniques (in next lecture) – user authorization – hidden form fields – URL rewriting – persistent cookies

Running Servlets • Servlets require a servlet container (web server) such as Tomcat. •

Running Servlets • Servlets require a servlet container (web server) such as Tomcat. • We use tomcat in this course (note that it is part of XAMPP installation however XAMPP uses an old version so we recommend to install tomcat directly from their distribution) • Servlets require some configuration to be defined, you 2 options: – Insert the parameters in the web. xml file – Use annotations (preferred option)

web. xml / annotations <servlet> <servlet-name>Example</servlet-name> <servlet-class>com. servlets</servlet-class> <init-param> <param-name>path</param-name> <param-value>/files/</param-value> </init-param> </servlet> <servlet-mapping>

web. xml / annotations <servlet> <servlet-name>Example</servlet-name> <servlet-class>com. servlets</servlet-class> <init-param> <param-name>path</param-name> <param-value>/files/</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>welcome</servlet-name> <url-pattern>/files/*</url-pattern> </servlet-mapping> Preferred method import javax. servlet. annotation. Web. Servlet; @Web. Servlet(name = ”welcome", url. Patterns = "/files/*", init. Params = @Web. Init. Param( name = ”path", value = "/files/" ) ) public class Download extends Http. Servlet {

Creating a Servlet project (intelli. J) • Tomcat must be installed • Choose New

Creating a Servlet project (intelli. J) • Tomcat must be installed • Choose New Project -> Java Enterprise -> Web Application – You will automatically have tomcat selected as server, if not you will have to specify it later in the configuration • Add a package to the “src” folder (right click add package…) • Open Views->Tool Windows->Web • Right click on the root folder (web) add Servlet – If you want to use annotations, make sure to check the “create Java EE 6 annotated class” – Select the package you created earlier – Give a class name • Run • Assume the Servlet is named “welcome”, the servlet should be accessible as – http: //localhost: 8080/nameofyourproject_exploded/welcome

Servlets and JDBC • Servlets typically access databases using JDBC • Concurrency is not

Servlets and JDBC • Servlets typically access databases using JDBC • Concurrency is not an issue for the DB (the DB server handles it) • Simple example: – Register Form activates servlet – Servlet gets user form input in the request – Servlet process the input and insert the user in the database – Servlet returns HTML page to browser (confirmation if ok, error page if any error)

Servlets and JDBC • You can either create a connection and close it for

Servlets and JDBC • You can either create a connection and close it for each request (in the do. Get and do Post methods) or. . • Create the connection in the init() method and close it in destroy() • What is the difference? – In one case the connection is released immediately after processing the request, in the other the connection is hold as long as the Servlet is loaded – Think that each client will create a connection in first case, so you could run out of connections. – Very often there is a layer that implements connection pooling (limiting the number of simultaneous connections)

Servlets in one picture cookies Servlet Lifecycle 1. The Servlet container calls the no-arg

Servlets in one picture cookies Servlet Lifecycle 1. The Servlet container calls the no-arg constructor. 2. The Servlet container calls the init() method. This method initializes the servlet and must be called before life of a servlet, the init() method is called only once. 3. After initialization, the servlet can service client requests. Each request is serviced in its own separate thread. The Web container calls the service() method of the servlet for every request. 4. Finally, the Servlet container calls the destroy() method that takes the servlet out of service. The destroy() method, like init(), is called only once in the lifecycle of a servlet. cookies request / response Web Server + Servlet container The Servlet container maintains a bounded pool of worker threads to handle requests. thread response. add. Cookie(…) request. get. Cookies() Servlet A Servlet B Servlet C request. set. Attribute(. . ) // addd extra params dispatcher. forward(request, response) // forward to other servlet website session. set. Attribute(…) object session. get. Attribute(…) session object

Links • http: //courses. coreservlets. com/Course. Materials/csajsp 2. html • https: //www. tutorialspoint. com/servlets/ind

Links • http: //courses. coreservlets. com/Course. Materials/csajsp 2. html • https: //www. tutorialspoint. com/servlets/ind ex. htm • https: //www. javatpoint. com/servlet-tutorial