Servlets by Kamalakar Dandu

* The preview only display some random pages of manuals. You can download full content via the form below.

The preview is being generated... Please wait a moment!
  • Submitted by: Kamalakar Dandu
  • File size: 2.6 MB
  • File type: application/pdf
  • Words: 2,890
  • Pages: 77
Report / DMCA this file Add to bookmark

Description

Objectives • Understand the Servlet Architecture. • Compare Servlet & Other Similar technologies. • Understand the Servlet Life Cycle. • Handle Request & Response. • Generate Dynamic HTML. • Handle Sessions.

Evolution of Dynamic Content Tech.

• • • • • • •

Common Gateway Interface (CGI) ColdFusion (Allaire) Active Server Pages (ASP) Server-Side JavaScript (SSJS) Personal Home Page tools (PHP) Java Servlets JavaServer Pages

The CGI Life Cycle Main Process Request for CGI 1

Child Process for CGI 1

Request for CGI 2

Child Process for CGI 2

Request for CGI 3

Child Process for CGI 3

CGI-Based Web Server

Java Servlet A Java program that extends the functionality of a Web server, generating dynamic content and interacting with Web clients using a request response paradigm.

J2EE 1.2 Architecture

An extensible Web technology that uses template data, custom elements, scripting languages, and server-side Java objects to return dynamic content to a client. Typically the template data is HTML or XML elements. The client is often a Web browser.

Advantages of Servlets • Java™ objects which extend the functionality of a HTTP server(a big plus). • Dynamic customization of content • Platform and server independent • No CGI limitations • better performance • Easier to write than CGI code  no need to parse headers and get info (all that is done by the HttpServlet class ) • No Networking restrictions (like applets) • Do not create a new process (or Servlet for every request) • Servlets can persist over time

Server Extensions Enhance or Change the base functionality of the server, allowing the server to handle tasks that were once relegated to external CGI programs.

The Power of Servlets • • • • • • •

Portability Power Efficiency and Endurance Safety Elegance Integration Extensibility and Flexibility

The Servlet Life Cycle • A web server communicates with a Servlet through a simple interface, javax.servlet.Servle t. This interface consists of three main methods: • init() • service() • destroy() and two ancillary methods: • getServletConfig() • getServletInfo()

Servlet Life Cycle (contd)

Request for Servlet1

Request for Servlet2

Main Process Thread JVM Servlet1 Thread Thread Servlet2

Request Servlet1 Servletforinitialized once; reused until destroyed and

garbage collected.

Java Servlet-based Web Server

Servlet Life Cycle (contd)

Life Cycle Of A Servlet (contd) • A servlet is constructed and initialized. It then services zero or more requests until the service that it extends shuts down • Initialized only once, stays resident in memory while servicing requests • Multiple threads of execute service(), one for each client connection • The servlet interface defines the life cycle methods :  init()  service()  destroy()

init() Method • Called by server immediately after servlet is instantiated • Called only once • Servlet creates and initializes the resources needed for handling requests

• public void init(ServletConfig config) throws ServletException; ServletException - thrown when servlet cannot initialize necessary resources

service() Method • It is the heart of the servlet. • It handles all requests sent by a client. • Each request message from a client results in a single call to the servlet's service() method. • It reads the request and produces the response message • public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException;

destroy() Method • This signifies the end of a servlet’s life. • It’s also a good place to save any persistent information that will be used the next time the servlet is loaded. • It is called to allow the servlet to clean up any resources. • Public void destroy();

Servlet Life Cycle (contd) Servlet loaded on demand (first time user accesses the servlet). Once loaded the servlet is in memory init() Client requests arrive service() Unloaded on closing server; manual unloading

destroy() each client request creates a new thread with service

Servlet Interface

• Servlets Classes / Interfaces are available in packages (in java servlet development kit) – javax.servlet.http – javax.servlet

Servlet Interface (contd)

GenericServlet Class Server

request

GenericServlet subclass

service()

response

KEY :

implemented by subclass

A generic servlet handling a request

A Http Servlet Handling a Request HTTP request

HttpServlet subclass

Web Server

GET request response POST request response HEAD request response

doGet()

service()

doPost() doHead()

Implementation of doGet() doPost()… is to return an error to the calling client if servlet does these KEY : not override implemented by methods. subclass

Generic servlet vs httpservlet service

init Generic Servlet

doGet(...) doPost(...) doPut(…)

extends

destroy

doOptions(…)

HttpServlet

doDelete(…) doTrace(…)

What does the Server Receive server

Searching Found www.mcp.com for www.mcp.com

client GET /index.html HTTP/1.0

Server receives only one of the HTTP request methods (Get/Post)

http://www.mcp.com/index.html

Servlet programmers must provide implementations for these requests

Web server recieves GET /servlet/myHelloServlet HttpServlet subclass Check request type Web Server it is “GET” doGet() hence call doGet()

GET/servlet/ myHelloServlet HTTP/1.0

service()

doPost()

Web server uses logic: doHead() myHelloServlet is loaded. If not , then load the servlet. call service method (already implemented in HttpServlet) (it checks the request type and correspondingly calls the doGet() or doPost() method )

javax.servlet

java.io InputStream

ServletInputStream

OutputStream

Servlet ServletConfig

ServletOutputStream

ServletContext Serializable ServletRequest java.lang

ServletResponse Object

GenericServlet SingleThreadModel

Exception

KEY Class

ServletException

ABSTRACT CLASS

Interface

UnavailableException extends

implements

Servlet javax.servlet.*

GenericServlet

service(req, res)

ServletRequest

ABSTRACT CLASS

Serializable

ServletResponse

ServletInputStream

Class

ServletConfig

ServletOutputStream

Interface

implements

ServletContext / ServletConfig • ServletConfig – used to get initialization parameters • getServletContext() • String getInitParameter(String) • Enumeration getInitParameterNames() • ServletContext – useful for logging & finding out about the other servlets • Servlet getServlet(String) • Enumeration getServlets() • Enumeration getServletNames() • void log(String) • void log(Exception, String)

GenericServlet

javax.servlet.http.*

HTTPServlet

Class

Interface

ABSTRACT CLASS

Serializable

extends

implements

Servlet Architecture Servlet

Methods for managing a servlet and communicating with clients

HTTPServlet

Interface

class

extends

Encapsulates communication from client to server ServletRequest

GET request Servlet

response ServletResponse Encapsulates communication from server to client

package codecamp; A Simple Code Example import javax.servlet.*; import javax.servlet.http.*; import java.io.*; Public class ServletGet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("First Servlet"); out.println("Hello Code Camp! "); } }

Example Write the following html file: mydisplay.html calling servlets


Click on the button “call servletGet” and note that the earlier servlet is called.

NOTE:User clicked on button, and the browser then Eg: mydisplay.html generated the GET method based on “action” settings.

Generating GET by clicking a button on browser server

Searching Found localhost for localhost

client GET /servlet/servletGet /mydisplay.html HTTP/1.0 HTTP/1.0

http://localhost…/…/mydisplay.html

call servletGet

Example Modify only the following line in html file: mydisplay.html



Click on the button “call servletGet” and note what happens.

NOTE:User clicked on button, and the browser then generated the POST method based on “action” settings. NOTE: the servlet servletGet did not contain a doPost method and hence got the error. Rename doGet() to doPost() and it would then work.

Transferring info from browser to Servlets • Generally in web pages, users fill up a form with fields. • Browser communicates with server (servlets) through GET and POST methods • GET requests : • – Getting information • – Appended to the URL in a query string ( limited • amount of data) • – .../servlet/ViewCourse?name=servlets_codecamp • – Can be bookmarked and emailed • POST requests: • – Sending information • – Send any amount of data • – .../servlet/PlaceOrderProcess • – Can Not be bookmarked and emailed. • – Use POST for things like placing an order.

Common Requests: GET and POST • GET • – Getting information • – Appended to the URL in a query string ( limited amount of data) • .../servlet/ViewCourse?name=servlets_codecamp • – Can be bookmarked and emailed • POST requests: • Sending information • – Send any amount of data • – .../servlet/PlaceOrderProcess • – Can Not be bookmarked and emailed. • – Use POST for things like placing an order.

Example Write a html with three text fields for name, id and location, with a submit button. Set the form method as „GET‟, and action as „servlet/servletGetParam‟

Eg: servlet_get_HTML.html Write a servlet with doGet() method. In the doGet() method read the parameters and then send it back to the browser for display

Eg: servletGetParam.java

Example Write a html with three text fields for name, id and location, with a submit button. Set the form method as „POST‟, and action as „servlet/servletGetParam‟

Eg: servlet_post_HTML.html Write a servlet with doPost() method. In the doPost() method read the parameters and then send it back to the browser for display

Eg: servletPost.java

Interface ServletRequest – information about the client • name of the host and the IP address of client • parameters sent from the client browser • scheme used by the browser to communicate to servlet (eg. http; https; ftp;…..) • protocol used by client (eg. ftp) • access to the ServletInputStream (which allows servlet to read binary data from the client ) – information about server • name of the server • port used by the server

ServletRequest… • Subclass ServletRequest to provide protocol specific information • Example: HTTPServletRequest (extends ServletRequest )supports methods to retrieve more protocol specific headers (getMethod() to identify the type of request)

javax.servlet.ServletRequest class Name public abstract methods

ServletRequest

String getContentType() ServletInputStream getInputStream() String getParameter(String) Enumeration getParameterNames() String getProtocol() BufferedReader getReader() String getRemoteAddr() String getServerName() int getServerPort() String getScheme() String getRealPath() String getCharacterEncoding() Object getAttribute()

interface HTTPServlet • Information from client  additional path info (sent along with request) • eg /servlet/myservlet/dict/defn.txt • “/dict/defn.txt” is the additional info to the servlet myservlet • within your servlet use getPathInfo() (null if no such data is available)  what was requested (file/ servlet/)  HTTP headers sent by the client • Connection, User-Agent, host, Accept, Acceptlanguage, Accept-Charset

HTTP Headers • General : Information not related to Client, Server or HTTP protocol. • Request : Preferred Document formats and server parameters. • Response : Information about the server. • Entity : Information on the data that is being sent between the client and server.

javax.servlet.http.HttpServletRequest Class Name public abstract methods

HTTPServletRequest extends ServletRequest Enumeration getHeaderNames() long getDateHeader(String) String getPathInfo() String getQueryString() String getRemoteUser() String getAuthType() Cookie[ ] getCookies() String getRequestURI() String getServletPath() String getSession() boolean isRequestedSessionIdFromCookie() boolean isRequestedSessionIdFromUrl()

Example Write a servlet that implements the doGet() method. Capture the information encapsulated in the request object (in ServletRequest and HTTPServletRequest), and send this info back to the client.

Eg: helloservletGet.java

ServletResponse Interface • Allows the servlet to reply to the client • Allows the servlet to set the content length and MIME type • Provides a handle to ServletOutputStream (or Writer) to send data to the client • Subclass HTTPServletResponse supports methods to set more protocol specific headers

javax.servlet.ServletResponse Class Name ServletResponse public void setContentLength(int) abstract void setContentType(String); ServletOutputStream getOutputStream() methods PrintWriter getWriter() String getCharacterEncoding(String)

javax.servlet.http. HttpServletResponse Class Name public abstract methods

HTTPServletResponse void addCookie(http.Cookie) boolean containsHeader(String); String encodeURL(String) String encodeRedirectURL(String) String encodeUri(String) String encodeRedirectUri(String) void setHeader(String,String) void setIntHeader(String,int) void setDateHeader(String,long) void setStatus(int,String) void sendError(int,String) void sendRedirect(String)

Redirecting … • Redirection can be set using the following methods in the HttpServletResponse class – setStatus(status code) • status codes available in the HttpServletResponse class as static variables – setHeader(“Location”, “ give new site location here”) • the new location must be an absolute url path – setHeader(“Refresh”, “3”) will tell the browser for 3 seconds before refreshing the page – setHeader(“Refresh”, “3; URL=…..”) will tell the browser for 3 seconds before going to the new location specified in the command.

Generating HTML • Hardcoded in the program (servletGet.java) • Using an HTML generator (require additional software; html generation classes) • Using an HTML generator creatively

Eg : ServletGet.java

Redirecting a Request • Servlet can use status codes and headers to inform a client to use another URL. It is useful when  document (html file) has moved.  load balancing is required. (one machine can distribute the load to many machines)

Abstract class HTTPServlet class Name HTTPServlet extends GenericServlets implements

Serializable protected void doGet(HttpServletRequest, HttpServletResponse) methods long getLastModified(HttpServletRequest);

void doPost(HttpServletRequest, HttpServletResponse) void doPut(HttpServletRequest, HttpServletResponse) The service method supports HTTP 1.0 void doDelete(HttpServletRequest, HttpServletResponse) protocol.void This method dispatchesHttpServletResponse) each request doOptions(HttpServletRequest, void doTrace(HttpServletRequest, HttpServletResponse) to the method designed to handle it. void service(HttpServletRequest, HttpServletResponse) public void service(ServletRequest, ServletResponse)

All methods throws ServletException and IOException

Overriding Methods • Servlet writer who wants to handle the GET and the HEAD (HTTP protocol) must override the doGet() method in the servlet. • Similarly override – doPost() method to handle POST request – doPut() method to handle PUT requests – doDelete() method to handle DELETE requests

Notes • Servlets are fundamentally multithreaded, hence can run multiple service() methods. • Therefore the code for service method must be thread safe. • If you do not want a multithreaded server then one must implement the SingleThreadedModel interface.

Example Write a counter servlet that counts the number of clients served.

Eg: MyCounterServ.java Modify the above servlet so that if many users are accessing the variable count, it should be synchronized.

Eg: MyCounterServSyn.java

Example Write a servlet that informs the client that the site has moved, and allow let the browser go to the new url automatically after 9 seconds.

Eg: RelocateServlet.java

Request Dispatcher • The basic use of a RequestDispatcher: One can effectively use the RequestDispatcher to call a JSP from a servlet or a servlet from another servlet. RequestDispatcher rd = getServletContext().getRequestDispatcher(" /welcome.jsp");

rd.include(request, response);

Sending Multimedia Content • To send an image that is available with the server to the client  open a stream to the client browser  open the local image file  read block of bytes/ or byte by byte of image  send information to server by writing to the stream

Example Write a serlvet that sends an image to the browser. Image file must be on the server system.

Eg: servletImage.java Problem: If we write 2 images to the application, it will read only the first one. Hence, one can send only one image at a time.

Example Write a serlvet that sends 2 tags to the client. The client would load one image after another and display both of them.

Eg: servletImageHTML.java Note: All the Solution: senddata the to html be sent tag , in a and the browser will open connection byteArrayOutputStream and and sent get all at theonce. information This is from server. buffering butThis could way slow anydown number when oflot images of information can be is passed.sent to the client. being

User Authentication • Specify in the resource list • servlet resource/ and what type of authentication • once set, then the browser gives a dialog box and then sends the name and password to the servlet

Eg: secureServlet.java

Session Tracking • Mechanism to maintain a state about a series of requests from the same user (request originating from same browser) • Sessions are shared across servlets • HttpSession Object  Can Store (name, value) Pairs.  Persistence and disk swapping through Object Serialization.  Works across protocols (HTTP/HTTPS).  Session validity, Creation time etc.

Session Tracking (contd) procedures in session tracking • get a HttpSession object for a user  HttpSession ss = new HttpSession(true) true means that if it a new session create a new session object, otherwise get session id. • store/get data from the HttpSession object  void ss.putValue(String name, Object val)  Object ss.getValue(String name)  void ss.removeValue(String name) • Invalidate the session  ss.invalidate();

Count Example using Session Write a servlet that uses session api to track the number of times a user has visited the site.

Eg: SessionDemo.java

Ways of Session-Tracking • Hidden Form Fields • Persistent Cookies • Servlet API

Security Issues • The Servlet Sandbox • Access Control Lists (ACLs)

Servlet Sandbox • It is an area where Servlets are given restricted authority on the server. • They may not have access to the file system or network, or they may have been granted a more trusted status. • It is up to the web server administrator to decide which servlets are granted this status.

Access Control Lists • An ACL is a list of users who are allowed to perform a specific function in the server. The list specifies:  What kind of access is allowed  What object the access applies to  Which users are granted access

Servlet Environment • Inter-Servlet Communication How to call a method of another Servlet

Servlet Environment (contd) • Communication with Active Server Resources  How to call another Servlet (or any other kind of active resource) to process a request • Accessing Passive Server Resources  How to access a resource in the server's document tree • Accessing Servlet Resources  How to access resources which belong to a Servlet • Sharing Data Between Servlets  How to share data between Servlets

Invoking a Servlet From an Applet HTTP Request thru DataOutput created by URLCorrection object

Formatted results thru DataInputStream object created by URLConnection object SQL Query ResultSet Object

Exercise (contd..) • 20. Due to the implementation of the application on the AWT framework it is required to install the JRE software & the required application components on each machine which needs to communicate with the application. A better alternative would be to implement the same in a http based server architecture,(repeat exercises 1 to 5 here)[20]

ThankQ