What Is A Servlet?: Advantages of Using Servlets
What Is A Servlet?: Advantages of Using Servlets
What Is A Servlet?: Advantages of Using Servlets
1. What Is a Servlet?
servlet.
• User sends request for a servlet by clicking a link that has URL to a servlet.
• The container finds the servlet using deployment descriptor and creates two objects
HttpServletRequest
HttpServletResponse
• Then the container creates or allocates a thread for that request and calls the Servlet's service()
method and passes the request, response objects as arguments.
• The service() method, then decides which servlet method, doGet() or doPost() to call, based
on HTTP Request Method(Get, Post etc) sent by the client. Suppose the client sent an HTTP
GET request, so the service() will call Servlet's doGet() method.
• Then the Servlet uses response object to write the response back to the client.
imort javax.servlet.*;
class className extends GenericServlet
{
public void init() throws ServletException
{
// Initialization code...
}
public void service(ServletRequest request, ServletResponse response)throws
ServletException, IOException
{
}
public void destroy()
{
// Finalization code...
}
}
6. servlet API:
javax.servlet - The javax.servlet package contains a number of classes and interfaces that
describe and define the contracts between a servlet class and the runtime environment
provided for an instance of such a class by a conforming servlet container.
javax.servlet.http-The javax.servlet.http package contains a number of classes and
interfaces that describe and define the contracts between a servlet class running under the
HTTP protocol and the runtime environment provided for an instance of such a class by a
conforming servlet container
• The ServletRequest class includes methods that allow you to read the names and
values of parameters that are included in a client request.
• The example contains two files. A Web page is defined in PostParameters.htm and a
servlet is defined in PostParametersServlet.java.
• Different mathods to read parameter are as follows:
• getParameter(string)
• getParamaterNames();
• getParamaterValues();
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http*;
public class A extends GenericServlet
{
public void service(ServletRequest req ,ServletResponse res)throws
ServletException,IOException
{
res.setContentType(“text/html”) ;
PrintWriter out=res.getWriter();
String msg=req.getParameter("t1");
out.println(“hello”+msg+”how are you”);
}
}
HTML code
<html>
<body>
<form action=http://localhost:8080/A >
<input type=”text box” name=”t1” value=” “>
<input type=”submit” name=”submit”>
</form>
</body>
</html>
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http*;
public class A extends GenericServlet
{
public void service(ServletRequest req ,ServletResponse res)throws
ServletException,IOException
{
res.setContentType(“text/html”) ;
PrintWriter out=res.getWriter();
Enumeration e=req.getParameterNames();
while(e.hasMoreElements())
{
Sting a=e.nextElement();
String msg=request.getParameter(a);
out.println(msg);
}
}
<html>
<body>
<form action=http://localhost:8080/A>
<input type=”text box” name=”t1” value=” “>
<input type=”text box” name=”t2” value=” “>
<input type=”submit” name=”submit”>
</form>
</body>
</html>
Program:
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http*;
public class A extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws
ServletException,IOException
{
res.setContentType(“text/html”) ;
PrintWriter out=res.getWriter();
<html>
<body>
<form action=http://localhost:8080/A method=POST>
<input type=”text box” name=”t1” value=” “>
<input type=”submit” name=”submit”>
</form>
</body>
</html>
Difference between HTTP doGet and HTTP doPost methods of Servlet
Difference Type GET (doGet()) POST (doPost())
HTTP Request The request contains only the Along with request line and header
request line and HTTP it also contains HTTP body.
URL Pattern Query string or form data is Form name-value pairs are sent in
simply appended to the URL the body of the request, not in the
as name-value pairs. URL itself.
Parameter passing The form elements are passed The form elements are passed in
to the server by appending at the body of the HTTP request.
the end of the URL.
Size The parameter data is Can send huge amount of data to
limited (the limit depends the server.
on the container normally
Idempotency GET is Idempotent(can be applied POST is not idempotent(warns if
multiple times without changing
applied multiple times without
the values
changing the values
Program:
import javax.servelt.*;
import java.io.*;
public class A extends GenericServlet
{
public void service(ServletRequest req ,ServletResponse res)throws
ServletException,IOException
{
res.setContentType(“text/html”) ;
PrintWriter out=res.getWriter();
void service(ServletRequest req, Called by the servlet container to allow the servlet to
ServletResponse res) respond to a request.
• The GenericServlet class provides implementations of the basic life cycle methods for a
servlet.
• GenericServlet implements the Servlet and ServletConfig interfaces.
• In addition, a method to append a string to the server log file is available.The signatures of
this method are shown here:
1. The examples here is Windows environment. The default location for Tomcat 5.5.17 is
C:\Program Files\Apache Software Foundation\Tomcat 5.5\
2. to set the environmental variable JAVA_HOME to the top-level directory in which
the Java Software Development Kit is installed.
3. To start Tomcat, select Start Tomcat in the Start | Programs menu, , and the n press Start in
the Tomcat Properties dialog. The directory
C:\Program Files\Apache Software Foundation\Tomcat 5.5\common\lib\
Contain servlet.api.jar.
4.. To make this file accessible, update your CLASSPATH environment
variable so that it includes
C:\Program Files\Apache Software Foundation\Tomcat5.5\common\lib\servlet.api.jar
5. First. Copy the servlet’s class file into the following directory:
C:\Program Files\Apache Software
Foundation\Tomcat5.5\webapps\servlets.examples\WEB-INF\classes
6. Next, add the servlet’s name and mapping to the web.xml file in the following directory
• JSP are translated and compiled into JAVA servlets but are easier to develop
than JAVA servlets.
• JSP uses simplified scripting language based syntax for embedding HTML into JSP.
• JSP containers provide easy way for accessing standard objects and actions.
• JSP reaps all the benefits provided by JAVA servlets and web container
environment, but they have an added advantage of being simpler and more natural
program for web enabling enterprise developer.
• JSP use HTTP as default request / response communication paradigm and thus
make JSP ideal as Web Enabling Technology.
Initialization:
• When a container loads a JSP it invokes the jspInit() method before servicing any
requests. If you need to perform JSP-specific initialization, override the jspInit()
method:
public void jspInit()
{
// Initialization code...
}
• Typically initialization is performed only once and as with the servlet init method,
you generally initialize database connections, open files, and create lookup tables in
the jspInit method.
JSP service:
• This phase of the JSP life cycle represents all interactions with requests until the JSP
is destroyed.
• Whenever a browser requests a JSP and the page has been loaded and initialized, the
JSP engine invokes the _jspService() method in the JSP.
3. JSP Architecture:
The following steps explain how the web server creates the web page using JSP:
• As with a normal page, your browser sends an HTTP request to the web server.
• The web server recognizes that the HTTP request is for a JSP page and forwards it to
a JSP engine. This is done by using the URL or JSP page which ends with .jsp
instead of .html.
• The JSP engine loads the JSP page from disk and converts it into a servlet content.
This conversion is very simple in which all template text is converted to println( )
Expression Tag:
• A JSP expression element contains a scripting language expression that is
evaluated, converted to a String, and inserted where the expression appears in the
JSP file.
• Because the value of an expression is converted to a String, you can use an expression
within a line of text, whether or not it is tagged with HTML, in a JSP file.
• The expression element can contain any expression that is valid according to
the Java anguage Specification but you cannot use a semicolon to end an expression.
example:
<%! int a = 5, b = 10;
<%= a+b %>
%>
Scriptlet Tag:
A scriptlet tag opens with <% and contains commonly used java control statements and
loops. It closes with %>
Syntax two forms:
<% control statements %>
Example:
<% for (int i = 0; i < 2; i++) { %>
<p>Hello World!</p>
<% } %>
Program to display the grading system for the given java subject marks using control
statements (VTU question VIMP):
<% !
int marks=65;
<% if(marks>=90)%>
<p>grade A</p>
<%else if(marks>=80 && marks<=89)%>
<p>Grade B</p>
<%else if(marks>=70 && marks<=79)%>
<p>Grade C</p>
<%else%>
<p>Fail</p>
%>
A.html
<html>
<body>
<form action=A.jsp>
<input type=”textbox” name=”t1” value=” “>
<input type=”submit” mane=”submit”>
</form>
</body>
</html>
using getParameterNames():
getParameterNames()-returns an enumeration of the parameter names.These are processed in
loop
program:
<%@ import java.util.*; %>
<%!
Enumeration e=req.getParameterNames();
while(e.hasMoreElements())
{
Sting a=e.nextElement();
String msg=request.getParameter(a);
out.println(msg);
}
%>
6. cookies:
• A cookie is a small piece of information created by a JSP program that is stored in
the client’s hard disk by the browser. Cookies are used to store various kind of
information such as username, password, and user preferences, etc.
• Different methods in cookie class are:
1. String getName()- Returns a name of cookie
2. String getValue()-Returns a value of cookie
3. int getMaxAge()-Returns a maximum age of cookie in millisecond
4. String getDomain()-Returns a domain
5. boolean getSecure()-Returns true if cookie is secure otherwise false
6. String getPath()-Returns a path of cookie
7.void setPath(Sting)- set the path of cookie
8.void setDomain(String)-set the domain of cookie
9.void setMaxAge(int)-set the maximum age of cookie
10.void setSecure(Boolean)-set the secure of cookie.
Creating cookie:
Cookie are created using cookie class constructor.
Content of cookies are added the browser using addCookies() method.
PROGRAM: To create and read the cookie for the given cookie name as “EMPID”
and its value as”AN2356”.(VTU question VIMP)
<%!
%>
JSP program to read a cookie
<%!
Cookie c[]=request.getCookies();
for(i=0;i<c.length;i++)
{
String name=c[i].getName();
String value=c[i].getValue();
out.println(“name=”+name);
out.println(“value=”+value);
}
%>
Program:
<%!
HttpSession h=req.getSesssion(true);
Date d=(Date) h.getAttribute(“Date”);
out.println(“last date and time”+d);
Date d1=new Date();
d1=h.setAttribute(“date”,d1);
out.println(“current date and time=”+d1);
%>