Sie sind auf Seite 1von 32

Java Servlets

Mr.Prasad Sawant

Resource Prerson

Mr.Prasad M.Sawant Qualification :M.Sc(Computer Science) :M.Sc(Computer Lecturer Dept BCA Prof.Ramkrushna More A.C.S College Akurdi http://prasadmsawant.blogspot.com/ Email :Sawanprasad@gmail.com :prasadsawant.rmacs@gmail.com

Acknowledgement
Mr.S.G.Lakhdive (H.O.D Computer Sci. Dept) Mrs .Rupali Jadhav(Computer Sci Dept) Jadhav(Computer Mrs.U.R.Ranawade(H.O.D BCA/BBA/MCA) Mrs.U.R.Ranawade(H.O.D

Java on the Web: J2EE


Thin clients (minimize download) Java all server side

Servlets

Client

Server

Where are Servlets? Servlets?

Static

File system

HTTP

Web Server Dynamic Servlet Server

Tomcat = Web Server + Servlet Server

Java Servlet API


The predominant language for server-side serverprogramming Standard way to extend server to generate dynamic content Web browsers are universally available thin clients Web server is middleware for running application logic User sends request server invokes servlet servlet takes request and generates responseresponsereturned to user

Servlet Life Cycle


No main() method! The server loads and initializes the servlet The servlet handles client requests The server can remove the servlet The servlet can remain loaded to handle additional requests Incur startup costs only once

Life Cycle Schema

Servlet Life Cycle


Servicing requests by calling the service method Calling the init method ServletConfig Initialization and Loading Destroying the servlet by calling the destroy method

Servlet Class

Garbage Collection
9

Servlet Basics
Packages: javax.servlet, javax.servlet.http Runs in servlet container such as Tomcat
Tomcat 4.x for Servlet 2.3 API Tomcat 5.x for Servlet 2.4 API

Servlet lifecycle
Persistent (remains in memory between requests) Startup overhead occurrs only once init() method runs at first request service() method for each request destroy() method when server shuts down

Common Gateway Interface (CGI)


Not persistent Not multithreaded Not high performancce Any language that can read standard input, write standard output and read environment variables Server sends request information specially encoded on standard input Server expects response information on standard output

Writing servlets
public class MyServlet extends javax.servlet.GenericServlet { public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { Resp.SetContentType(text/plain); } }

GenericServlet
public class MyServlet extends javax.servlet.GenericServlet { public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { resp.SetContentType(text/plain); } }

HttpServlet
public class MyServlet extends javax.servlet.http.HttpServlet { public void doGet(ServletRequest req, ServletResponse resp) throws ServletException, IOException { resp.SetContentType(text/plain); PrintWriter out = resp.getWriter(); out.println(Hello, world); } public void doPost(ServletRequest req, ServletResponse resp) throws ServletException, IOException { doGet(req, resp); }

HttpServlet
doPost does three things
Set output type text/plain MIME type getWriter() method for out stream Print on out stream

getLastModified() method
To cache content if content delivered by a servlet has not changed Return Long =time content last changed Default implementation returns a negative number servlet doesnt know

getServletInfo() method
Returns String for logging purposes

Web Applications
Consists of a set of resources including
Servlets, Static content, JSP files, Class libraries

Servlet context,
a particular path on server to identify the web application Servlets have an isolated, protected environment to operate in without interference ServletContext class where servlets running in same context can use this to communicate with each other Example servlet context: /catalog request.getContextPath() + /servlet/CatalogServlet

Web App Structure


Directory tree
Static resources: / Packed classes: /WEB-INF/lib/*.jar /WEBUnpacked classes: /WEB-INF/classes/*.class /WEBDeployment descriptor: /WEB-INF/web.xml /WEB Configuration information for the servlets including Names, servlet (path) mapprings, initialization parameters, contextcontext-level configuration

Servlet Path Mappings


Servlets are not files, so must be mapped to URIs (Uniform Resource Identifiers) Servet container can set default, typically /servlet/* Example: /servlet/MyPacPageServlet can invoke PageServlet.class Mapping by Exact path: /store/chairs Prefix: /store/* Extension: *.page A servlet mapped to / path becomes the default servlet for the application and is invoked when no other servlet is found

Servlet Context Methods


Resources such as index.html can be accessed through web server or by servlet
Servlet uses request.getContextPath() to identify its context path, for example: /app Servlet uses getResource() and getResourceAsStream(request.getContextPath() + /index.html)

To retrieve context-wide initialization parameters, servlet contextuses getInitParameter() and getInitParameterNames() To access a range of information about the local environment, shared with other servlets in same servlet context, servlet uses getAttribute(), setAttribute(), removeAttribute(), getAttributeNames()

HttpServletRequest interface
Server creates object implementing this interface, passes it to servlet. Allows access to URL info: getProtocol(), getServerName(), getPort(), getScheme() User host name: getRemoteHost() Parameter info: (variables from input form): .getParameterNames(), getParameter() HTTP specific request data: getHeaderNames(), getHeader(), getAuthType()

Forms and Interaction


<form method=get action=/servlet/MyServlet>
GET method appends parameters to action URL: /servlet/MyServlet?userid=Jeff&pass=1234 This is called a query string (starting with ?)

Username: <input type=text name=userid size=20> Password: <input type=password name=pass size=20> <input type=submit value=Login>

POST Method
<form method=post
Post method does not append parameters to action URL: /servlet/MyServlet Instead, parameters are sent in body of request where the password is not visible as in GET method

POST requests are not idempotent


From Mathematics an idempotent unary operator definition: whenever it is applied twice to any element, it gives the same result as if it were applied once. Cannot bookmark them Are not safely repeatable Cant be reloaded browsers treat them specially, ask user

HttpServletResponse
Specify the MIME type of the response
.setContentType(image/gif); Called before .getWriter() so correct Charset is used

Two methods for producing output streams:


Java.io.Printwriter out = resp.getWriter() ServletOutputStream str = resp.getOutputStream() //used for non-text responses non-

HTTP response headers and status code


setHeader(), containsHeader(), setStatus(), 200 OK, 404 Not Found, etc. sendError() sendRedirect(), sets Location header and status code for redirect. Causes browser to make another request.

RequestDispatcher
Can forward request to another servlet Can include bits of content from other servlets in its own response RequestDispatcher d = req.getRequestDispatcher(/servlet/OtherServlet);
Either include goes and comes back d.include(req, resp); Or forward doesnt come back d.forward(req, resp);

Request dispatching is Different from sendRedirect()


browser not involved from user perspective, URL is unchanged

Cookies
Persistent client-side storage of data known to server clientand sent to client Cookie is multiple names and values. Value limited to 4096 bytes has expiration date, and a server name (returned to same host and not to others) Cookie is sent in HTTP header of response
resp.addCookie(name,value)

Cookie is returned to server in HTTP header of subsequent request cookies = req.getCookies();


For (int i=0;i<cookies.length;i++) { cookies[i].getName cookies[i].getAttribute

Session Tracking
For tracking individual users through the site Application needs stateful environment whereas the web is inherently stateless Previously, applications had to resort to complicated code, using cookies, hidden variables in forms, rewriting URLs to contain state information Delegates most of the user-tracking functions to userthe server Server creates object javax.servlet.http.HttpSession

Session
Servlet uses req.getSession(true)
Boolean arg handles case if no current session object Should new one be created or not Session.isNew() useful to detect new session object

Servlet binds data to the HttpSession object with session.setAttribute(hits,new Integer(34)); Server assigns unique session ID, stored in a cookie If cookies are not available, server uses URL rewriting. To create links, with session ID use
resp.encodeURL(/servlet/View) or resp.encodeRedirectURL(/servlet/View)

Compiling
javac classpath $LIB/servlet$LIB/servlet-api.jar Hellox.java

Directory Structure
Create your web applications here

Create a directory D for your web application

Create WEB-INF under D Create classes under WEB-INF

Directory Structure (cont.)


Static content in D

Dynamic content in WEB-INF

web.xml in WEB-INF

Servlets in classes

<?xml version="1.0" encoding="ISO-8859-1"?> encoding="ISO-8859<web<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns="http://java.sun.com/xml/ns/j2ee" xsi:schemaLocation= xsi:schemaLocation= "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" http://java.sun.com/xml/ns/j2ee/webversion="2.4">

Declares servlet

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-

abbreviation
<description>Examples</description> <display-name>Examples</display-name> <display-name>Examples</display<servlet> servlet> <servlet-name>Hellox</servlet-name> servlet-name>Hellox</servlet<servlet-class>Hellox</servlet-class> servlet-class>Hellox</servlet</servlet> </servlet> <servlet-mapping> servlet<servlet-name>Hellox</servlet-name> servlet-name>Hellox</servlet<url-pattern>/Hellox</url-pattern> url-pattern>/Hellox</url</servlet-mapping> </web-app> </servlet</web-

Das könnte Ihnen auch gefallen