Beruflich Dokumente
Kultur Dokumente
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
Servlets
Client
Server
Static
File system
HTTP
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
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
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()
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
HttpServletResponse
Specify the MIME type of the response
.setContentType(image/gif); Called before .getWriter() so correct Charset is used
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);
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)
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
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-