Servlets part 1 Dr Solange Karsenty Hadassah Academic

  • Slides: 32
Download presentation
Servlets (part 1) Dr Solange Karsenty Hadassah Academic College 1

Servlets (part 1) Dr Solange Karsenty Hadassah Academic College 1

Java Servlet Diagram • 3. Servlet Engine runs the servlet • 1. Browser sends

Java Servlet Diagram • 3. Servlet Engine runs the servlet • 1. Browser sends request to Web Server • 2. Web Server sends request to Servlet Engine • Servlet Container • Servlet • browser • 6. Web Server sends HTML to Browser • Servlet • Web Server • Servlet • jdbc • 5. Servlet can generate and return HTML (not only) • Servlet • DB • 4. Servlet can access database 3

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 It connect to www. hac. il Then this becomes GET /people/solange/index. html HTTP/1. 0 [headers etcetera] 4

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: : 19970916: : extensions to HTM <HTML> 5

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 1 xx -- informational 2 xx -- success. 200 3 xx -- redirection. 4 xx -- client side failure. Things like bad urls, 5 xx -- server side failure Response headers Message Body Actual response to asking www. cs. huji. ac. il for OPTIONS 6

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…) 8

Forms : מומלץ לחזור על טפסים • Form: http: //www. w 3 schools. com/html/tryit.

Forms : מומלץ לחזור על טפסים • Form: http: //www. w 3 schools. com/html/tryit. asp? filename=tryhtml_form_ text • Radio buttons: http: //www. w 3 schools. com/html/tryit. asp? filename=tryhtml_form_ radio • The submit button: http: //www. w 3 schools. com/html/tryit. asp? filename=tryhtml_form_ submit • Full tutorial: http: //www. w 3 schools. com/html_forms. asp 9

HTTP Methods : תזכורת : טפסים של method ב • הבדלים • POST: •

HTTP Methods : תזכורת : טפסים של method ב • הבדלים • 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) 10

We have a html page including a form, where the ACTION is the servlet

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) לרכיב הפניה שרת בצד (URL) 12

1. the servlet class must extends Http. Servlet 2. There are 2 methods, do.

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 (what happens if we don’t? ) Servlet : הערה . html ליצירת מיועד לא ? עושים מה אז את לכתוב אפשר זה בשלב ולעשות בנפרד html ה “include” MVC על נלמד בהמשך - ל controller בין והפרדה view output 13

Http. Servlet Request Handling GET request Web Server Http. Servlet subclass Servlet. Request do.

Http. Servlet Request Handling GET request Web Server Http. Servlet subclass Servlet. Request do. Get() Servlet. Response לקוח service() POST request Servlet. Request do. Post() Servlet. Response Request/response Contains streams 14

The Http. Servlet Interface המתודות את • ממשש • • do. Get() handles GET

The Http. Servlet Interface המתודות את • ממשש • • do. Get() handles GET requests do. Post() handles POST requests do. Put() handles PUT requests do. Delete() handles DELETE requests do. Head() handles HEAD requests (get headers only) do. Trace() handles TRACE requests (debug) service() the main receiver: dispatch to all methods above Generic. Servlet- מ • יורש 17

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

(base class) Servlet. Request Interface public abstract int get. Content. Length() public abstract String get. Content. Type() public abstract String get. Scheme() public abstract String get. Server. Name() int get. Server. Port() String get. Remote. Addr() String get. Remote. Host() Size and MIME type http, https, or ftp client and server Host info 18

Http. Servlet. Request Interface public Enumeration get. Header. Names() String get. Header(String name) int

Http. Servlet. Request Interface public Enumeration get. Header. Names() String get. Header(String name) int get. Int. Header(String name) long get. Date. Header(String name) public String get. Request. URI() Public String get. Query. String() public String get. Method() Http headers http: //foo. bar/a. html returns: /a. html http: //foo. bar/a? b=x&c=y returns: b=x&c=y GET / POST / PUT / etc. . public abstract String get. Parameter(String name) public abstract String[] get. Parameter. Values(String name) public abstract Enumeration get. Parameter. Names() public abstract Object get. Attribute(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() (Client) Parameters (form input data etc. . ) (Server) Parameters יחד מידע מעבירים כאשר אחר servlet- ל request- ה עם Cookies session 19

? Response- מה כלול ב צריך . לדפדפן תוכן להחזיר המאפשר Http. Servlet. Response

? Response- מה כלול ב צריך . לדפדפן תוכן להחזיר המאפשר Http. Servlet. Response אוביקט • זהו : ללקוח לשלוח שרוצים תוכן לסוג בהתאם לבחור (html or JSON )לדוגמא טקסט כתיבת : get. Writer • ( תמונה )לדוגמא בינארית כתיבת : get. Output. Stream • (? )למה ! תוכן ששולחים לפני headers- ה שדות את לכוון מאוד • חשוב • Set header data before you start writing into the response stream!! • For example set. Content. Type to specifiy the text/html format • once you have written into the response stream, headers are automatically sent, therefore you cannot change them! : נפוצה טעות תוכן שליחת שינוי לפני ללקוח headers 20

Http. Servlet. Response Interface public void send. Error(int set. Status(int sc, String msg) throws

Http. Servlet. Response Interface public void send. Error(int set. Status(int sc, String msg) throws IOException sc, String sm) sc) public boolean contains. Header(String name) void set. Header(String name, String value) void set. Int. Header(String name, int value) void set. Date. Header(String name, long date) Static ints defined in Http. Servlet. Response are used as arguments here (and you can either use the default message or substitute your own). 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 public void add. Cookie(Cookie cookie) public String encode. URL(String url) public String encode. Redirect. Url(String url) Redirect the CLIENT (in NODEJS-express we used response. redirect()) Argument must be an absolute URL 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) 21

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 (when? ) • 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 • Implemented by almost everyone: • A single instance of the servlet persists until the . class file is altered • It handles all the requests 23

How can you handle states? מצבים ניהול : • תזכורת • Look at the

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 • Cookies • sessions 25

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 26

Servlet. Config servlet כל עבור נוצר זה • אוביקט למסד התחברות פרטית לדוגמא -

Servlet. Config servlet כל עבור נוצר זה • אוביקט למסד התחברות פרטית לדוגמא - היתחול של פרמטריים ממנו לחלץ • ניתן נתונים : מקומות משתי באחד זמין הזה • מידע • 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. public Servlet. Context get. Servlet. Context() public String get. Init. Parameter(String name) public Enumeration get. Init. Parameter. Names() get. Init. Parameter(String name) 27

Servlets מנת להריץ על מה נדרש Java + Servlets ב התומך web • שרת

Servlets מנת להריץ על מה נדרש Java + Servlets ב התומך web • שרת • tomcat • Glassfish • Servlets require some configuration to be defined, you 2 options: • Insert the parameters in the web. xml file • Use annotations (preferred option) 28

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

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

Creating a Servlet project (intelli. J) (java/tomcat של מקומיות ההתקנות עם )תאום טכניות בעיות

Creating a Servlet project (intelli. J) (java/tomcat של מקומיות ההתקנות עם )תאום טכניות בעיות על סרטון כולל – הקורס באתר סרטונים ראו • Tomcat and Java 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 30

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. users request response Web Server + Servlet container tomcat The Servlet container maintains a bounded pool of worker threads to handle requests. thread Servlet A Your code Servlet B Servlet C request. set. Attribute(. . ) // addd extra params dispatcher. forward(request, response) // forward to other servlet website tomcat response. add. Cookie(…) request. get. Cookies() session. set. Attribute(…) object session. get. Attribute(…) session object 31

Links • Java Enterprise Edition (EE 8) API DOC: • https: //javaee. github. io/javaee-spec/javadocs/overview-summary.

Links • Java Enterprise Edition (EE 8) API DOC: • https: //javaee. github. io/javaee-spec/javadocs/overview-summary. html • http: //courses. coreservlets. com/Course-Materials/csajsp 2. html • https: //www. tutorialspoint. com/servlets/index. htm • https: //www. javatpoint. com/servlet-tutorial 32