Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Contents
1 2 3 4 5 6 7 8 9 Definition Servlet Request Response Mechanism JSDK Servlet interface Servlet Life Cycle Servlet instance Servlet Class hierarchy GenericServlet HTTPServlet
Contents
11 12 13 14 15 16 17 18 19 20 Request and Response object A Simple Servlet Steps to deploy a web application HTML file with a link to servlet Deployment Descriptors Brief introduction to XML web.xml Writing web.xml Packaging Deploying
Contents
21 22 23 24 25 26 27 28 29 30 Packaging and deploying the servlet Steps for packaging Deployment Execution Request and Response hierarchy ServletRequest HttpServletRequest Interface ServletResponse Interface HttpServletResponse Interface Getting single parameters
Contents
31 32 33 34 Getting multiple parameters Servlet to get multiple param Servlet variable initialization SingleThreadModel Interface
Know
What a servlet is and its lifecycle The Request Response Mechanism Servlet classes HttpServletRequest and HttpServletResponse classes
Be Able To
Write a simple servlet
Definition
A servlet is a server side program written in Java that resides and executes in an application server It enables the delivery of dynamic content
Servlet
Client
JSDK
Java Servlet Development Kit (JSDK) contains the class library that is required to create servlets and JSP. The 2 packages that are required to create servlets are javax.servlet and javax.servlet.http. A java class is a servlet if it directly or indirectly implements the Servlet interface.
Servlet interface
public void init(ServletConfig config) throws ServletException public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException public void destroy() public ServletConfig Life cycle methods getServletConfig() public String getServletInfo()
Subsequent requests
Initialized Servlet
Begin service
service() is called
Destroyed Servlet
destroy() is called
Servlet instance
Only one instance of a particular servlet class is created. The same instance is used for all the requests. When the container shuts down, this instance is destroyed.
Servlet instance
The container runs multiple threads on the service() method to process multiple requests. Only a single instance of servlet of each type ensures minimum number of servlet objects created and destroyed on the server
adds to scalability
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
GenericServlet
GenericServlet class provides basic implementation of the Servlet interface. This is an abstract class. It implements all the methods except service() method.
GenericServlet
Other methods included are:
public void log(String message) public void init() throws ServletException
HTTPServlet
HTTPServlet inherits from the GenericServlet and provides a HTTP specific implementation of the Servlet interface. The service(ServletRequest req, ServletResponse res) method is implemented.
HTTPServlet
Since this implementation specific to HTTP protocol, there are methods that specific to each HTTP methods like GET, POST, TRACE etc. It is an abstract class and is subclassed to create an HTTP servlet suitable for a Web site.
Our focus
Web Container
Servlet A
HttpServletRequest Object
Application server
HttpServletResponse Object
A Simple Servlet
import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class GreetingServlet extends HttpServlet { String welcomeMsg =Welcome to simple servlet; java.util.Date currDate;
greet.war
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { currDate=new java.util.Date(); PrintWriter out = response.getWriter(); response.setContentType("text/html"); out.println("<html><head><title>Greeting s Servlet </title></head>); out.println("<body>+ welcomeMsg+<br>+currDate+ </body></html>"); }}
Deployment Descriptor
Deployment descriptors is an xml file that helps in managing the configuration of an application. This is the file using which an application can communicate with the container and vice versa. For a web application, the deployment descriptor file name is web.xml. The Java Servlet specifies a document type definition for deployment descriptor which is available at
http://java.sun.com/j2ee/dtds/web_app_2_2.dtd
Servlet components that are used in web application along with their fully qualified class names URLs for servlets Welcome file name Initialization parameters if any Session Configuration Our focus in this chapter Application Lifecycle Listener classes Filter Definitions and Filter Mappings Error Pages Environment Variable Mappings Mime type mapping
web.xml
Writing web.xml
<web-app> <display-name>Greet</display-name> Optional. IDEs use it for listing web <servlet>
application name
Packaging
Packaging application means placing the files in the appropriate placeholders (directory).
Packaging
Servlet specification lays out the rules of how enterprise applications should be packaged. This is necessary so that the container (any j2ee container) knows where to find the files (the servlet class files, html class files etc.) Since a web application is composed of many files, the specification also tells us how to archive the files and deploy it as single file application.
Deploying
Deploying means uploading the application on the server. If there is any problem with the packaging, the application will not be uploaded. There are many J2EE IDEs that help in developing and packaging the application.
Deploying
Most of the application servers support hot deployment. Most of the application servers support start and stop of applications that are deployed.
JSPs/HTML
JSPs/HTML
xxx.war
Deployment
As per j2ee specification, a jar file should be created with the extension .war. This war file has to be then deployed depending on the application server. Jar Command to create war path/simple:> jar cvf simple.war *.* For tomcat, just copy the simple folder into the folder called webapps.
Deployment
Start the tomcat server. Type in the following url in the address bar
http://localhost:8080/slide1ex1 /index.html Or simply http://localhost:8080/slide1ex1
Folder name protocol
According to j2ee specs, war file has to be created. For tomcat we dont do so. So, does this mean that tomcat does not strictly follow j2ee specs? Tomcat follows j2ee specs! It just gives you a simple way to deploy your application. Another option to deploy would be to place the war file
ServletRequest
BufferedReader getReader() ServletInputStreamAllows you to read raw bytes getInputStream() or characters from the stream int getContentLength() Enumeration getParameterNames() String getParameter(String name) String[] getParameterValues(String name)
Example ahead
HttpServletRequest Interface
String getMethod() String getHeader(String name) Enumeration getHeaderNames() String getQueryString() Cookies[] getCookies() Later HttpSession getSession()
HTTP protocol specific method s
ServletResponse Interface
void setContentType(String type) void setContentLength(int len) ServletOutputStream Allows us to write getOutputStream() into the response PrintWriter getWriter() stream
We have seen this !
HttpServletResponse Interface
void addCookies(Cookie c) String addHeader(String name,String value) void sendRedirect(String url) void sendError(int ecode)
Question?
What will happen if your form has a post method, and the servlet that the form calls has only doGet() method?
String colors[]=req.getParameterValues("color"); out.println("<body>"); for(int i=0;i<colors.length;i++) out.println("<font color='"+ colors[i]+"'>Hello </font><br>" ); out.println("</body></html>"); } }
greet.war
Question?
What happens if you dont select any of the checkboxes?
SingleThreadModel Interface
In the servlet model that we have seen so far, a single servlet processes multiple requests simultaneously. This means that the doGet and doPost methods must be careful to synchronize access to fields and other shared data, since multiple threads may be trying to access the data simultaneously. On the other hand, you can have your servlet implement the SingleThreadModel interface, as below. public class YourServlet extends HttpServlet implements And say goodbye to Scalability SingleThreadModel {...}