Mod 4
Mod 4
SERVLETS
Introduction to Web
The web clients make requests to web server. When a server answers a request, it usually sends
some type of content(MIME- Multi purpose Internet Mail Exchange) to the client. The client uses web
browser to send request to the server. The server often sends response to the browser with a set of
instructions written in HTML(HyperText Markup Language)
Before Servlets, CGI(Common Gateway Interface) programming was used to create web applications.
Here's how a CGI program works :
Because of these disadvantages, developers started looking for better CGI solutions. And then Sun
Microsystems developed Servlet as a solution.
Servlet
Servlet technology is used to create web application (resides at server side and generates dynamic web
page).
Servlet can be described in many ways, depending on the context.
Servlet is server side program.
Servlet is an API that provides many interfaces and classes.
Servlet is a web component that is deployed on the server to create dynamic web page.
the JVM. Now let us discuss the life cycle methods in details.
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.
2. Creating a Servlet
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.*;
import java.io.*;
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.
<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>
Servlet API
Servlet API consists of two important packages that encapsulates all the important classes and interface,
namely :
1. javax.servlet.*;
INTERFACES CLASSES
Servlet ServletInputStream
ServletContext ServletOutputStream
ServletConfig ServletException
ServletRequest UnavailableException
ServletResponse GenericServlet
Interface Summary
Defines a set of methods that a servlet uses to communicate with its servlet
ServletContext 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
Provides an input stream for reading binary data from a client request,
ServletInputStream
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.
ServletException Defines a general exception a servlet can throw when it encounters difficulty.
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).
2. javax.servlet.http.*;
CLASSES
INTERFACES
Cookie HttpServletRequest
HttpServlet HttpServletResponse
HttpSessionBindingEvent HttpSession
Interface Summary
Provides a way to identify a user across more than one page request or
HttpSession
visit to a Web site and to store information about that user.
Interface HttpServletResponse
Interface HttpServletRequest
Interface HttpSession
Class Summary
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.
MyServlet.java
public class MyServlet extends HttpServlet {
HttpServlet class provides various methods that handle various types of HTTP request.
A servlet typically must override at least one method, usually one of these:
doGet, if the servlet supports HTTP GET requests
doPost, for HTTP POST requests
doPut, for HTTP PUT requests
doDelete, for HTTP DELETE requests
GET and POST methods are commonly used when handling form input.
NOTE: By default a request is Get request.
Difference between GET and POST requests
GET Request POST Request
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.
Session
Session simply means a particular interval of time. Session Tracking is a way to maintain state
(data) of an user. It is also known as session management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time
user requests to the server, server treats the request as the new request. So we need to maintain the state
of an user to recognize to particular user.
There are 2 techniques used in Session tracking:
1. Cookies
2. HttpSession
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client requests.
By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by
the user, cookie is added with request by default. Thus, we recognize the user as the old user.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
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>
MyServlet.java
public class MyServlet extends HttpServlet {
if(pass.equals("1234"))
{
Cookie ck = new Cookie("username",name);
response.addCookie(ck);
//response.sendRedirect("First");//call ur servlet
First.java
public class First extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{ // . . .
Cookie[] cks = request.getCookies();
out.println("Welcome "+cks[0].getValue());
}
}
Returns the name of the cookie. The name cannot be changed after
public String getName()
creation.
HttpSession
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
index.html
<form method="post" action="Validate">
User: <input type="text" name="uname " /><br/>
<input type="submit" value="submit">
</form>
Validate.java
public class Validate extends HttpServlet {
1. JSP scriptlet tag A scriptlet tag is used to execute java source code in JSP.
<% java source code %>
<html>
<mytag:hello/>
</body>
</html>
5. JSP Comments
JSP comment marks text or statements that the JSP container should ignore.
syntax of the JSP comments <%- - This is JSP comment - -%>
Request String
The query string contains the attribute & the value of the html form or JSP form, which sends
with the POST /GET method to Servlet or JSP page for any request.
A query string is the part of a URL which is attached to the end, after the file name. It begins
with a question mark and usually includes information in pairs. The format is parameter=value,
as in the following example:
www.mediacollege.com/cgi-bin/myscript.cgi?name=”Umesh”
Query strings can contain multiple sets of parameters, separated by an ampersand (&) like so:
www.mediacollege.com/cgi-bin/myscript.cgi?fname=”Umesh”&lname=”M”
to parse this info we use method of JSP request object
we can easily get using request.getParameter() with name of parameter as argument, to get its
value.
welcome.jsp
index.html
<html>
<form action="welcome.jsp"> <body>
<input type="text" name="uname"> <%
<input type="submit" value="go"><br/> String
</form> name=request.getParameter("uname");
out.print("Welcome "+name);
welcome.jsp session.setAttribute("user",name);
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
//other methods of Session what u used in servlets can be used here.
Cookie (concept same as servlet)
Step 1: Creating a Cookie object
Cookie cookie = new Cookie("key","value");
Step 2: Setting the maximum age
You use setMaxAge to specify how long (in seconds) the cookie should be valid. The following code
will set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24);
Step 3: Sending the Cookie into the HTTP response headers
You use response.addCookie to add cookies in the HTTP response header as follows
response.addCookie(cookie);
<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));
<html>
<body>
p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p>
<p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p>
</body>
</html>
Reading Cookies with JSP
<html>
<body>
<%
Cookie cookie = null;
Cookie[] cookies = null;
</html>
//other methods of Cookie what u used in servlets can be used here.