Ajj Mod4
Ajj Mod4
Ajj Mod4
Servlet
Introdution to servlet
Servlet is small program that execute on the server side of a web connection. Just as applet
extend the functionality of web browser the applet extend the functionality of web server.
In order to understand the advantages of servlet, you must have basic understanding of
how web browser communicates with the web server.
Consider a request for static page. A user enters a URL into browser. The browser generates http
request to a specific file. The file is returned by http response. Web server map this particular
request for this purpose. The http header in the response indicates the content. Source of web
page as MIME type of text/html.
Java servlet is more efficient, easier to use, more powerful, more portable, and cheaper than
traditional CGI and than many alternative CGI-like technologies. (More importantly, servlet
developers get paid more than Perl programmers :-).
Efficient. With traditional CGI, a new process is started for each HTTP request. If the
CGI program does a relatively fast operation, the overhead of starting the process can
dominate the execution time. With servlets, the Java Virtual Machine stays up, and each
request is handled by a lightweight Java thread, not a heavyweight operating system
process. Similarly, in traditional CGI, if there are N simultaneous request to the same
CGI program, then the code for the CGI program is loaded into memory N times. With
servlets, however, there are N threads but only a single copy of the servlet class.
Convenient. Hey, you already know Java. Why learn Perl too? Besides the convenience
of being able to use a familiar language, servlets have an extensive infrastructure for
automatically parsing and decoding HTML form data, reading and setting HTTP headers,
handling cookies, tracking sessions, and many other such utilities.
Powerful. Java servlets let you easily do several things that are difficult or impossible
with regular CGI. For one thing, servlets can talk directly to the Web server (regular CGI
programs can't). This simplifies operations that need to look up images and other data
stored in standard places. Servlets can also share data among each other, making useful
things like database connection pools easy to implement. They can also maintain
Advance Java and J2EE –Module 4
information from request to request, simplifying things like session tracking and caching
of previous computations.
Portable. Servlets are written in Java and follow a well-standardized API. Consequently,
servlets written for, say I-Planet Enterprise Server can run virtually unchanged on
Apache, Microsoft IIS, or Web Star. Servlets are supported directly or via a plug in on
almost every major Web server.
Inexpensive. There are a number of free or very inexpensive Web servers available that
are good for "personal" use or low-volume Web sites. However, with the major exception
of Apache, which is free, most commercial-quality Web servers are relatively expensive.
Nevertheless, once you have a Web server, no matter the cost of that server, adding
servlet support to it (if it doesn't come preconfigured to support servlets) is generally free
or cheap.
2. What is servlet? What are the phases of servlet life cycle? Give an example.
Servlets are small programs that execute on the server side of a web connection. Just as
applet extend the functionality of web browser the applet extend the functionality of web server.
It class the init method when it loads the instance. It is used to intialise servlet.
Web container calls service method each time when request for the servlet is
received. If servlet is not initialized it calls init then it calls the service method. Syntax of
service method is as follows
Advance Java and J2EE –Module 4
The web container calls the destroy method before it removes the servlet
from service. It gives servlet an opportunity to clean up memory, resources etc. Servlet
destroy method has following syntax.
public void destroy().
Ready
There are three states of servlet new, ready, end. It is in new state when servlet is created.
The servlet instance is created when it is in new state. After invoking the init () method servlet
comes to ready state. In ready state servlet invokes destroy method it comes to end state.
3. Explain about deployment descriptor
Deployment descriptor is a file located in the WEB-INF directory that controls the
behavior of a java servlet and java server pages. The file is called the web.xml file and contains
the header, DOCTYPE, and web app element. The web app element should contain a servlet
element with three elements. These are servlet name, servlet class, and init-param.
The servlet name elements contain the name used to access the java servlet. The
servlet class is the name of the java servlet class. init-param is the name of an initialization
parameter that is used when request is made to the java servlet.
Example file:
Example code
Html code that calls a servlet:
<FORM ACTION=”/servlet/myservlets.js2”>
Enter Email Address :< INPUT TYPE=”TEXT” NAME=”email”>
<INPUT TYPE=”SUBMIT”>
</FORM>
Advance Java and J2EE –Module 4
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class js2 extends Httpservlet {
public void doGet(HttpservletRequset request,HttpservletResponse response)
throws servletException , IOException {
//String email;
//Email=request.getParameter(“email”);
Respose.setContentType(“text/html”);
PrinterWriter pw=response.getWriter();
pw.println(“<HTML>\n” +
“HEAD><TITLE> Java Servlet</TITLE></HEAD>\n”
+ “<BODY>\n”+
//“<p>MY Email Address :” +email +”</p>\n” +
<h1> My First Servlet
“</BODY>\n” +
</HTML>”);
}
}
5. How to read HTTP Request Headers?
A request from client contains two components these are implicit data,
such as email address explicit data at HTTP request header. Servlet can read these
request headers to process the data component of the request.
A java servlet can read an HTTP request header by calling the getHeader()
method of the HttpservletRequest object. getHeader() requires one argument
which is the name of the http request header.
getHeader()
Advance Java and J2EE –Module 4
6. How to send data to client and writing the HTTP Response Header?
A java servlet responds to a client’s request by reading client data and HTTP
request headers, and then processing information based on the nature of the request.
For example, a client request for information about merchandise in an online
product catalog requires the java servlet to search the product database to retrieve product
information and then format the product information into a web page, which is returned
to client.
There are two ways in which java servlet replies to client request. These are sent
by sending information to the response stream and sending information in http response
header. The http response header is similar to the http request header.
Explicit data are sent by creating an instance of the PrintWriter object and then
using println() method to transmit the information to the client.
My Response
Java servlet can write to the HTTP response header by calling setStatus() method
requires one argument which is an integer that represent the status code.
Response.setStatus(100);
Cookies are text files stored on the client computer and they are kept for various
information tracking purpose. Java Servlets transparently supports HTTP cookies.
There are three steps involved in identifying returning users:
Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie
value, both of which are strings.
(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie
should be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24);
(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);
Writing Cookie
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloForm extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
Cookie myCookie = new Cookie("user id", 123);
myCookie.setMaxAge(60*60);
response.addCookie(myCookie );
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println( "<html>\n" +
"<head><title>" + My Cookie + "</title></head>\n" +
“<nody>\n” +
“<h1>+ My Cookie +”<h1>\n” +
“<p> Cookie Written + </p>\n” +
“</body></HTML>”);
}
}
Advance Java and J2EE –Module 4
Syntax :
HttpSession s1=request.getSession(true);
JSP program
A jsp is java server page is server side program that is similar in design and functionality
to a java servlet.
A JSP is called by a client to provide web services, the nature of which depends on client
application.
A jsp is simpler to create than a java servlet because a jsp is written in HTML rather than
with the java programming language. . There are three methods that are automatically called
when jsp is requested and when jsp terminates normally. These are the jspInit() method , the
jspDestroy()m ethod and service() method.
A jspInit() is identical ti init() method of java servlet. It is called when first time jsp is
called.
Advance Java and J2EE –Module 4
A jsp tag consists of a combination of HTML tags and JSP tags. JSP tags define
java code that is to be executed before the output of jsp program is sent to the browser.
A jsp tag begin with a <%, which is followed by java code , and wnds with %>,
A jsp tags are embedded into the HTML component of a jsp program and are
processed by Jsp virtual engine such as Tomcat.
Java code associated with jsp tag are executed and sent to browser.
Comment tag :A comment tag opens with <%-- and close with --%> and is follwed by a
comment that usually describes the functionality of statements that follow a comment tag.
Declaration statement tags: A declartion statement tag opens with <%! And is
followed by declaration statements that define the variables, object, and methods that are
avilabe to other component of jsp program.
Directive tags: A directive tag opens with <%@ and commands the jsp virtual engine to
perform a specific task, such as importing java package required by objects and methods used in
a declaration statement. The directive tag closes with %> . There are commonly used in
directives import, include , and taglib. The import tag is used to import java packages into the jsp
program. Include is used for importing file. Taglib is used for including file.
Example:
Expression tags: An expression tag opens with <%= and is used for an expression
statement whose result page replaces the expression tag when the jsp virtual engine resolves JSP
tags. An expression tag closes with %>
Advance Java and J2EE –Module 4
Scriptlet tag: A sciptlet tag opens with <% and contains commonly used java control
statements and loops. And Scriptlet tag closes with %>
You can declare java variables and objects that are used in a JSP program by
using the same codin technique used to declare them in java. JSP declaration
statements must appear as jsp tag
Ex:
<html>
<head>
<.head>
<body>
</body>
</html>
%>
</body></html>
<body>
Advance Java and J2EE –Module 4
<%
%>
</html>
Create cookie:
<html>
<head>
<title> creating cookie</title>
</head>
<body>
<%! String MyCookieName=”EMPID”;
Advance Java and J2EE –Module 4
String UserValue=”AN2536”;
%>
</body>
</html>
Reading Cookie:
<html>
<head>
<title>reading cookie </title>
</head>
<body>
<% String myCookieName=”EMPID”;
String myCookieValue;
String CName, CValue;
int found=0;
Cookie[] cookies=request.getCoookies();
for( int i=0;i<cookies.length;i++) {
CName= cookies[i].getName();
CValue =cookies[i].getValue();
If(myCookieName.equals(CName)) {
found=1;
myCookieValue=Cvalue; } }
If(found== 1) { %>
<p> Cookie Name = < %= CName %> </p>
<p> Cookie Value = < %= CValue %> </p>
<% } %> </body></html>
1. What are different types of JSP tags describe the JSP tags with example.( Dec 2011)
2. Define JSP. Explain two types of control statements with example.(Dec 2012)
3. Write the JSP program to create and read cookie called “EMPID” and that has value
“AN2536”(Dec 2012)
4. What is RMI? Briefly explain working of RMI in java.(Dec 2012)
5. Department has set the grade for the subject Java as follows:
Above 90: A, 80 - 89: B , 70 -79 : C
Below 70 = fail. Sham enters his marks for the subject Java in the interface provided.
Write a JSP program to accept the mark and display the grade.(Jun 2011)
8. Write a program using RMI such as client and server program in which client sends hello
message to server and replies to client (June 2012)
9. Develop simple java servlet that handle HTTP Request and Response (June 2012)
13. What are servlets? Briefly explain the application of servlets in web programming (dec
2010)