Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: discrete mathematics full notes (engineering) btech
Description: this PDF will provide you full notes of discrete mathematics subject ! it's easy way to understand critical solution in easy way ! try it
Description: this PDF will provide you full notes of discrete mathematics subject ! it's easy way to understand critical solution in easy way ! try it
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
Java Servlets
About the Tutorial
Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs
...
This tutorial will teach you how to use Java Servlets to develop your web based
applications in simple and easy steps
...
After completing this tutorial you will find yourself at a
moderate level of expertise in using Java Servlets from where you can take yourself to
next levels
...
It will be
great if you have a basic understanding of web application and how internet works
...
Ltd
...
Ltd
...
We strive to update the contents of our website and tutorials as timely and as precisely
as possible, however, the contents may contain inaccuracies or errors
...
Ltd
...
If you discover any errors on our
website or in this tutorial, please notify us at contact@tutorialspoint
...
i
Audience
...
i
Table of Content
...
SERVLETS – OVERVIEW
...
2
Servlets Packages
...
2
2
...
3
Setting up Java Development Kit
...
3
Setting Up the CLASSPATH
...
SERVLETS – LIFE CYCLE
...
7
The service() Method
...
8
The doPost() Method
...
8
Architecture Diagram
...
SERVLETS – EXAMPLES
...
10
Compiling a Servlet
...
11
ii
Java Servlets
5
...
13
GET Method
...
13
Reading Form Data using Servlet
...
14
GET Method Example Using Form
...
16
Passing Checkbox Data to Servlet Program
...
20
6
...
24
Methods to read HTTP Header
...
27
7
...
30
Methods to Set HTTP Response Header
...
33
8
...
36
Methods to Set HTTP Status Code
...
39
9
...
41
Servlet Filter Methods
...
42
Servlet Filter Mapping in Web
...
43
Using Multiple Filters
...
44
iii
Java Servlets
10
...
46
web
...
46
Request Attributes – Errors/Exceptions
...
48
11
...
52
The Anatomy of a Cookie
...
53
Setting Cookies with Servlet
...
56
Delete Cookies with Servlet
...
SERVLETS – SESSION TRACKING
...
62
Hidden Form Fields
...
62
The HttpSession Object
...
64
Deleting Session Data
...
SERVLETS – DATABASE ACCESS
...
69
Create Data Records
...
70
14
...
74
Creating a File Upload Form
...
75
Compile and Running Servlet
...
SERVLET – HANDLING DATE
...
81
Date Comparison
...
82
Simple DateFormat Format Codes
...
SERVLETS – PAGE REDIRECTION
...
SERVLETS – HITS COUNTER
...
87
18
...
92
Auto Page Refresh Example
...
SERVLETS – SENDING EMAIL
...
95
Send an HTML Email
...
100
User Authentication Part
...
SERVLETS – PACKAGING
...
104
Compiling Servlets in Packages
...
106
21
...
107
System
...
println()
...
107
Using JDB Debugger
...
109
Client and Server Headers
...
109
22
...
111
Detecting Locale
...
113
Locale Specific Dates
...
115
Locale Specific Percentage
...
SERVLET – ANNOTATIONS
...
120
@WebInitParam
...
123
vi
1
...
Using Servlets, you can collect input from users through web page forms, present
records from a database or another source, and create web pages dynamically
...
But Servlets offer several advantages in comparison
with the CGI
...
Servlets execute within the address space of a Web server
...
Servlets are platform-independent because they are written in Java
...
So servlets are trusted
...
It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already
...
1
Java Servlets
Servlets Tasks
Servlets perform the following major tasks:
Read the explicit data sent by the clients (browsers)
...
Read the implicit HTTP request data sent by the clients (browsers)
...
Process the data and generate the results
...
Send the explicit data (i
...
, the document) to the clients (browsers)
...
Send the implicit HTTP response to the clients (browsers)
...
g
...
Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that supports
the Java Servlet specification
...
servlet and javax
...
http packages,
which are a standard part of the Java's enterprise edition, an expanded version of the
Java class library that supports large-scale development projects
...
At the time of writing
this tutorial, the versions are Java Servlet 2
...
1
...
After you
install the servlet packages and add them to your computer's Classpath, you can compile
servlets with the JDK's Java compiler or any other current compiler
...
So
fasten your belt for a nice drive with Servlets
...
2
Java Servlets
2
...
Like any other Java program, you need to compile a servlet by using the Java compiler
javac and after compilation the servlet application, it would be deployed in a configured
environment to test and run
...
You can download SDK from Oracle's Java site: Java SE Downloads
...
Finally set PATH and JAVA_HOME environment variables to refer to
the directory that contains java and javac, typically java_install_dir/bin and
java_install_dir respectively
...
8
...
bat file
...
8
...
8
...
Then, you would update the
PATH value and press the OK button
...
), if the SDK is installed in /usr/local/jdk1
...
0_65 and you
use the C shell, you would put the following into your
...
setenv PATH /usr/local/jdk1
...
0_65/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1
...
0_65
Alternatively, if you use an Integrated Development Environment (IDE) like Borland
JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to
confirm that the IDE knows where you installed Java
...
Some web
servers are freely downloadable and Tomcat is one of them
...
Here are the steps to setup Tomcat on
your machine:
Download latest version of Tomcat from http://tomcat
...
org/
...
For example in C:\apache-tomcat-8
...
28 on windows, or
/usr/local/apache-tomcat-8
...
289 on Linux/Unix and create CATALINA_HOME
environment variable pointing to these locations
...
bat
or
C:\apache-tomcat-8
...
28\bin\startup
...
) machine:
$CATALINA_HOME/bin/startup
...
0
...
sh
After startup, the default web applications included with Tomcat will be available by
visiting http://localhost:8080/
...
apache
...
0
...
) machine:
/usr/local/apache-tomcat-8
...
28/bin/shutdown
...
If you are running Windows, you need to put the following lines in your C:\autoexec
...
set CATALINA=C:\apache-tomcat-8
...
28
set CLASSPATH=%CATALINA%\common\lib\servlet-api
...
Then, you would update the CLASSPATH value and
press the OK button
...
), if you are using the C shell, you would put the following
lines into your
...
setenv CATALINA=/usr/local/apache-tomcat-8
...
28
5
Java Servlets
setenv CLASSPATH $CATALINA/common/lib/servlet-api
...
6
3
...
The following are the paths followed by a servlet
The servlet is initialized by calling the init () method
...
The servlet is terminated by calling the destroy() method
...
Now let us discuss the life cycle methods in detail
...
It is called only when the servlet is created, and not
called for any user requests afterwards
...
The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first
started
...
The init() method simply creates or loads some data that will be used
throughout the life of the servlet
...
}
The service() Method
The service() method is the main method to perform the actual task
...
e
...
Each time the server receives a request for a servlet, the server spawns a new thread
and calls service
...
) and calls doGet, doPost, doPut, doDelete, etc
...
7
Java Servlets
Here is the signature of this method:
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}
The service () method is called by the container and service method invokes doGe,
doPost, doPut, doDelete, etc
...
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
...
Here is the signature of these two methods
...
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD
and it should be handled by doPost() method
...
This
method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup
activities
...
The destroy method definition looks like this:
8
Java Servlets
public void destroy() {
// Finalization code
...
First the HTTP requests coming to the server are delegated to the servlet
container
...
Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of the
servlet
...
Servlets – Examples
Java Servlets
Servlets are Java classes which service HTTP requests and implement the
javax
...
Servlet interface
...
servlet
...
HttpServlet, an abstract class that implements the Servlet
interface and is specially designed to handle HTTP requests
...
io
...
servlet
...
servlet
...
*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException
{
// Do required initialization
message = "Hello World";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response
...
PrintWriter out = response
...
println("
" + message + "
");}
public void destroy()
{
// do nothing
...
java with the code shown above
...
This path location
must be added to CLASSPATH before proceeding further
...
java as follows:
$ javac HelloWorld
...
I have included only servlet-api
...
This command line uses the built-in javac compiler that comes with the Sun
Microsystems Java Software Development Kit (JDK)
...
If everything goes fine, above compilation would produce HelloWorld
...
Next section would explain how a compiled servlet would be deployed in
production
...
If you have a fully qualified class name of com
...
MyServlet, then this servlet
class must be located in WEB-INF/classes/com/myorg/MyServlet
...
For
now,
let
us
copy
HelloWorld
...
xml file
located in
11
Java Servlets
Above entries to be created inside
...
xml
file
...
You are almost done, now let us start tomcat server using
...
sh
(on
Linux/Solaris
etc
...
If everything goes
fine, you would get the following result:
12
5
...
The browser
uses two methods to pass this information to web server
...
GET Method
The GET method sends the encoded user information appended to the page request
...
test
...
Never use the
GET method if you have password or other sensitive information to pass to the server
...
This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests using
doGet() method
...
This packages the information in exactly the same way as GET method,
but instead of sending it as a text string after a ? (question mark) in the URL it sends it
as a separate message
...
Servlet handles this
type of requests using doPost() method
...
getParameter() method to get the value of a
form parameter
...
getParameterNames(): Call this method if you want a complete list of all
parameters in the current request
...
http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI
Given below is the HelloForm
...
We are going to use getParameter() method which makes it very easy to
access passed information:
// Import required java libraries
import java
...
*;
import javax
...
*;
import javax
...
http
...
setContentType("text/html");
PrintWriter out = response
...
0 " +
"transitional//en\">\n";
out
...
getParameter("first_name") + "\n" +
"
14
Java Servlets
+ request
...
java as follows:
$ javac HelloForm
...
class file
...
xml file
located in
Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your
browser's Location:box and make sure you already started tomcat server, before firing
above command in the browser
...
We are going to use same Servlet HelloForm to handle this imput
...
htm and put it in
directory
...
htm, here is the actual output of the above form
...
Based on the input provided, it will
generate similar result as mentioned in the above example
...
Below is HelloForm
...
// Import required java libraries
import java
...
*;
import javax
...
*;
import javax
...
http
...
16
Java Servlets
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response
...
getWriter();
String title = "Using GET Method to Read Form Data";
String docType =
" ...
println(docType +
"\n" +
"
"\n" +
"
" + title + "
\n" +"
- \n" +
- First Name: "
+ request
...
getParameter("last_name") + "\n" +
"
"
"");
}
// Method to handle POST method request
...
htm with the POST
method as follows:
17
Java Servlets
Here is the actual output of the above form, Try to enter First and Last Name and then
click submit button to see the result on your local machine where tomcat is running
...
Passing Checkbox Data to Servlet Program
Checkboxes are used when more than one option is required to be selected
...
htm, for a form with two checkboxes
The result of this code is the following form
18
Java Servlets
Maths
Physics
Chemistry Select Subject
Selected Subject
Given below is the CheckBox
...
// Import required java libraries
import java
...
*;
import javax
...
*;
import javax
...
http
...
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response
...
getWriter();
String title = "Reading Checkbox Data";
String docType =
" ...
println(docType +
"\n" +
"
"\n" +
"
" + title + "
\n" +"
- \n" +
- Maths Flag : : "
+ request
...
getParameter("physics") + "\n" +
19
Java Servlets
" - Chemistry Flag: : "
+ request
...
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
For the above example, it would display following result:
Reading Checkbox Data
Maths Flag : : on
Physics Flag: : null
Chemistry Flag: : on
Reading All Form Parameters
Following is the generic example which uses getParameterNames() method of
HttpServletRequest to read all the available form parameters
...
Once we have an Enumeration, we can loop down the Enumeration in standard way by,
using hasMoreElements() method to determine when to stop and using nextElement()
method to get each parameter name
...
io
...
servlet
...
servlet
...
*;
import java
...
*;
// Extend HttpServlet class
public class ReadParams extends HttpServlet {
// Method to handle GET method request
...
setContentType("text/html");
PrintWriter out = response
...
0 " +
"transitional//en\">\n";
out
...
getParameterNames();
while(paramNames
...
nextElement();
out
...
getParameterValues(paramName);
// Read single valued data
if (paramValues
...
length() == 0)
out
...
println(paramValue);
} else {
// Read multiple valued data
out
...
length; i++) {
out
...
println("
"
}
}
out
...
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Now, try the above servlet with the following form:
22
Java Servlets
Now calling servlet using the above form would generate the following result:
Reading All Form Parameters
Param
Value(s)
maths
on
chemistry
on
You Cccdtry the above servlet to read any other form's data having other objects like text
can
box, radio button or drop down box etc
...
Servlets – Client HTTP Request
When a browser requests for a web page, it sends lot of information to the web server
which cannot be read directly because this information travel as a part of header of HTTP
request
...
Following is the important header information which comes from browser side and you
would use very frequently in web programming:
Header
Description
Accept
This header specifies the MIME types that the browser or
other clients can handle
...
Accept-Charset
This header specifies the character sets the browser can use
to display the information
...
Accept-Encoding
This header specifies the types of encodings that the
browser knows how to handle
...
Accept-Language
This header specifies the client's preferred languages in
case the servlet can produce results in more than one
language
...
Authorization
This header is used by clients to identify themselves when
accessing password-protected Web pages
...
Persistent connections permit
the client or other browser to retrieve multiple files with a
single request
...
Cookie
This header returns cookies to servers that previously sent
them to the browser
...
If-Modified-Since
This header indicates that the client wants the page only if it
has been changed after the specified date
...
24
Java Servlets
If-Unmodified-Since
This header is the reverse of If-Modified-Since; it specifies
that the operation should succeed only if the document is
older than the specified date
...
For example, if you are at Web page 1 and click on a link to
Web page 2, the URL of Web page 1 is included in the
Referrer header when the browser requests Web page 2
...
Methods to read HTTP Header
There are following methods which can be used to read HTTP header in your servlet
program
...
S
...
Method & Description
1
Cookie[] getCookies()
Returns an array containing all of the Cookie objects the client sent with this
request
...
3
Enumeration getHeaderNames()
Returns an enumeration of all the header names this request contains
...
5
HttpSession getSession()
Returns the current session associated with this request, or if the request does
not have a session, creates one
...
7
Locale getLocale()
Returns the preferred Locale that the client will accept content in, based on the
Accept-Language header
...
9
ServletInputStream getInputStream()
Retrieves the body of the request as binary data using a ServletInputStream
...
11
String getCharacterEncoding()
Returns the name of the character encoding used in the body of this request
...
13
String getContextPath()
Returns the portion of the request URI that indicates the context of the request
...
15
String getMethod()
Returns the name of the HTTP method with which this request was made, for
example, GET, POST, or PUT
...
17
String getPathInfo()
Returns any extra path information associated with the URL the client sent when
it made this request
...
19
String getQueryString()
Returns the query string that is contained in the request URL after the path
...
21
String getRemoteHost()
Returns the fully qualified name of the client that sent the request
...
23
String getRequestURI()
Returns the part of this request's URL from the protocol name up to the query
string in the first line of the HTTP request
...
25
String getServletPath()
Returns the part of this request's URL that calls the JSP
...
27
boolean isSecure()
Returns a Boolean indicating whether this request was made using a secure
channel, such as HTTPS
...
29
int getIntHeader(String name)
Returns the value of the specified request header as an int
...
HTTP Header Request Example
Following is the example which uses getHeaderNames() method of HttpServletRequest
to read the HTTP header information
...
Once we have an Enumeration, we can loop down the Enumeration in the standard
manner, using hasMoreElements() method to determine when to stop and using
nextElement() method to get each parameter name
...
io
...
servlet
...
servlet
...
*;
import java
...
*;
// Extend HttpServlet class
public class DisplayHeader extends HttpServlet {
// Method to handle GET method request
...
setContentType("text/html");
PrintWriter out = response
...
0 " +
"transitional//en\">\n";
out
...
getHeaderNames();
while(headerNames
...
nextElement();
out
...
getHeader(paramName);
out
...
println("\n");
}
// Method to handle POST method request
...
0 (compatible; MSIE 7
...
1;
Trident/4
...
2; MS-RTC LM 8)
accept-encoding
gzip, deflate
host
localhost:8080
connection
Keep-Alive
cache-control
no-cache
29
Java Servlets
7
...
A typical response looks like this:
HTTP/1
...
...
(Blank Line)
...
...
1 in the example), a status code
(200 in the example), and a very short message corresponding to the status code (OK in
the example)
...
1 response headers which go back to
the browser from web server side and you would use them very frequently in web
programming:
Header
Description
Allow
This header specifies the request methods (GET, POST, etc
...
Cache-Control
This header specifies the circumstances in which the
response document can safely be cached
...
Public means document is
cacheable, Private means document is for a single user and
can only be stored in private (non-shared) caches and nocache means document should never be cached
...
A value of close instructs the
browser not to use persistent HTTP connections and keepalive means using persistent connections
...
Content-Encoding
This header specifies the way in which the page was encoded
during transmission
...
For example en, en-us, ru, etc
...
This information is needed only if the browser is using a
persistent (keep-alive) HTTP connection
...
Expires
This header specifies the time at which the content should be
considered out-of-date and thus no longer be cached
...
The client can then cache the document and supply a date by
an If-Modified-Since request header in later requests
...
This notifies the browser of the
document address
...
Refresh
This header specifies how soon the browser should ask for an
updated page
...
Retry-After
This header can be used in conjunction with a 503 (Service
Unavailable) response to tell the client how soon it can repeat
its request
...
31
Java Servlets
Methods to Set HTTP Response Header
There are following methods which can be used to set HTTP response header in your
servlet program
...
S
...
1
2
3
Method & Description
String encodeRedirectURL(String url)
Encodes the specified URL for use in the sendRedirect method or, if encoding is
not needed, returns the URL unchanged
...
boolean containsHeader(String name)
Returns a Boolean indicating whether the named response header has already
been set
...
5
void addCookie(Cookie cookie)
Adds the specified cookie to the response
...
7
void addHeader(String name, String value)
Adds a response header with the given name and value
...
9
void flushBuffer()
Forces any content in the buffer to be written to the client
...
11
void resetBuffer()
Clears the content of the underlying buffer in the response without clearing
headers or status code
...
13
14
15
16
void sendError(int sc, String msg)
Sends an error response to the client using the specified status
...
void setBufferSize(int size)
Sets the preferred buffer size for the body of the response
...
void setContentLength(int len)
Sets the length of the content body in the response In HTTP servlets, this
method sets the HTTP Content-Length header
...
void setDateHeader(String name, long date)
Sets a response header with the given name and date-value
...
void setIntHeader(String name, int value)
Sets a response header with the given name and integer value
...
void setStatus(int sc)
Sets the status code for this response
...
// Import required java libraries
import java
...
*;
import javax
...
*;
import javax
...
http
...
util
...
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set refresh, autoload time as 5 seconds
response
...
setContentType("text/html");
33
Java Servlets
// Get current time
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar
...
HOUR);
int minute = calendar
...
MINUTE);
int second = calendar
...
SECOND);
if(calendar
...
AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
PrintWriter out = response
...
0 " +
"transitional//en\">\n";
out
...
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
34
Java Servlets
Now calling the above servlet would display current system time after every 5 seconds
as follows
...
Servlets – Http Status Codes
The format of the HTTP request and HTTP response messages are similar and will have
following structure:
An initial status line + CRLF ( Carriage Return + Line Feed i
...
New Line )
Zero or more header lines + CRLF
A blank line, i
...
, a CRLF
An optional message body like file, query data or query output
...
1 200 OK
Content-Type: text/html
Header2:
...
HeaderN:
...
>
...
The status line consists of the HTTP version (HTTP/1
...
Following is a list of HTTP status codes and associated messages that might be returned
from the Web Server:
Code
Message
Description
100
Continue
Only a part of the request has been received by
the server, but as long as it has not been
rejected, the client should continue with the
request
101
Switching Protocols
The server switches protocol
...
203
Non-authoritative
Information
204
No Content
205
Reset Content
206
Partial Content
300
Multiple Choices
A link list
...
Maximum five addresses
301
Moved Permanently
The requested page has moved to a new url
302
Found
The requested page has moved temporarily to
a new url
303
See Other
The requested page can be found under a
different url
304
Not Modified
305
Use Proxy
306
Unused
This code was used in a previous version
...
307
Temporary Redirect
The requested page has moved temporarily to
a new url
...
405
Method Not Allowed
The method specified in the request is not
allowed
...
407
Proxy Authentication
Required
You must authenticate with a proxy server
before this request can be served
...
409
Conflict
The request could not be completed because of
a conflict
...
411
Length Required
The "Content-Length" is not defined
...
412
Precondition Failed
The precondition given in the request evaluated
to false by the server
...
414
Request-url Too Long
The server will not accept the request, because
the url is too long
...
415
Unsupported Media Type
The server will not accept the request, because
the media type is not supported
...
The server
met an unexpected condition
501
Not Implemented
The request was not completed
...
502
Bad Gateway
The request was not completed
...
The server is
temporarily overloading or down
...
505
HTTP Version Not Supported
The server does not support the "http protocol"
version
...
These methods are available with HttpServletResponse object
...
N
...
The setStatus method takes an int
(the status code) as an argument
...
public void sendRedirect(String url)
1
2
This method generates a 302 response along with a Location header giving the
URL of the new document
...
HTTP Status Code Example
Following is the example which would send a 407 error code to the client browser and
browser would show you "Need authentication!!!" message
...
io
...
servlet
...
servlet
...
*;
import java
...
*;
// Extend HttpServlet class
public class showError extends HttpServlet {
// Method to handle GET method request
...
response
...
39
Java Servlets
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Now calling the above servlet would display the following result:
HTTP Status 407 - Need authentication!!!
type Status report
messageNeed authentication!!!
descriptionThe client must first authenticate itself with the proxy (Need
authentication!!!)
...
5
...
Servlets – Writing Filters
Java Servlets
Servlet Filters are Java classes that can be used in Servlet Programming for the following
purposes:
To intercept requests from a client before they access a resource at back end
...
There are various types of filters suggested by the specifications:
Authentication Filters
Data compression Filters
Encryption Filters
Filters that trigger resource access events
Image Conversion Filters
Logging and Auditing Filters
MIME-TYPE Chain Filters
Tokenizing Filters
XSL/T Filters That Transform XML Content
Filters are deployed in the deployment descriptor file web
...
When the web container starts up your web application, it creates an instance of each
filter that you have declared in the deployment descriptor
...
Servlet Filter Methods
A filter is simply a Java class that implements the javax
...
Filter interface
...
servlet
...
N
...
public void init(FilterConfig filterConfig)
This method is called by the web container to indicate to a filter that it is being
placed into service
...
41
Java Servlets
Servlet Filter – Example
Following is the Servlet Filter Example that would print the clients IP address and current
date time
...
io
...
servlet
...
servlet
...
*;
import java
...
*;
// Implements Filter class
public class LogFilter implements Filter
public void
{
init(FilterConfig config)
throws ServletException{
// Get init parameter
String testParam = config
...
out
...
io
...
String ipAddress = request
...
System
...
println("IP "+ ipAddress + ", Time "
+ new Date()
...
doFilter(request,response);
}
public void destroy( ){
42
Java Servlets
/* Called before the Filter instance is removed
from service by the web container*/
}
}
Compile LogFilter
...
Servlet Filter Mapping in Web
...
Create the following entry for filter
tag in the deployment descriptor file web
...
You can specicy a particular servlet path if you want to apply filter on few
servlets only
...
You can use Log4J logger to log above log in a separate file
...
Consider, you define two filters AuthenFilter and LogFilter
...
xml determines the order in which the web
container applies the filter to the servlet
...
xml file
...
Servlets – Exception Handling
When a servlet throws an exception, the web container searches the configurations in
web
...
You would have to use the error-page element in web
...
web
...
Following would be the entry created in web
...
46
Java Servlets
javax
...
ServletException
...
IOException
If you want to have a generic Error Handler for all the exceptions then you should define
following error-page instead of defining separate error-page elements for every
exception:
...
Throwable
Following are the points to be noted about above web
...
xml
...
If the web application throws either ServletException or IOException, then the
web container invokes the /ErrorHandler servlet
...
Above example is very much generic and hope it serve the purpose to
explain you the basic concept
...
S
...
1
2
Attribute & Description
javax
...
error
...
lang
...
javax
...
error
...
lang
...
47
Java Servlets
javax
...
error
...
lang
...
javax
...
error
...
lang
...
javax
...
error
...
javax
...
error
...
lang
...
Error Handler Servlet – Example
This example would give you basic understanding of Exception Handling in Servlet, but
you can write more sophisticated filter applications using the same concept:
// Import required java libraries
import java
...
*;
import javax
...
*;
import javax
...
http
...
util
...
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Analyze the servlet exception
Throwable throwable = (Throwable)
request
...
servlet
...
exception");
Integer statusCode = (Integer)
request
...
servlet
...
status_code");
String servletName = (String)
request
...
servlet
...
servlet_name");
if (servletName == null){
servletName = "Unknown";
48
Java Servlets
}
String requestUri = (String)
request
...
servlet
...
request_uri");
if (requestUri == null){
requestUri = "Unknown";
}
// Set response content type
response
...
getWriter();
String title = "Error/Exception Information";
String docType =
" ...
println(docType +
"\n" +
"
"\n");
if (throwable == null && statusCode == null){
out
...
println("Please return to the response
...
");
}else if (statusCode != null){
out
...
println("
Error information
");out
...
println("Exception Type : " +
throwable
...
getName( ) +
"");
out
...
println("The exception message: " +
throwable
...
println("");
out
...
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Compile ErrorHandler
...
Let us add the following configuration in web
...
lang
...
For example, if you type a wrong URL then it would display the
following result:
The status code : 404
The above code may not work with some web browsers
...
51
Java Servlets
11
...
Java Servlets transparently supports HTTP cookies
...
For example name, age, or
identification number etc
...
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
...
The Anatomy of a Cookie
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie
directly on a browser)
...
1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1
...
9 (UNIX) PHP/4
...
com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path
and a domain
...
The expires field is an
instruction to the browser to "forget" the cookie after the given time and date
...
If the user points the browser at any page that matches the path and
domain of the cookie, it will resend the cookie to the server
...
0
Connection: Keep-Alive
User-Agent: Mozilla/4
...
2
...
demon
...
uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A servlet will then have access to the cookie through
request
...
the
request
method
Servlet Cookies Methods
Following is the list of useful methods which you can use while manipulating cookies in
servlet
...
N
...
com
...
com
...
If you don't set this, the cookie will last only for the current session
...
public String getName()
This method returns the name of the cookie
...
public void setValue(String newValue)
This method sets the value associated with the cookie
...
public void setPath(String uri)
This method sets the path to which this cookie applies
...
public String getPath()
This method gets the path to which this cookie applies
...
e
...
public void setComment(String purpose)
This method specifies a comment that describes a cookie's purpose
...
public String getComment()
53
Java Servlets
This method returns the comment describing the purpose of this cookie, or null
if the cookie has no comment
...
Cookie cookie = new Cookie("key","value");
Keep in mind, neither the name nor the value should contain white space or any of the
following characters:
[ ] ( ) = , " / ? @ : ;
(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds)
the cookie should be valid
...
cookie
...
addCookie to add cookies in the HTTP response header as follows:
You
use
response
...
// Import required java libraries
import java
...
*;
import javax
...
*;
import javax
...
http
...
Cookie firstName = new Cookie("first_name",
54
Java Servlets
request
...
getParameter("last_name"));
// Set expiry date after 24 Hrs for both the cookies
...
setMaxAge(60*60*24);
lastName
...
response
...
addCookie( lastName );
// Set response content type
response
...
getWriter();
String title = "Setting Cookies Example";
String docType =
" ...
println(docType +
"\n" +
"
"\n" +
"
" + title + "
\n" +"
- \n" +
- First Name: "
+ request
...
getParameter("last_name") + "\n" +
"
"
"");
}
}
Compile the above servlet HelloForm and create appropriate entry in web
...
55
Java Servlets
Keep above HTML content in a file Hello
...
When
you
would
access
http://localhost:8080/Hello
...
First Name:
Last Name:
Submit
Try to enter First Name and Last Name and then click submit button
...
Next section would explain you how you would access these cookies back in your web
application
...
servlet
...
Cookie objects by
calling the getCookies( ) method of HttpServletRequest
...
Example
Let us read cookies which we have set in previous example:
// Import required java libraries
import java
...
*;
import javax
...
*;
import javax
...
http
...
getCookies();
// Set response content type
response
...
getWriter();
String title = "Reading Cookies Example";
String docType =
" ...
println(docType +
"\n" +
"
"\n" );
if( cookies != null ){
out
...
length; i++){
cookie = cookies[i];
out
...
getName( ) + ",
");
out
...
getValue( )+"
");
}
}else{
out
...
println("");
out
...
xml file
...
If you want to delete a cookie then you simply need to
follow up following three steps:
Read an already existing cookie and store it in Cookie object
...
Add this cookie back into response header
...
// Import required java libraries
import java
...
*;
import javax
...
*;
import javax
...
http
...
getCookies();
// Set response content type
response
...
getWriter();
String title = "Delete Cookies Example";
String docType =
" ...
println(docType +
"\n" +
"
"\n" );
if( cookies != null ){
out
...
length; i++){
cookie = cookies[i];
if((cookie
...
compareTo("first_name") == 0 ){
cookie
...
addCookie(cookie);
out
...
getName( ) + "
");
}
out
...
getName( ) + ",
");
out
...
getValue( )+"
");
}
}else{
out
...
println("");
out
...
xml file
...
Start at the Tools menu and
select Internet Options
...
60
Java Servlets
61
Java Servlets
12
...
Still there are following three ways to maintain session between web client and web
server:
Cookies
A webserver can assign a unique session ID as a cookie to each web client and for
subsequent requests from the client they can be recognized using the recieved cookie
...
Hidden Form Fields
A web server can send a hidden HTML form field along with a unique session ID as
follows:
This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or POST data
...
This could be an effective way of keeping track of the session but clicking on a regular
( ...
URL Rewriting
You can append some extra data on the end of each URL that identifies the session, and
the server can associate that session identifier with data it has stored about that session
...
com/file
...
URL rewriting is a better way to maintain sessions and it works even when browsers
don't support cookies
...
62
Java Servlets
The HttpSession Object
Apart from the above mentioned three ways, servlet provides HttpSession Interface
which 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
...
The session persists for a specified time period, across more than one
connection or page request from the user
...
getSession();
You need to call request
...
Here is a summary of the important methods available through HttpSession
object:
S
...
Method & Description
public Object getAttribute(String name)
1
This method returns the object bound with the specified name in this session,
or null if no object is bound under the name
...
public long getCreationTime()
3
This method returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT
...
public long getLastAccessedTime()
This method returns the last accessed time of the session, in the format of
milliseconds since midnight January 1, 1970 GMT
...
public void invalidate()
7
This method invalidates this session and unbinds any objects bound to it
...
63
Java Servlets
public void removeAttribute(String name)
9
This method removes the object bound with the specified name from this
session
...
public void setMaxInactiveInterval(int interval)
11
This method specifies the time, in seconds, between client requests before the
servlet container will invalidate this session
...
We would associate a new session with the
request if one does not already exist
...
io
...
servlet
...
servlet
...
*;
import java
...
*;
// Extend HttpServlet class
public class SessionTrack extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Create a session object if it is already not
created
...
getSession(true);
// Get session creation time
...
getCreationTime());
// Get last access time of this web page
...
getLastAccessedTime());
String title = "Welcome Back to my website";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
64
Java Servlets
String userIDKey = new String("userID");
String userID = new String("ABCD");
// Check if this is new comer on your web page
...
isNew()){
title = "Welcome to my website";
session
...
getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session
...
setAttribute(visitCountKey,
visitCount);
// Set response content type
response
...
getWriter();
String docType =
" ...
println(docType +
"\n" +
"
"\n" +
"
" + title + "
\n" +"
Session Infomation
\n" +"
Session info | value |
---|---|
id | \n" +" + session ... xml file ... Welcome to my website Session Infomation Session info value id 0AE3EC93FF44E3C525B4351B77ABB2D5 Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010 Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010 User ID ABCD Number of visits 0 Deleting Session Data When you are done with a user's session data, you have several options: Remove a particular attribute: You can call public void removeAttribute(String name) method to delete the value associated with a particular key ... Setting Session timeout: You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually ... 4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users ... xml Configuration: If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web ... 67 Java Servlets The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat ... So if your session is configured in web ... 68 Java Servlets 13 ... Before starting with database access through a servlet, make sure you have proper JDBC environment setup along with a database ... To start with basic concept, let us create a simple table and create few records in that table as follows: Create Table To create the Employees table in TEST database, use the following steps: Step 1 Open a Command Prompt and change to the installation directory as follows: C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin> Step 2 Login to database as follows C:\Program Files\MySQL\bin>mysql -u root -p Enter password: ******** mysql> Step 3 Create table Employee in TEST database as follows: mysql> use TEST; mysql> create table Employees ( id int not null, age int not null, first varchar (255), last varchar (255) 69 Java Servlets ); Query OK, 0 rows affected (0 ... 05 sec) mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma'); Query OK, 1 row affected (0 ... 00 sec) mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal'); Query OK, 1 row affected (0 ... // Loading required libraries import java ... *; import java ... *; import javax ... *; import javax ... http ... sql ... mysql ... Driver"; static final String DB_URL="jdbc:mysql://localhost/TEST"; // Database credentials static final String USER = "root"; static final String PASS = "password"; // Set response content type response ... getWriter(); String title = "Database Result"; String stmt = null; String docType = " ... println(docType + "\n" + " "\n" + " " + title + "\n");try{ // Register JDBC driver Class ... mysql ... Driver"); // Open a connection conn = DriverManager ... createStatement(); String sql; sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt ... next()){ //Retrieve by column name int id = rs ... getInt("age"); String first = rs ... getString("last"); //Display values out ... println(", Age: " + age + " "); out ... println(", Last: " + last + " "); } out ... close(); stmt ... close(); }catch(SQLException se){ //Handle errors for JDBC se ... forName e ... close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn ... printStackTrace(); }//end finally try } //end try } } Now let us compile above servlet and create following entries in web ... ... Servlets – File Uploading Java Servlets A Servlet can be used with an HTML form tag to allow users to upload files to the server ... Creating a File Upload Form The following HTM code below creates an uploader form ... The form enctype attribute should be set to multipart/form-data ... Following example is using UploadServlet servlet to upload file ... /> tag with attribute type="file" ... The browser associates a Browse button with each of them ... Writing Backend Servlet Following is the servlet UploadServlet which would take care of accepting uploaded file and to store it in directory ... xml as follows: ... 0 ... Following is the source code for UploadServlet which can handle multiple file uploading at a time ... x ... jar file in your classpath ... apache ... FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x ... jar file in your classpath ... apache ... 75 Java Servlets While testing following example, you should upload a file which has less size than maxFileSize otherwise file would not be uploaded ... 0 ... c:\temp and c:\apache-tomcat- // Import required java libraries import java ... *; import java ... *; import javax ... ServletConfig; import javax ... ServletException; import javax ... http ... servlet ... HttpServletRequest; import javax ... http ... apache ... fileupload ... apache ... fileupload ... apache ... fileupload ... DiskFileItemFactory; import org ... commons ... servlet ... apache ... io ... *; public class UploadServlet extends HttpServlet { private boolean isMultipart; private String filePath; private int maxFileSize = 50 * 1024; private int maxMemSize = 4 * 1024; private File file ; public void init( ){ // Get the file location where it would be stored ... getInitParameter("file-upload"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java ... IOException { 76 Java Servlets // Check that we have a file upload request isMultipart = ServletFileUpload ... setContentType("text/html"); java ... PrintWriter out = response ... println(""); out ... println(" out ... println(""); out ... println(""); out ... setSizeThreshold(maxMemSize); // Location to save data that is larger than maxMemSize ... setRepository(new File("c:\\temp")); // Create a new file upload handler ServletFileUpload upload = new ServletFileUpload(factory); // maximum file size to be uploaded ... setSizeMax( maxFileSize ); try{ // Parse the request to get file items ... parseRequest(request); // Process the uploaded file items Iterator i = fileItems ... println(""); out ... println(" 77 Java Servlets out ... println(""); while ( i ... next(); if ( !fi ... getFieldName(); String fileName = fi ... getContentType(); boolean isInMemory = fi ... getSize(); // Write the file if( fileName ... substring( fileName ... substring(fileName ... write( file ) ; out ... println(""); out ... out ... io ... getName( )+": POST method required ... xml file as follows ... When you would try http://localhost:8080/UploadFile ... File Upload: Select a file to upload: Choose File No File Chosen Upload File If your servlet script works fine, your file should be uploaded in c:\apache-tomcat8 ... 28\webapps\data\ directory ... Servlet – Handling Date Java Servlets One of the most important advantages of using Servlet is that you can use most of the methods available in core Java ... util package, this class encapsulates the current date and time ... The first constructor initializes the object with the current date and time ... boolean before(Date date) Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns false ... int compareTo(Date date) Compares the value of the invoking object with that of date ... Returns a negative value if the invoking object is earlier than date ... int compareTo(Object obj) Operates identically to compareTo(Date) if obj is of class Date ... boolean equals(Object date) Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns false ... int hashCode( ) Returns a hash code for the invoking object ... String toString( ) Converts the invoking Date object into a string and returns the result ... You can use a simple Date object with toString() method to print current date and time as follows: // Import required java libraries import java ... *; import java ... Date; import javax ... *; import javax ... http ... setContentType("text/html"); PrintWriter out = response ... 0 " + "transitional//en\">\n"; out ... toString() + "\n" + ""); } } 81 Java Servlets Now let us compile above servlet and create appropriate entries in web ... This would produce following result: Display Current Date & Time Mon Jun 21 21:46:49 GMT+04:00 2010 Try to refresh URL http://localhost:8080/CurrentDate and you would find difference in seconds every time you would refresh ... In case you need to compare two dates, following are the methods: You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970, for both objects and then compare these two values ... Because the 12th of the month comes before the 18th, for example, new Date(99, 2, 12) ... You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date ... SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting ... io ... text ... util ... servlet ... servlet ... *; // Extend HttpServlet class public class CurrentDate extends HttpServlet { 82 Java Servlets public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response ... getWriter(); String title = "Display Current Date & Time"; Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("E yyyy ... dd 'at' hh:mm:ss a zzz"); String docType = " ... println(docType + "\n" + " "\n" + " " + title + "\n" +" " + ft |