Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the...

19
Java Servelets Java Servelets

Transcript of Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the...

Page 1: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

Java ServeletsJava Servelets

Page 2: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

What Is a Servlet? What Is a Servlet?

A A servletservlet is a Java programming language class used to is a Java programming language class used to extend the capabilities of servers that host applications extend the capabilities of servers that host applications accessed via a request-response programming model. accessed via a request-response programming model.

Although servlets can respond to any type of request, they Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by are commonly used to extend the applications hosted by Web servers.Web servers.

For such applications, Java Servlet technology defines For such applications, Java Servlet technology defines HTTP-specific servlet classes. HTTP-specific servlet classes.

The The javax.servletjavax.servlet and and javax.servlet.httpjavax.servlet.http packages packages provide interfaces and classes for writing servlets.provide interfaces and classes for writing servlets.

All servlets must implement the All servlets must implement the ServletServlet interface, which interface, which defines life-cycle methods. defines life-cycle methods.

When implementing a generic service, you can use or When implementing a generic service, you can use or extend the extend the GenericServletGenericServlet class provided with the Java class provided with the Java Servlet API. Servlet API.

The The HttpServletHttpServlet class provides methods, such as doGet class provides methods, such as doGet and doPost, for handling HTTP-specific services. and doPost, for handling HTTP-specific services.

Page 3: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

A servlet is a server side software A servlet is a server side software component, written in java that component, written in java that dynamically extends the functionality dynamically extends the functionality of a server.of a server.

Unlike applets servlets don’t display Unlike applets servlets don’t display GUI.GUI.

It works behind the scene on server It works behind the scene on server and results of servlet’s processing are and results of servlet’s processing are returned to the client.returned to the client.

Page 4: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

Advantages Advantages Capable of running in same process space a the Capable of running in same process space a the

web server.web server. Compiled.Compiled. Crash resistantCrash resistant Cross platformCross platform DurableDurable Dynamically loaded across the networkDynamically loaded across the network ExtensibleExtensible MultithreadedMultithreaded Protocol independentProtocol independent Written in javaWritten in java

Page 5: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

FunctionsFunctions

Dynamically build and return an Dynamically build and return an HTML file based on client request.HTML file based on client request.

Process user input of HTML Form and Process user input of HTML Form and return appropriate response.return appropriate response.

Facilitate communication among Facilitate communication among many clients.many clients.

Interact with server resources like Interact with server resources like database, other application.database, other application.

Multiplayer games.Multiplayer games.

Page 6: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

Advantage of Servlets Over Advantage of Servlets Over CGICGI

Java servlets are more efficient, easier to use, more powerful, more Java servlets are more efficient, easier to use, more powerful, more portable, and cheaper than traditional CGI and than many alternative CGI-portable, and cheaper than traditional CGI and than many alternative CGI-like technologies. (More importantly, servlet developers get paid more than like technologies. (More importantly, servlet developers get paid more than Perl programmers :-). Perl programmers :-).

Efficient.Efficient. – With traditional CGI, a new process is started for each HTTP request. With traditional CGI, a new process is started for each HTTP request. – If the CGI program does a relatively fast operation, the overhead of starting the If the CGI program does a relatively fast operation, the overhead of starting the

process can dominate the execution time. process can dominate the execution time. – With servlets, the Java Virtual Machine stays up, and each request is handled by With servlets, the Java Virtual Machine stays up, and each request is handled by

a lightweight Java thread, not a heavyweight operating system process. a lightweight Java thread, not a heavyweight operating system process. – Similarly, in traditional CGI, if there are Similarly, in traditional CGI, if there are NN simultaneous request to the same CGI simultaneous request to the same CGI

program, then the code for the CGI program is loaded into memory N times. program, then the code for the CGI program is loaded into memory N times. – With servlets, however, there are With servlets, however, there are NN threads but only a single copy of the servlet threads but only a single copy of the servlet

class. Servlets also have more alternatives than do regular CGI programs for class. Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations, keeping database optimizations such as caching previous computations, keeping database connections open, and the like. connections open, and the like.

Convenient.Convenient. – You already know Java. You already know Java. – Why learn Perl too? Besides the convenience of being able to use a familiar Why learn Perl too? Besides the convenience of being able to use a familiar

language, servlets have an extensive infrastructure for automatically parsing language, servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and setting HTTP headers, handling and decoding HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such utilities. cookies, tracking sessions, and many other such utilities.

Page 7: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

Powerful.Powerful. – Java servlets let you easily do several things that are difficult or impossible with Java servlets let you easily do several things that are difficult or impossible with

regular CGI. regular CGI. – For one thing, servlets can talk directly to the Web server (regular CGI programs For one thing, servlets can talk directly to the Web server (regular CGI programs

can't). can't). – This simplifies operations that need to look up images and other data stored in This simplifies operations that need to look up images and other data stored in

standard places. standard places. – Servlets can also share data among each other, making useful things like database Servlets can also share data among each other, making useful things like database

connection pools easy to implement. connection pools easy to implement. – They can also maintain information from request to request, simplifying things like They can also maintain information from request to request, simplifying things like

session tracking and caching of previous computations. session tracking and caching of previous computations. Portable.Portable.

– Servlets are written in Java and follow a well-standardized API. Servlets are written in Java and follow a well-standardized API. – Consequently, servlets written for, say I-Planet Enterprise Server can run virtually Consequently, servlets written for, say I-Planet Enterprise Server can run virtually

unchanged on Apache, Microsoft IIS, or WebStar. unchanged on Apache, Microsoft IIS, or WebStar. – Servlets are supported directly or via a plugin on almost every major Web server. Servlets are supported directly or via a plugin on almost every major Web server.

Inexpensive.Inexpensive. – There are a number of free or very inexpensive Web servers available that are good There are a number of free or very inexpensive Web servers available that are good

for "personal" use or low-volume Web sites. for "personal" use or low-volume Web sites. – However, with the major exception of Apache, which is free, most commercial-However, with the major exception of Apache, which is free, most commercial-

quality Web servers are relatively expensive. quality Web servers are relatively expensive. – Nevertheless, once you have a Web server, no matter the cost of that server, adding Nevertheless, once you have a Web server, no matter the cost of that server, adding

servlet support to it (if it doesn't come preconfigured to support servlets) is generally servlet support to it (if it doesn't come preconfigured to support servlets) is generally free or cheapfree or cheap

Page 8: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

Servlet APIServlet API It doesn’t run as an application rather it is loaded in It doesn’t run as an application rather it is loaded in

memory and as instance is created.memory and as instance is created. When a servlet instance is created its init() is When a servlet instance is created its init() is

called.called. Servlets are required to respond to new Servlets are required to respond to new

connections to the server.connections to the server. When a new connection is detected, a call is made When a new connection is detected, a call is made

to the service() of the servlet.to the service() of the servlet. service() takes two parameters defined by interface service() takes two parameters defined by interface

type called ServletRequest and ServletResponse.type called ServletRequest and ServletResponse. Servlet class is abstract because service() is Servlet class is abstract because service() is

defined not implemented; so to implement a defined not implemented; so to implement a servlet, it is necessary to override this method.servlet, it is necessary to override this method.

Page 9: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

Servlet class is not protocol specific.Servlet class is not protocol specific. A subclass of Servlet class, the HttpServlet A subclass of Servlet class, the HttpServlet

class is provided to handle http protocol.class is provided to handle http protocol. Two interfaces are defined for use with Two interfaces are defined for use with

HttpServlet classHttpServlet class– HttpServletRequestHttpServletRequest– HttpServletResponseHttpServletResponse

These extend the ServletRequest & These extend the ServletRequest & ServletResponse.ServletResponse.

Page 10: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

Life Cycle of ServletLife Cycle of Servlet

Servlet life cycle is defined by Servlet life cycle is defined by javax.servlet.Servlet inteface.javax.servlet.Servlet inteface.

All servlets must implement All servlets must implement javax.servlet.Servlet interface to run javax.servlet.Servlet interface to run in a servlet engine.in a servlet engine.

Page 11: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

Servlet Class

Instantiation & loadingServlet engine can

instantiate more than one servlet instance

Initializationinit(ServletConfig conf)

Readyservice()

A service() executes for each servlet instance

Destructiondestroy()

Garbage CollectionServer no longer

has a reference to the object

Page 12: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

Creating servletsCreating servlets

protected void protected void service(HttpServletRequest req, service(HttpServletRequest req, HttpServletResponse resp) throws HttpServletResponse resp) throws ServletException, IOExceptionServletException, IOException

Standard HTTP requests like Get and Standard HTTP requests like Get and Post are supported by doGet() and Post are supported by doGet() and doPost().doPost().

Page 13: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

HttpServletRequestHttpServletRequest

getMethod()getMethod()– Returns get/post with which request was made.Returns get/post with which request was made.

getQueryString()getQueryString() getRemoteUser()getRemoteUser() getRequestSessionId()getRequestSessionId() getSession(boolean)getSession(boolean)

– If FALSE returns current valid session otherwise If FALSE returns current valid session otherwise creates a new session.creates a new session.

isRequestedSessionIdValid()isRequestedSessionIdValid() getCookies()getCookies()

Page 14: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

HttpServletResponseHttpServletResponse

addCookie(Cookie)addCookie(Cookie)– Add cookie to responseAdd cookie to response

encodeUrl(String)encodeUrl(String) sendRedirect(String)sendRedirect(String) sendError(int)sendError(int)

Page 15: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

Cookie ClassCookie Class Cookie used for session management with Cookie used for session management with

HTTP and HTTPS.HTTP and HTTPS. Used to get browsers to hold small data Used to get browsers to hold small data

associated with user’s browsing.associated with user’s browsing. Cookies are named and have single value.Cookies are named and have single value. Assigned by the servers using fields added Assigned by the servers using fields added

to HTTP response headers.to HTTP response headers. Cookies are saved one at a time into HTTP Cookies are saved one at a time into HTTP

response headers using response headers using javax.servlet.http.HttpServletResponse.adjavax.servlet.http.HttpServletResponse.addCookie().dCookie().

Page 16: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

Web browsers are expected to Web browsers are expected to support 20 cookies per host of at least support 20 cookies per host of at least 4KB each.4KB each.

HTTP request fields are retrieved HTTP request fields are retrieved using using javax.servlet.http.HttpServletRequest.javax.servlet.http.HttpServletRequest.getCookie().getCookie().

This returns all cookies found in This returns all cookies found in request.request.

Page 17: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

Cookie ClassCookie Class

Cookie(String,String)Cookie(String,String) setDomain(String)setDomain(String) getDomain()getDomain() setMaxAge(int)setMaxAge(int)

– Age in sec; 0 to deleteAge in sec; 0 to delete getMaxAge()getMaxAge() setValue(String)setValue(String) getValue()getValue() getName()getName()

Page 18: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

ExampleExample FirstServlet.htmlFirstServlet.html FirstServlet.javaFirstServlet.java STEPSSTEPS Set Set

classpath=c:/jsdk2.0/lib/jsdk.jar;C:/jsdk2.0/srclasspath=c:/jsdk2.0/lib/jsdk.jar;C:/jsdk2.0/srcc

Compile .java fileCompile .java file– .class file should be in example directory.class file should be in example directory

Run servletrunnerRun servletrunner Run FirstServlet.html in browserRun FirstServlet.html in browser

– C:\JSDK2.0\examples\FirstServlet.htmlC:\JSDK2.0\examples\FirstServlet.html

Page 19: Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.

Survey.htmlSurvey.html Survey.javaSurvey.java