Description
all about servlets
SERVLETS
A servlet is a Java™ technology-based Web component, managed by a container that generates dynamic content. It is a server-side software program, written in Java code that handles messaging between a client and server, a program (running on a web server) that dynamically generates some output as its reaction to a request. Servlets can respond to client requests by dynamically constructing a response that is sent back to the client. A single servlet can be invoked multiple times to serve requests from multiple clients. A servlet can handle multiple requests concurrently and can synchronize requests. Servlets can forward requests to other servers and servlets.
The basic flow is this: 1. The client sends a request to the server. 2. The server instantiates (loads) the servlet and creates a thread for the servlet process. 3. The server sends the request information to the servlet. 4. The servlet builds a response and passes it to the server. 5. The server sends the response back to the client. The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle. Java Servlet Containers Apache Tomcat BEA WebLogic Server IBM WebSphere Application Server JBoss Application Server Oracle Application Server Sun Java System Application Server Platform Edition Role of an Application Server: A servlet engine runs within the application server and manages the servlet. It loads and initializes the servlet, passes requests and responses to the servlet and client, manages multiple instances of a servlet, and acts as a request dispatcher. It destroys the servlet at the end of its useful life. Servlets are unloaded and removed from memory when the server shuts down. How do you run a servlet? • Invoked as an explicit URL reference • Embedded in HTML and invoked from a Web application.
The Servlet Life Cycle •When the Servlet instance has been created, the container will call init() •Now the Servlet is ready for processing user requests – service() is called for processing a request – the Servlet remains loaded and ready after a request is processed •destroy() is called before a Servlet is deleted –time of deletion is not defined
The Servlet API The Java Servlet API defines a standard interface for the request and response messages between a Web client and a Web servlet. So your servlets can be portable across platforms and across different Web application servers. In essence, the API encases requests as objects so the server can pass them to the servlet; the responses are similarly encapsulated so the server can pass them back to a client. The Java Servlet API has two packages. javax.servlet contains classes to support generic protocolindependent servlets, and javax.servlet.http includes specific support for the HTTP protocol.
Prerequisites to excecute a servlet: Have an Application server installed (using Apache Tomact here):
myapplication/
contains auxiliary files (e.g. HTML, GIF, CSS, JSP files), can be in sub-directories contains deployment descriptor, web.xml contains Servlet class files (in appropriate sub-directories, if non-default package names) contains extra jar files
myapplication/WEB-INF/ myapplication/WEBINF/classes/ myapplication/WEB-INF/lib/
To Compile a servlet
> set classpath \tomcat\common\lib\servlet-api.jar;. > javac HelloWorld.java
Invoking a servlet by typing its address in the URL Using javax.servlet package( Generic Servlets)
Basic Servlet.java import javax.servlet.*; import java.io.*; public class BasicServlet extends GenericServlet { public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("Hello."); } }
web.xml file(Deployment Descriptor) <?xml version=”1.0” encoding=”ISO-8859-1”?> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>BasicServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/sayHello</url-pattern> </servlet-mapping> </web-app>
The Deployment Descriptor The /WEB-INF/web.xml file contains the Web Application Deployment Descriptor for your application. As the filename extension implies, this file is an XML document, and defines everything about your application that a server needs to know. The deployment descriptor: web.xml provides control of: • URL mapping (from URLs to files) • initialization parameters • timeout settings • directory listings • error pages • security constraints, client authentication • filters and listeners Using javax.servlet.http package To write an HTTP servlet for use on the Web, use the HttpServlet class. * A client request to a servlet is represented by an HttpServletRequest object. This object encapsulates the communication from the client to the server. It can contain information about the client environment and any data to be sent to the servlet from the client. * The response from the servlet back to the client is represented by an HttpServletResponse object. This is often the dynamically generated response, such as an HTML page, and is built with data from the request and from other sources accessed by the servlet.
• •
doGet() method doPost() method
HelloWorldServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HelloWorldServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<HTML>"); out.println("<HEAD><TITLE>Have you seen this before?</TITLE></HEAD>"); out.println("<BODY><H1>Hello, World!</H1><H6>Again.</H6></BODY></HTML>"); } }
web.xml file(Deployment Descriptor) <?xml version=”1.0” encoding=”ISO-8859-1”?> <web-app> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class> HelloWorldServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/sayHelloAgain</url-pattern> </servlet-mapping> </web-app>
Embedded in a form: Client Interaction Client side <html> <head><title>Testing Servlets</title></head> <body> <body> <form method="POST" action="http://localhost:8080/MyApp/ServletTest"> <p>WELCOME</p> <p>User Name: <input type="text" name="T1" size="20"></p> <p>Password: <input type="text" name="T2" size="20"></p> <p><input type="submit" value="Submit" name="B1"> <input type="reset" value="Reset" name="B2"></p> </form> </body> </html>
Server side import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ServletTest extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) Throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); try { Enumeration values = req.getParameterNames(); while(values.hasMoreElements()) { String name = (String)values.nextElement(); String value = req.getParameterValues(name); out.println(name + ": " + value); } out.println(“<br>Thank You!!!<br>”); } catch(Exception e) {} out.close(); } }
doc_766825757.pdf
all about servlets
SERVLETS
A servlet is a Java™ technology-based Web component, managed by a container that generates dynamic content. It is a server-side software program, written in Java code that handles messaging between a client and server, a program (running on a web server) that dynamically generates some output as its reaction to a request. Servlets can respond to client requests by dynamically constructing a response that is sent back to the client. A single servlet can be invoked multiple times to serve requests from multiple clients. A servlet can handle multiple requests concurrently and can synchronize requests. Servlets can forward requests to other servers and servlets.
The basic flow is this: 1. The client sends a request to the server. 2. The server instantiates (loads) the servlet and creates a thread for the servlet process. 3. The server sends the request information to the servlet. 4. The servlet builds a response and passes it to the server. 5. The server sends the response back to the client. The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle. Java Servlet Containers Apache Tomcat BEA WebLogic Server IBM WebSphere Application Server JBoss Application Server Oracle Application Server Sun Java System Application Server Platform Edition Role of an Application Server: A servlet engine runs within the application server and manages the servlet. It loads and initializes the servlet, passes requests and responses to the servlet and client, manages multiple instances of a servlet, and acts as a request dispatcher. It destroys the servlet at the end of its useful life. Servlets are unloaded and removed from memory when the server shuts down. How do you run a servlet? • Invoked as an explicit URL reference • Embedded in HTML and invoked from a Web application.
The Servlet Life Cycle •When the Servlet instance has been created, the container will call init() •Now the Servlet is ready for processing user requests – service() is called for processing a request – the Servlet remains loaded and ready after a request is processed •destroy() is called before a Servlet is deleted –time of deletion is not defined
The Servlet API The Java Servlet API defines a standard interface for the request and response messages between a Web client and a Web servlet. So your servlets can be portable across platforms and across different Web application servers. In essence, the API encases requests as objects so the server can pass them to the servlet; the responses are similarly encapsulated so the server can pass them back to a client. The Java Servlet API has two packages. javax.servlet contains classes to support generic protocolindependent servlets, and javax.servlet.http includes specific support for the HTTP protocol.
Prerequisites to excecute a servlet: Have an Application server installed (using Apache Tomact here):
myapplication/
contains auxiliary files (e.g. HTML, GIF, CSS, JSP files), can be in sub-directories contains deployment descriptor, web.xml contains Servlet class files (in appropriate sub-directories, if non-default package names) contains extra jar files
myapplication/WEB-INF/ myapplication/WEBINF/classes/ myapplication/WEB-INF/lib/
To Compile a servlet
> set classpath \tomcat\common\lib\servlet-api.jar;. > javac HelloWorld.java
Invoking a servlet by typing its address in the URL Using javax.servlet package( Generic Servlets)
Basic Servlet.java import javax.servlet.*; import java.io.*; public class BasicServlet extends GenericServlet { public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("Hello."); } }
web.xml file(Deployment Descriptor) <?xml version=”1.0” encoding=”ISO-8859-1”?> <web-app> <servlet> <servlet-name>Hello</servlet-name> <servlet-class>BasicServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/sayHello</url-pattern> </servlet-mapping> </web-app>
The Deployment Descriptor The /WEB-INF/web.xml file contains the Web Application Deployment Descriptor for your application. As the filename extension implies, this file is an XML document, and defines everything about your application that a server needs to know. The deployment descriptor: web.xml provides control of: • URL mapping (from URLs to files) • initialization parameters • timeout settings • directory listings • error pages • security constraints, client authentication • filters and listeners Using javax.servlet.http package To write an HTTP servlet for use on the Web, use the HttpServlet class. * A client request to a servlet is represented by an HttpServletRequest object. This object encapsulates the communication from the client to the server. It can contain information about the client environment and any data to be sent to the servlet from the client. * The response from the servlet back to the client is represented by an HttpServletResponse object. This is often the dynamically generated response, such as an HTML page, and is built with data from the request and from other sources accessed by the servlet.
• •
doGet() method doPost() method
HelloWorldServlet.java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class HelloWorldServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<HTML>"); out.println("<HEAD><TITLE>Have you seen this before?</TITLE></HEAD>"); out.println("<BODY><H1>Hello, World!</H1><H6>Again.</H6></BODY></HTML>"); } }
web.xml file(Deployment Descriptor) <?xml version=”1.0” encoding=”ISO-8859-1”?> <web-app> <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class> HelloWorldServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/sayHelloAgain</url-pattern> </servlet-mapping> </web-app>
Embedded in a form: Client Interaction Client side <html> <head><title>Testing Servlets</title></head> <body> <body> <form method="POST" action="http://localhost:8080/MyApp/ServletTest"> <p>WELCOME</p> <p>User Name: <input type="text" name="T1" size="20"></p> <p>Password: <input type="text" name="T2" size="20"></p> <p><input type="submit" value="Submit" name="B1"> <input type="reset" value="Reset" name="B2"></p> </form> </body> </html>
Server side import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ServletTest extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) Throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); try { Enumeration values = req.getParameterNames(); while(values.hasMoreElements()) { String name = (String)values.nextElement(); String value = req.getParameterValues(name); out.println(name + ": " + value); } out.println(“<br>Thank You!!!<br>”); } catch(Exception e) {} out.close(); } }
doc_766825757.pdf