Java Servlet

Views:
 
     
 

Presentation Description

No description available.

Comments

By: anandhi.28282 (14 month(s) ago)

Hello Mr.Prasad,The Servlet presentation was good.It would be useful to me if WASCE eclipse is used instead of Tomcat..And do you have JSP & Struts Presentations.If so,can u please send me at anandhi.28282@gmail.com

Presentation Transcript

Mr.Prasad Sawant : 

Java Servlets Mr.Prasad Sawant

Resource Prerson : 

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

Acknowledgement : 

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

Java on the Web: J2EE : 

Java on the Web: J2EE Thin clients (minimize download) Java all “server side” Client Server

Where are Servlets? : 

Where are Servlets? HTTP Web Server File system ServletServer Static Dynamic

Java Servlet API : 

Java Servlet API The predominant language for server-side programming 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 response- returned to user

Servlet Life Cycle : 

7 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 : 

8 Life Cycle Schema

Servlet Life Cycle : 

9 Servlet Life Cycle Servlet Class Initialization and Loading Calling the init method Servicing requests by calling the service method Destroying the servlet by calling the destroy method Garbage Collection ServletConfig

Servlet Basics : 

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) : 

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 : 

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

GenericServlet : 

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

HttpServlet : 

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 : 

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 doesn’t know getServletInfo() method Returns String for logging purposes

Web Applications : 

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 : 

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

Servlet Path Mappings : 

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 : 

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 uses 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 : 

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 : 

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 : 

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 Can’t be reloaded browsers treat them specially, ask user

HttpServletResponse : 

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 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 : 

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 backd.include(req, resp); Or forward – doesn’t come back d.forward(req, resp); Request dispatching is Different from sendRedirect() browser not involved from user perspective, URL is unchanged

Cookies : 

Cookies Persistent client-side storage of data known to server and 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 : 

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 the server Server creates object javax.servlet.http.HttpSession

Session : 

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 : 

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

Directory Structure : 

Directory Structure

Directory Structure (cont.) : 

Directory Structure (cont.)

Slide 31: 

<?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation= "http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <description>Examples</description> <display-name>Examples</display-name> <servlet> <servlet-name>Hellox</servlet-name> <servlet-class>Hellox</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hellox</servlet-name> <url-pattern>/Hellox</url-pattern> </servlet-mapping> </web-app> Declares servlet abbreviation

Slide 32: 

Thank You