Professional Documents
Culture Documents
Servlet 3
Servlet 3
Sometimes, the client may ask the Servlet to send the file contents of a
file existing on the server. It is not file download. Here, the Servlet
reads manually line-by-line and send each line separately to client.
<BODY>
<H2> Getting File contents from the Server </H2>
<FORM METHOD="get" ACTION="http://localhost:8888/india/TFRAS">
</FORM>
</BODY>
web.xml entry for Servlet TextFileReadAndSend.java
<servlet>
<servlet-name>snrao1</servlet-name>
<servlet-class>TextFileReadAndSend</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>snrao1</servlet-name>
<url-pattern>/TFRAS</url-pattern>
</servlet-mapping>
Servlet Program: TextFileReadAndSend.java
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.*;
String str;
while( (str = br.readLine()) != null )
{
pw.println(str + "<BR>");
}
br.close();
pw.close();
}
}
BufferedReader br = new BufferedReader(new FileReader("c:/"+name));
The file asked by the user is assumed to exist in C drive. This also can
be taken from client (security may prevent this). Instead, the classpath
of the file can be placed in <context-param> and read into the Servlet.
Reading and sending HTML file contents is very different from text file
and is explained in Read HTML File Contents Example.
ima
ima1
Earlier we did a program where client requested for a text file; but the
case now is with HTML file.
If the user sends a request for HTML file, when it comes to the browser,
it is interpreted and output of the HTML file is obtained and not the
HTML contents as it is. To overcome this, it must be read angle brackets
of the HTML file separately.
In case the file user wanted is a HTML file, the servlet file should be
changed slightly as follows where HTML angle brackets should be read
differently.
<BODY>
<H2> Getting File contents from the Server </H2>
<FORM METHOD="get" ACTION="http://localhost:8888/india/HFS">
</FORM>
</BODY>
web.xml entry for Servlet
<servlet>
<servlet-name>snrao1</servlet-name>
<servlet-class>HTMLFileSend</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>snrao1</servlet-name>
<url-pattern>/HFS</url-pattern>
</servlet-mapping>
Servlet File: HTMLFileSend.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
int k;
char ch;
while( (k = fr.read()) != -1 )
{
ch = (char) k;
if(k == 13) // 13 is ASCII value of new line character
pw.print("<BR>");
else if(ch == '<')
pw.print("<");
else if(ch == '>')
pw.print(">");
else
pw.print(ch);
}
fr.close();
pw.close();
}
}
In the earlier text file reading, We used BufferedReader to read a line
at a time. Now, here FileReader is used to read character by character.
if(k == 13)
If the character read from the file is 13, send a <BR> to client browser.
13 is the ASCII value of new line (obtained with enter key).
If the character read is < angle bracket, send lt; prefixed by & and
similarly with > also.
Finally if not all, send the character itself to client (else condition
is executed).
There is another way of reading HTML file contents and sent to client
which is very easier than this and is explained in
response.getOutputStream() Example.
ima
ima1
W3C (World Wide Consortium) developed these status codes along with the
development of HTTP protocol (originally developed by Web’s inventor, Tim
Berners-Lee in 1992 while developing FTP). A list of status codes is
maintained by The Internet Assigned Numbers Authority (IANA). It is
treated as the official registry of HTTP status codes. Because these are
not proprietary, any Web technology using HTTP protocol can make use of
them like ASP, Servlets/JSP, PHP etc.
Alias name written in the URL (in <form action="xxx"> may not be the same
(for misspelling) as given in web.xml file.
The Servlet may not be placed in the correct directory like "classes"
folder.
The source file of .java extension must have been placed in "classes"
folder instead of its .class file.
If the Programmer can fix anyone of the above mistakes, most probably, he
may come out of the 404 error.
After knowing clearly in a simple way "what a status code is?" and "why
it is needed?", let us dig further in the subject.
A status code is a numeric value with 3 digits. W3C divided all the
status codes broadly into 5 categories starting with digit 1 (of type
1xx), with digit 2 (of type 2xx), with digit 3 (of type 3xx), with digit
4 (of type 4xx) and with digit 5 (of type 5xx).
I. Status codes with Prefix 1 (of type 1xx) : Meant for just Information
Some examples:
II. Status codes with Prefix 2 (of type 2xx) : Means that Web Server
accepted the request successfully
It is not much used (because meant for positive response) and sometimes
not visible to client.
Some examples:
"202" means "Accepted" : The request is accepted for processing but the
processing has not been completed and may be disallowed.
III. Status codes with Prefix 3 (of type 3xx) : Meant for Redirection
(Used when Server redirects the request)
The client requested the Web sever with some URL, but the server may
shift to another URL to fulfil the request.
Some examples:
IV. Status codes with Prefix 4 (of type 4xx) : Client does some errors in
requesting
Some examples:
"400" means "Bad Request" : Request is not honoured by the server due to
malformed URL syntax. The client can repeat the request with some
modifications.
"505" means "HTTP Version Not Supported" : The HTTP version, client used
to send the request, is not supported by the server.
Following table gives you the list of status codes. Only commonly
occurring are given.
Server delivers a message to the client, "404 Not Found". 404 indicates
status code of the response. It is a very commonly occurring status code.
404 indicates:
The source (which can generate the response like a Servlet) requested by
the client does not exist on the Server; that is, server is unable to
locate the source. Here, client is authorized to access.
The hyperlink (URL) may be broken with some extra spaces not required
while it is being typed by the user.
The hyperlink may be a dead hyperlink (which existed earlier but not
now).
The source (URL) must have moved to another server temporarily or
permanently and server is unable to redirect to the new location.
The extension for an HTML file may be .htm or .html. Should be checked
how the server accepts.
For student learning Servlets
Check the spelling of <url-pattern> alias name of Servlet you have typed
in the URL (of <ACTION> attrubute of <FORM> tag).
Check you have placed .java file of .class file of the Servlet in the
Server.
Check where you have placed .class file and it must be classes folder of
Tomcat.
When you correct all, restart the Tomcat and check again.
Now let us study what a WAR file is and its creation etc. WAR stands for
Web ARchive. A WAR file is a JAR file, but contains Web components only.
What does it mean? A JAR can contains any files compressed like text
files, doc files, gif files and excel sheets etc. A WAR file is also a
compressed file like JAR but contains only the Web components like
Servlets, JSPs, web.xml, JavaBeans, Struts and HTML pages etc.
The command to create a WAR file is JAR only (executed from command-
prompt) but extension is .war.
Follow the same 7 Steps – Servlets Tomcat Execution, anyhow a few steps
required are added to the existing and reproduced here.
http://tomcat.apache.org/download-60.cgi
Check with the documentation of what JDK or JRE version is compatible to
the specific Tomcat version. For example I have loaded Tomcat 5.0 and got
compatible JDK 6.0.
While installation, it asks the port number and I have entered 8888
(default is displayed as 8080. I have not preferred 8080 for the reason
on many systems Oracle server will be working on 8080. For this reason
better choose a different port number). Later, give your own password.
Step 1:When installed, Tomcat gives many folders of which a few are given
hereunder used for execution. See the following one.
Note: Now, a fresher should be careful here in the following steps. Steps
are very simple but should be followed carefully. Any small mistake
committed, Tomcat simply refuses to execute your Servlet.
In the above webapps folder create your own new folder. I created and
named it as "india".
Just copy the above WEB-INF folder (ofcourse, along with its
subdirectories) into india folder.
When you did, now you get the following structure. Check it.
C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\india\WEB-
INF
Note 1: Do not confuse now with the WEB-INF folder as WEB-INF exists in
two places – one in ROOT and one in india.
Remember, now onwards when I talk about WEB-INF folder, I mean the WEB-
INF available in india and not in ROOT. This is very important.
Step 5: Giving the alias name to the servlet with Deployment Descriptor.
In the web.xml file add the following code just before </web-app> tag.
<servlet>
<servlet-name>abcd</servlet-name>
<servlet-class>Validation</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>abcd</servlet-name>
<url-pattern>/roses</url-pattern>
</servlet-mapping>
Now the alias name of Validation servlet is roses. Client should call the
Validation servlet with the name roses. Observe, this roses you used in
HTML file.
Now creation and deployment of WAR file is over. Next step is execution.
Include the WAR file name in the client request as follows.
<body>
</form>
</body>
Observe, hyderabad in the action is the WAR file name.
The same Validate servlet of Login Screen Validation is used without any
modification.
Step 7: Open a browser. Open the UserPass.html file from File Menu of the
browser, enter the user name and password and click Send button. Now you
get VALID or INVALID.
Servlets
JavaServer Pages
Utility Classes
Static Documents including, XHTML, images, etc.
Client side classes
Meta information that describes the web application
The standard method for packaging Web applications is to use a Web
ARchive file (WAR). You can create a WAR file by using Java’s archiving
tool jar (jar command). The extension must be .war
greetings is a folder that contains all the files required for a WAR
file. A WAR file should contain all the files to make it to work
independently as one unit.
Now run the weblogic server and type from the browser prompt as follows:
http://localhost:7001/wishes/myData
A similar program is available but creating WAR file in Tomcat server WAR
File in Tomcat with Creation, Deployment, Execution.
Java PrintWriter Vs ServletOutputStream:::
We know when the user clicks a submit button or hyper link, a request
goes to a Servlet. The Servlet container loads the Servlet, calls
implicitly the service(HttpServletRequest request, HttpServletResponse
response) method. The parameter objects request and response has a
gigantic responsibilities. The request object is meant to receive the
data from client and response object is meant to send data to client. If
the Programmer can take care of these two objects, the functionality
(purpose) of Servlet is over.
Earlier we have seen the ways of receiving data from client. Now let us
do with response. The response object functionality is to send data to
client of what client is interested. For this, response uses IO Streams.
There are two streams involved depending on the nature of data like text
data or binary data. For text data, the response uses PrintWriter and for
binary data it uses ServletOutputStream. Two methods exist in
ServletResponse interface (inherited by HttpServletResponse) to return
the objects of PrintWriter and ServletOutputStream – getWriter() and
getOuptputStream(). That is, there are two styles exist.
First let us see what Servlet API says about these methods defined in
javax.servlet.ServletResponse interface.
Sometimes, the Servlet may need to send images and JAR files etc. to the
client. They do not include text data. To send them to client, the
Programmer should convert this data into binary format and to send this
binary data to client, the ServletOutputStream is used.
image
Observe the hierarchy and understand the relationship between the three
(involved in multilevel inheritance). With the observation, a conclusion
can be arrived, to write a Servlet three ways exist.
1. Servlet interface
2. GenericServlet
Signature:
3. HttpServlet
When HTTP protocol was developed by W3C people to suit more Web
requirements, the Servlet designers introduced HttpServlet to suit more
for HTTP protocol. HttpServlet is protocol dependent and used specific to
HTTP protocol only.
Signature:
When the client clicks the submit button and sends a request to the
server to invoke some Servlet (by giving the alias name of Servlet), the
Servlet container loads the servlet and calls the service() method. The
container also creates objects of ServeltRequest and ServletResponse and
passes them to service() method. The ServletRequest receives the data
sent by the client (which the Programmer can extract in the program) and
ServletResponse is responsible to send the data required by the client.
This we studied in First Example – Login Screen Validation.
ServletRequest HttpServletRequest
Belongs to javax.servlet package Belongs to javax.servlet.http package
— sub interface of ServletRequest
Comes with many methods like getParameter() etc. It inherits all the
methods of ServletRequest and apart adds its own like getQueryString()
etc.
Used in combination with GenericServlet Used in combination with
HttpServlet
Protocol independent Protocol dependent and specific for HTTP protocol
When HTTP was not used, in earlier days, when a request came from client,
Web container used to create an object of ServletRequest and passed to
service() method. When a request comes from client using HTTP
protocol, Web container creates an object of HttpServletRequest and
passes to service() method
Something more to know:
1. With HTTP protocol also, GenericServlet and ServletRequest can be
used. The container creates an object of HttpServletRequest (because
request is coming from client using HTTP) and passes to ServletRequest,
if ServletRequest is required by the container. The actual implementation
is left to the Web server designers.
ServletResponse HttpServletResponse
Belongs to javax.servlet package Belongs to javax.servlet.http package
— sub interface of ServletResponse
Comes with many methods like getWriter() etc. It inherits all the
methods of ServletResponse and apart adds its own like encodeURL() and
sendRedirect() etc.
Used in combination with GenericServlet Used in combination with
HttpServlet
Protocol independent Protocol dependent and specific for HTTP protocol
When HTTP was not used, in earlier days, when a request came from client,
Web container used to create an object of ServletResponse and passed to
service() method. When a request comes from client using HTTP
protocol, Web container creates an object of HttpServletResponse and
passes to service() method
Something more to know: