IAT-2 Java
IAT-2 Java
IAT-2 Java
A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet
The servlet is initialized by calling the init () method.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of the JVM.
The service() method is the main method to perform the actual task.
The servlet container (i.e. web server) calls the service() method to handle requests coming from
the client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls
doGet, doPost, doPut, doDelete, etc. methods as appropriate.
The service () method is called by the container and service method invokes doGe, doPost, doPut,
doDelete, etc.methods as appropriate.
So you have nothing to do with service() method but you override either doGet() or doPost()
depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here is
the signature of these two methods.
While all the Servlet classes are kept inside classes folder.
import javax.servlet.*;
import
javax.servlet.http.*;
import java.io.*;
}
}
Write above code and save it as MyServlet.java anywhere on your PC. Compile it from there and
paste the class file into WEB-INF/classes/ directory that you have to create inside
Tomcat/webapps directory.
import javax.servlet.*;
import java.io.*;
// extending GenericServlet class
throws IOException,ServletException{
{ response.setContentType("text/html"); // set content
type
}
}
3. Compiling a Servlet
To compile a Servlet a JAR file is required. Different servers require different JAR files. In Apache Tomcat
server servlet-api.jar file is required to compile a servlet class.
NOTE: After compiling your Servlet class you will have to paste the class file into WEB-INF/classes/ directory.
<web-app>
<servlet>
<servlet-name> MyServlet </servlet-name>
<servlet-class> MyServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> MyServlet </servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
5. Starting Tomcat Server for the first time set JAVA_HOME or JRE_HOME in environment
variable (It is required to start server).
Go to My Computer properties -> Click on advanced tab then environment variables -> Click on the
new tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk folder in variable
value -> ok
Call request.getCookies
– This yields an array of Cookie objects.
• Loop down the array, calling getName on each entry until you find the cookie of interest
– Use the value (getValue) in application-specific way.
Constructor of Cookie class
Constructor Description
Cookie(String name, String constructs a cookie with a specified name and value.
value)
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot be changed
after creation.
Program
index.html
<form method="post" action=" MyServlet ">
Name:<input type="text" name="user" /><br/>
Password:<input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form>
if(pass.equals("1234"))
{
Cookie ck = new Cookie("username",name);
response.addCookie(ck);
//response.sendRedirect("First");//call ur servlet
out.print("</form>);
}
}
}
INTERFACES CLASSES
Servlet- ServletInputStream
ServletContext -ServletOutputStream
ServletConfig -ServletException
ServletRequest- UnavailableException
ServletResponse- GenericServlet
Interface Summary
ServletConfig
ServletContext Defines a set of methods that a servlet uses to communicate with its servlet
container, for example, to get the MIME type of a file, dispatch requests, or write
to a log file.
Interface Servlet
Interface
ServletRequest
Interface ServletResponse
Interface ServletConfig
Interface ServletContext
Class Summary
ServletInputStream Provides an input stream for reading binary data from a client request,
including an efficient readLine method for reading data one line at a time.
ServletOutputStream Provides an output stream for sending binary data to the client.
Class GenericServlet
java.lang.Object
javax.servlet.GenericServlet
All Implemented Interfaces: Servlet, ServletConfig
Class ServletInputStream
java.lang.Object
java.io.InputStream
javax.servlet.ServletInputStream
Method Summary
Class ServletOutputStream
Method Summary
void println()
void print(java.lang.String s)
Writes a String to the client, without a carriage return-line feed (CRLF) character at the
end.
void println()
Writes a carriage return-line feed (CRLF) to the client.
void println(java.lang.String s)
Writes a String to the client, followed by a carriage return-line feed (CRLF).
CLASSES
INTERFACES
Cookie HttpServletRequest
HttpServlet HttpServletResponse
HttpSessionBindingEvent HttpSession
Interface Summary
HttpSession Provides a way to identify a user across more than one page request or
visit to a Web site and to store information about that user.
Interface HttpServletResponse
HttpServletRequest
Interface HttpServletRequest :
interface HttpSession
Class Summary
HttpSessionEvent This is the class representing event notifications for changes to sessions
within a web application
Class Cookie
class HttpServlet:
Class HttpSessionBindingEvent
Method Summary
java.lang.String getName()
Returns the name with which the attribute is bound to or unbound from the
session.
HttpSession getSession()
Return the session that changed.
java.lang.Object getValue()
Returns the value of the attribute that has been added, removed or replaced.
Class HttpSessionEvent
Method Summary
HttpSession getSession()
Return the session that changed.
With an example program Explain the mechanism of SessionTracking
in Servlets?
HttpSession object is used to store entire session with a specific client. We can store, retrieve
and remove attribute from HttpSession object. Any servlet can have access to HttpSession
object throughout the getSession() method.
Methods Description
returns the time when the session was created, measured in
long getCreationTime()
milliseconds since midnight January 1, 1970 GMT.
Example
index.html
<form method="post" action="Validate">
User: <input type="text" name="uname "
/><br/>
<input type="submit" value="submit">
</form>
}
}
Welcome.java
public class Welcome extends HttpServlet {
1. JSP scriptlet tag A scriptlet tag is used to execute java source code in
JSP. <% java source code %>
<html>
<body>
</body>
</html>
b. Include Directive
The include directive tells the Web Container to copy everything in the included file and paste it
into current JSP file. The include directive is used to include the contents of any resource it may
be jsp file, html file or text file. Syntax of include directive is:
<html>
<mytag:hello/>
<
/
bod
y>
</h
tml
>
5. JSP Comments
JSP comment marks text or statements that the JSP container should
ignore. syntax of the JSP comments <%- - This is JSP comment - -%>
index.html
<form action="welcome.jsp">
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</html>
welcome.jsp
<html>
<body> <%
String name=request.getParameter("uname");
out.print("Welcome "+name); session.setAttribute("user",name);
%>
</body>
Data is sent in header to the server Data is sent in the request body
Get request can send only limited amount of data Large amount of data can be sent.
Get request is not secured because data is exposed Post request is secured because data is not
exposed in URL in URL.