Advance java Notes
Advance java Notes
Collection of Framework
What is a Java Collection Framework ?
• Interfaces:
• Interface in Java refers to the abstract data types. They allow Java
collections to be manipulated independently from the details of their
representation. Also, they form a hierarchy in object-oriented
programming languages.
• Classes:
• Classes in Java are the implementation of the collection interface. It
basically refers to the data structures that are used again and again.
• Algorithm: Algorithm refers to the methods which are used to
perform operations such as searching and sorting, on objects that
implement collection interfaces. Algorithms are polymorphic in
nature as the same method can be used to take many forms or you
can say perform different implementations of the Java collection
interface.
Java Collections : Interface
boolean add( Object o) It is used to append the specified element to the end of the vector.
boolean contains(Object
Returns true if this list contains the specified element.
o)
boolean remove(Object o) Removes the first occurrence of the specified element from this list.
int indexOf(Object
Returns the index of the first occurrence of the specified element in this list, or -1.
element)
int lastIndexOf(Object
Returns the index of the last occurrence of the specified element in this list, or -1.
element)
Doubly Linked List:
• In a doubly Linked list, it has two references, one to the next node and
another to previous node.
Method Description
boolean It is used to append the specified element to the end of the
add( Object o) vector.
boolean
contains(Object Returns true if this list contains the specified element.
o)
void add (int
index, Object Inserts the element at the specified element in the vector.
element)
Vectors
• Vectors are similar to arrays, where the elements of the vector object
can be accessed via an index into the vector. Vector implements a
dynamic array. Also, the vector is not limited to a specific size, it can
shrink or grow automatically whenever required. It is similar to
ArrayList, but with two differences :
• Vector is synchronized.
• Vector contains many legacy methods that are not part of the
collections framework.
• Syntax:
• Vector object = new Vector(size,increment);
Method Description
boolean
Appends the specified element to the end of the list.
add(Object o)
void clear() Removes all of the elements from this list.
void add(int
index, Object Inserts the specified element at the specified position.
element)
boolean
Removes the first occurrence of the specified element from this
remove(Object
list.
o)
boolean
contains(Object Returns true if this list contains the specified element.
element)
int
Returns the index of the first occurrence of the specified
indexOfObject (
Java collections: Queue
boolean
Remove the specified element from the set.
remove(Object o)
Returns a shallow copy of the HashSet instance: the
Object clone()
elements themselves are not cloned.
Object first() Return the first element currently in the sorted set.
Object last() Return the last element currently in the sorted set.
Map
• HashMap
• : this implementation uses a hash table as the underlying data structure. It implements all of
the Mapoperations and allows null values and one null key. This class is roughly equivalent
to Hashtable - a legacy data structure before Java Collections Framework, but it is not synchronized
and permits nulls. HashMap does not guarantee the order of its key-value elements. Therefore,
consider to use a HashMap when order does not matter and nulls are acceptable.
• LinkedHashMap
• : this implementation uses a hash table and a linked list as the underlying data structures, thus the
order of a LinkedHashMap is predictable, with insertion-order as the default order. This
implementation also allows nulls like HashMap. So consider using a LinkedHashMap when you want
a Map with its key-value pairs are sorted by their insertion order.
• TreeMap:
• this implementation uses a red-black tree as the underlying data structure. A TreeMap is sorted
according to the natural ordering of its keys, or by a Comparator provided at creation time. This
implementation does not allow nulls. So consider using a TreeMap when you want a Map sorts its
key-value pairs by the natural order of the keys (e.g. alphabetic order or numeric order), or by a
custom order you specify.
Chapter 2
• A thread
• is a light-weight smallest part of a process that can run concurrently with the
other parts(other threads) of the same process.
• Threads are independent because they all have separate path of execution that’s
the reason if an exception occurs in one thread, it doesn’t affect the execution of
other threads. All threads of a process share the common memory. The process
of executing multiple threads simultaneously is known as multithreading.
• 1. The main purpose of multithreading is to provide simultaneous execution of
two or more parts of a program to maximum utilize the CPU time. A
multithreaded program contains two or more parts that can run concurrently.
Each such part of a program called thread.
Thread
• 2. Threads are lightweight sub-processes, they share the common memory space.
In Multithreaded environment, programs that are benefited from multithreading,
utilize the maximum CPU time so that the idle time can be kept to minimum.
• 3. A thread can be in one of the following states:
NEW – A thread that has not yet started is in this state.
RUNNABLE – A thread executing in the Java virtual machine is in this state.
BLOCKED – A thread that is blocked waiting for a monitor lock is in this state.
WAITING – A thread that is waiting indefinitely for another thread to perform a
particular action is in this state.
TIMED_WAITING – A thread that is waiting for another thread to perform an
action for up to a specified waiting time is in this state.
TERMINATED – A thread that has exited is in this state.
A thread can be in only one state at a given point in time.
Creating a thread in Java
Runnable
NonRunnable
blocked
Running
Terminated
Can we start a thread twice
• No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but
for second time, it will throw exception.
• What if we call run() method directly instead start() method?
• Each thread starts in a separate call stack.
• Invoking the run() method from main thread, the run() method goes onto the
current call stack rather than at the beginning of a new call stack.
• The join() method
• The join() method waits for a thread to die. In other words, it causes the currently
running threads to stop executing until the thread it joins with completes its task
Syntax:
• public void join()throws InterruptedException
• .public void join(long milliseconds)throws InterruptedException.
• getName(),setName(String) and getId() method:
• public String getName()
• public void setName(String name)
• public long getId()
• The currentThread() method:
• The currentThread() method returns a reference to the currently executing
thread object.
• Naming Thread
• The Thread class provides methods to change and get the name of a thread. By
default, each thread has a name i.e. thread-0,
• thread-1 and so on. By we can change the name of the thread by using setName()
method. The syntax of setName() and
• getName() methods are given below:
• public String getName(): is used to return the name of a thread.
• public void setName(String name): is used to change the name of a thread.
• Priority of a Thread (Thread Priority):
• Each thread have a priority. Priorities are represented by a number between 1
and 10. In most cases, thread schedular schedules
• the threads according to their priority (known as preemptive scheduling). But it is
not guaranteed because it depends on JVM .
• specification that which scheduling it chooses.
3 constants defined in Thread class:
• public static int MIN_PRIORITY
• public static int NORM_PRIORITY
• public static int MAX_PRIORITY
• Daemon Thread in Java
• Daemon thread in java
• is a service provider thread that provides services to the user thread. Its life
depend on the mercy of user .
• threads i.e. when all the user threads dies, JVM terminates this thread
automatically.
• There are many java daemon threads running automatically e.g. gc, finalizer etc.
• Points to remember for Daemon Thread in Java
• It provides services to user threads for background supporting tasks. It has no role
• Its life depends on user threads.
• It is a low priority thread.
1) public InputStream getInputStream() returns the InputStream attached with this socket.
• The ServerSocket class can be used to create a server socket. This object is used
to establish communication with the clients.
Method Description
• The URLConnection class provides many methods, we can display all the data of a
webpage by using the getInputStream() method. The getInputStream() method
returns all the data of the specified URL in the stream that can be read and
displayed.
• Java HttpURLConnection class
• The Java HttpURLConnection class is http specific URLConnection. It works for
HTTP protocol only.
• By the help of HttpURLConnection class, you can information of any HTTP URL such
as header information, status code, response code etc.
• The java.net.HttpURLConnection is subclass of URLConnection class.
• How to get the object of HttpURLConnection class
• The openConnection() method of URL class returns the object of URLConnection
• public URLConnection openConnection()throws IOException{}
• Java InetAddress class
• Java InetAddress class represents an IP address. The java.net.InetAddress class
provides methods to get the IP of any host name for
example www.javatpoint.com, www.google.com, www.facebook.com etc.
Commonly used methods of InetAddress class
•Method Description
public static InetAddress getByName(String host) it returns the instance of InetAddress containing
throws UnknownHostException LocalHost IP and name.
public static InetAddress getLocalHost() throws it returns the instance of InetAdddress containing
UnknownHostException local host name and address.
• JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database. It is a part of JavaSE (Java Standard Edition).
JDBC API uses JDBC drivers to connect with the database. There are four types of
JDBC drivers:
• JDBC-ODBC Bridge Driver,
• Native Driver,
• Network Protocol Driver, and
• Thin Driver
• We can use JDBC API to access tabular data stored in any relational database. By
the help of JDBC API, we can save, update, delete and fetch data from the
database. It is like Open Database Connectivity (ODBC) provided by Microsoft.
JDBC API
JDBC Driver
Java application Database
What is API
• API (Application programming interface) is a document that contains a
description of all the features of a product or software. It represents classes and
interfaces that software programs can follow to communicate with each other. An
API can be created for applications, libraries, operating systems, etc.
• JDBC Driver
• Advantages:
• easy to use.
• can be easily connected to any database.
• Disadvantages:
• Performance degraded because JDBC method call is converted into the ODBC
function calls.
• The ODBC driver needs to be installed on the client machine.
Java Database Connectivity with 5 Steps
• There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:
• Register the Driver class
• Create connection
• Create statement
• Execute queries
• Close connection
• Java Database Connectivity with MySQL
• Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
• Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address,
3306 is the port number and sonoo is the database name. We may use any database,
in such case, we need to replace the sonoo with our database name.
• Username: The default username for the mysql database is root.
• Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.
• Two ways to load the jar file:
• Paste the mysqlconnector.jar file in jre/lib/ext folder
• Set classpath
• 1) Paste the mysqlconnector.jar file in JRE/lib/ext folder:
• Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
• 2) Set classpath:
• There are two ways to set the classpath:
• temporary
• C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
• Statement interface
• The Statement interface provides methods to execute queries with the
database. The statement interface is a factory of ResultSet i.e. it provides factory
method to get the object of ResultSet.
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the
object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop,
insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple results.
public void setString(int paramIndex, String value) sets the String value to the given parameter index.
public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.
public void setDouble(int paramIndex, double value) sets the double value to the given parameter index.
public int executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.
• throws SQLException
• CREATE TABLE "IMGTABLE"
• ( "NAME" VARCHAR2(4000),
• "PHOTO" BLOB
• )
• Advance jdbc
• Scrollable Resultset in JDBC
• In Jdbc ResultSet Interface are classified into two type;.
• Non-Scrollable ResultSet in JDBC
• Scrollable ResultSet
• By default a ResultSet Interface is Non-Scrollable, In non-scrollable ResultSet we can
move only in forward direction (that means from first record to last record), but not in
Backward Direction, If you want to move in backward direction use Scrollable Interface.
Difference
Non-Scrollable ResultSet Scrollable ResultSet
Non-Scrollable ResultSet cursor can not Scrollable ResultSet cursor can move
1
move randomly randomly
Type:
•public static final int TYPE_FORWARD_ONLY=1003
•public static final int TYPE_SCROLL_INSENSITIVE=1004
•public static final int TYPE_SCROLL_SENSITIVE=1005
Mode:
•public static final int CONCUR_READ_ONLY=1007
•public static final int CONCUR_UPDATABLE=1008
Methods of Scrollable ResultSet
• The java.sql.Date class maps to the SQL DATE type, and the java.sql.Time and
java.sql.Timestamp classes map to the SQL TIME and SQL TIMESTAMP data types,
respectively.
• Following example shows how the Date and Time classes format the standard Java
date and time values to match the SQL data type requirements
• Batch Processing in JDBC
• Instead of executing a single query, we can execute a batch (group) of queries. It makes
the performance fast.
• The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for
batch processing.
• Advantage of Batch Processing
• Fast Performance
Example of batch processing in jdbc
• Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).
• Servlet technology is robust and scalable because of java language. Before Servlet,
CGI (Common Gateway Interface) scripting language was common as a server-side
programming language. However, there were many disadvantages to this
technology. We have discussed these disadvantages below.
• There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.
• What is a Servlet?
• Servlet can be described in many ways, depending on the context.
• Servlet is a technology which is used to create a web application.
• Servlet is an API that provides many interfaces and classes including documentation.
• Servlet is an interface that must be implemented for creating any Servlet.
• Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
• Servlet is a web component that is deployed on the server to create a dynamic
web page.
client server
Response
send to client
Advantages of Servlet
• There are many advantages of Servlet over CGI. The web container creates
threads for handling the multiple requests to the Servlet. Threads have many
benefits over the Processes such as they share a common memory area,
lightweight, cost of communication between the threads are low. The
advantages of Servlet are as follows:
• Better performance: because it creates a thread for each request, not process.
• Portability: because it uses Java language.
• Robust: JVM manages Servlets, so we don't need to worry about the memory
leak, garbage collection, etc.
• Secure: because it uses java language.
Life Cycle of a Servlet (Servlet Life
Cycle)
• The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:
• Servlet class is loaded.
• Servlet instance is created.
• init method is invoked.
• service method is invoked.
• destroy method is invoked.
Life cycle
Destorying
Initialization the service
In service
Website
• Website is a collection of related web pages that may contain text, images, audio
and video. The first page of a website is called home page. Each website has
specific internet address (URL) that you need to enter in your browser to access a
website.
• Website is hosted on one or more servers and can be accessed by visiting its
homepage using a computer network. A website is managed by its owner that
can be an individual, company or an organization.
• Static website
• Static website is the basic type of website that is easy to create. You don't need
the knowledge of web programming and database design to create a static
website. Its web pages are coded in HTML.
• The codes are fixed for each page so the information contained in the page does
not change and it looks like a printed page.
Server Client Browser
Dynamic website
Database
HTTP (Hyper Text Transfer Protocol)
• The Hypertext Transfer Protocol (HTTP) is application-level protocol for collaborative,
distributed, hypermedia information systems. It is the data communication protocol used to
establish communication between client and server.
• HTTP is TCP/IP based communication protocol, which is used to deliver the data like image
files, query results, HTML files etc on the World Wide Web (WWW) with the default port is
TCP 80. It provides the standardized way for computers to communicate with each other.
• HTTP Requests
• The request sent by the computer to a web server, contains all sorts of potentially interesting
information; it is known as HTTP requests.
• The HTTP client sends the request to the server in the form of request message which
includes following information:
• The Request-line
• The analysis of source IP address, proxy and port
• The analysis of destination IP address, protocol, port and host
• The Request method and Content
• The User-Agent header
• The Connection control header
• The Cache control header
• Get vs. Post
GET POST
1) In case of Get request, only limited amount of In case of post request, large amount of data can be
data can be sent because data is sent in header. sent because data is sent in body.
2) Get request is not secured because data is exposed in Post request is secured because data is not exposed in
URL bar. URL bar.
5) Get request is more efficient and used more than Post request is less efficient and used less than ge
Post.
Content Type
• Content Type is also known as MIME (Multipurpose internet Mail
Extension)Type. It is a HTTP header that provides the description about what are
you sending to the browser.
• MIME is an internet standard that is used for extending the limited capabilities of
email by allowing the insertion of sounds, images and text in a message.
• The features provided by MIME to the email services are as given below:
• It supports the non-ASCII characters
• It supports the multiple attachments in a single message
• It supports the attachment which contains executable audio, images and video
files etc.
• It supports the unlimited message length.
Reading All Form Parameters
• uses getParameterNames() method of HttpServletRequest to read all the
available form parameters. This method returns an Enumeration that contains the
parameter names in an unspecified order
• 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.
• HTTP Header Request
• getHeaderNames() method of HttpServletRequest to read the HTTP header
information. This method returns an Enumeration that contains the header
information associated with the current HTTP request.
• Once we have an Enumeration, we can loop down the Enumeration in the
standard manner, using hasMoreElements() method to determine when to stop
HTTP Header Response
• additionally we would use setIntHeader() method to set Refresh header.
• sendRedirect()
• Page redirection is a technique where the client is sent to a new location other
than requested. Page redirection is generally used when a document moves to a
new location or may be because of load balancing.
• The simplest way of redirecting a request to another page is using
method sendRedirect() of response object. Following is the signature of this
method −
• HTTP is a "stateless" protocol which means each time a client retrieves a Web
page, the client opens a separate connection to the Web server and the server
automatically does not keep any record of previous client request.
• Still there are following three ways to maintain session between web client and
web server −
• 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.
• This may not be an effective way because many time browser does not support a
cookie, so I would not recommend to use this procedure to maintain the sessions.
• 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. Each time when web
browser sends request back, then session_id value can be used to keep the track of
different web browsers.
• This could be an effective way of keeping track of the session but clicking on a
regular (<A HREF...>) hypertext link does not result in a form submission, so hidden
RequestDispatcher in Servlet
• The RequestDispatcher interface provides the facility of dispatching the request to another
resource it may be html, servlet or jsp. This interface can also be used to include the content of
another resource also. It is one of the way of servlet collaboration.
• There are two methods defined in the RequestDispatcher interface.
• Methods of RequestDispatcher interface
• The RequestDispatcher interface provides two methods. They are:
• public void forward(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Forwards a request from a servlet to another resource
(servlet, JSP file, or HTML file) on the server.
• public void include(ServletRequest request,ServletResponse response)throws
ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or
HTML file) in the response.
• 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 servlet container uses this interface to create a session between
an HTTP client and an HTTP server. The session persists for a specified
time period, across more than one connection or page request from
the user.
ServletConfig Interface
• An object of ServletConfig is created by the web container for each servlet. This object can
be used to get configuration information from web.xml file.
• If the configuration information is modified from the web.xml file, we don't need to
change the servlet. So it is easier to manage the web application if any specific content is
modified from time to time.
• Advantage of ServletConfig
• The core advantage of ServletConfig is that you don't need to edit the servlet file if
information is modified from the web.xml file.
• Methods of ServletConfig interface
• public String getInitParameter(String name):Returns the parameter value for the specified
parameter name.
• public Enumeration getInitParameterNames():Returns an enumeration of all the
initialization parameter names.
• public String getServletName():Returns the name of the servlet.
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.
• 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 servlet container uses this interface to create a session between an HTTP
client and an HTTP server. The session persists for a specified time period, across
more than one connection or page request from the user.
Cookies in Servlet
• A cookie is a small piece of information that is persisted between the multiple
client requests.
• A cookie has a name, a single value, and optional attributes such as a comment,
path and domain qualifiers, a maximum age, and a version number.
• How Cookie works
• 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.
Types of Cookie
• There are 2 types of cookies in servlets.
• Non-persistent cookie
•
Non-persistent cookie
• It is valid for single session only. It is removed each time when user closes the
browser.
• Persistent cookie
• It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.
• Advantage of Cookies
• Simplest technique of maintaining the state.
• Cookies are maintained at client side.
• Disadvantage of Cookies
• It will not work if cookie is disabled from the browser.
Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.
public String getName() Returns the name of the cookie. The name cannot
be changed after creation.
• In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining
the state of an user.
• In such case, we store the information in the hidden field and get it from another
servlet. This approach is better if we have to submit form in all the pages and we
don't want to depend on the browser.
• Let's see the code to store value in hidden field.
• Real application of hidden form field
• It is widely used in comment form of a website. In such case, we store page id or
page name in the hidden field so that each page can be uniquely identified.
• Advantage of Hidden Form Field
• It will always work whether cookie is disabled or not.
Disadvantage of Hidden Form Field:
• Many times you would be interested in knowing total number of hits on a particular page of your
website. It is very simple to count these hits using a servlet because the life cycle of a servlet is
controlled by the container in which it runs.
• Following are the steps to be taken to implement a simple page hit counter which is based on
Servlet Life Cycle −
• Initialize a global variable in init() method.
• Increase global variable every time either doGet() or doPost() method is called.
• If required, you can use a database table to store the value of global variable in destroy() method.
This value can be read inside init() method when servlet would be initialized next time. This step is
optional.
• If you want to count only unique page hits with-in a session then you can use isNew() method to
check if same page already have been hit with-in that session. This step is optional.
• You can display value of the global counter to show total number of hits on your web site. This step
Servlet Filter
public void init(FilterConfig config) init() method is invoked only once. It is used to
initialize the filter.
public void doFilter(HttpServletRequest doFilter() method is invoked every time when user
request,HttpServletResponse response, FilterChain request to any resource, to which the filter is
chain) mapped.It is used to perform filtering tasks.
public void destroy() This is invoked only once when filter is taken out of
the service.
2) FilterChain interface
• The object of FilterChain is responsible to invoke the next filter or resource in the
chain.This object is passed in the doFilter method of Filter interface.The
FilterChain interface contains only one method:
• public void doFilter(HttpServletRequest request, HttpServletResponse
response): it passes the control to the next filter or resource.
Event and Listener in Servlet
• Events are basically occurrence of something. Changing the state of an object is known as an event.
• We can perform some important tasks at the occurrence of these exceptions, such as counting total
and current logged-in users, creating tables of the database at time of deploying the project,
creating database connection object etc.
• There are many Event classes and Listener interfaces in the javax.servlet and javax.servlet.http
packages.
• Event classes
• The event classes are as follows:
• ServletRequestEvent
• ServletContextEvent
• ServletRequestAttributeEvent
• ServletContextAttributeEvent
• HttpSessionEvent
• HttpSessionBindingEvent
ServletContextEvent and ServletContextListener
Jsp translator
Servlet object
JRE
compiler
Class file
The JSP API
• The JSP API consists of two packages:
• javax.servlet.jsp
• javax.servlet.jsp.tagext
• javax.servlet.jsp package
• The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as follows:
• JspPage
• HttpJspPage
• The classes are as follows:
• JspWriter
• PageContext
• JspFactory
• JspEngineInfo
• JspException
JSP expression tag
• The code placed within JSP expression tag is written to the output stream of the
response. So you need not write out.print() to write data. It is mainly used to
print the values of variable or method.
• Syntax of JSP expression tag
• <%= statement %>
Difference between servlet and jsp
Servlet is a java code. JSP is a html based code.
Writing code for servlet is harder than JSP as it JSP is easy to code as it is java in html.
is html in java.
JSP is the view in MVC approach for showing
Servlet plays a controller role in MVC approach. output.
Servlet can accept all protocol requests. JSP only accept http requests.
In Servlet, we can override the service()
method. In JSP, we cannot override its service() method.
• In JSP, config is an implicit object of type ServletConfig. This object can be used to get
initialization parameter for a particular JSP page. The config object is created by the
web container for each jsp page.
• Generally, it is used to get initialization parameter from the web.xml file.
• JSP application implicit object
• n JSP, application is an implicit object of type ServletContext.
• The instance of ServletContext is created only once by the web container when
application or project is deployed on the server.
• This object can be used to get initialization parameter from configuaration file
(web.xml). It can also be used to get, set or remove attribute from the application
scope.
session implicit object
• In JSP, session is an implicit object of type HttpSession.The Java developer can use
this object to set,get or remove attribute or to get session information.
• pageContext implicit object
• In JSP, pageContext is an implicit object of type PageContext class.The
pageContext object can be used to set,get or remove attribute from one of the
following scopes:page
• request
• session
• application
page implicit object:
• In JSP, page is an implicit object of type Object class.This object is assigned to the
reference of auto generated servlet class. It is written as:
• JSP directives
• The jsp directives are messages that tells the web container how to translate a
JSP page into the corresponding servlet.
• There are three types of directives:
• page directive
• include directive
• taglib directive
Attributes of JSP page directive
• import
• contentType
• extends
• info
• buffer
• language
• isELIgnored
• isThreadSafe
• autoFlush
• session
• pageEncoding
• errorPage
import
• The import attribute is used to import class,interface or all the members of a package.It is similar to import
keyword in java class or interface.
• contentType
• The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP
response.The default value is "text/html;charset=ISO-8859-1".
• 3)extends
• The extends attribute defines the parent class that will be inherited by the generated servlet.It is rarely used.
• 4)info
• This attribute simply sets the information of the JSP page which is retrieved later by using getServletInfo()
method of Servlet interface.
• 5)buffer
• The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.The default
size of the buffer is 8Kb.
language
• The language attribute specifies the scripting language used in the JSP page. The
default value is "java".
• isELIgnored
• We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By
default its value is false i.e. Expression Language is enabled by default. We see
Expression Language later.
• isThreadSafe
• Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP
page, you can use isThreadSafe attribute of page directive.The value of isThreadSafe
value is true.If you make it false, the web container will serialize the multiple
requests, i.e. it will wait until the JSP finishes responding to a request before passing
another request to it.If you make the value of isThreadSafe attribute like:
• <%@ page isThreadSafe="false" %>
• errorPage
• The errorPage attribute is used to define the error page, if exception
occurs in the current page, it will be redirected to the error page.
• 10)isErrorPage
• The isErrorPage attribute is used to declare that the current page is
the error page.
Jsp Include Directive
• The include directive is used to include the contents of any resource it may
be jsp file, html file or text file. The include directive includes the original
content of the included resource at page translation time (the jsp page is
translated only once so it will be better to include static resource).
• Advantage of Include directive
• Code Reusability
• JSP Taglib directive
• The JSP taglib directive is used to define a tag library that defines many
tags. We use the TLD (Tag Library Descriptor) file to define the tags. In the
custom tag section we will use this tag so it will be better to learn it in
custom tag.
Exception Handling in JSP
• There can be defined too many attributes for any custom tag. To define the attribute,
you need to perform two tasks:
• Define the property in the TagHandler class with the attribute name and define the
setter method
• define the attribute element inside the tag element in the TLD file
• Let's understand the attribute by the tag given below:
• Iteration using JSP Custom Tag
• We can iterate the body content of any tag using the doAfterBody()method
of IterationTag interface.
• Here we are going to use the TagSupport class which implements the IterationTag
interface. For iterating the body content, we need to use
the EVAL_BODY_AGAIN constant in the doAfterBody() method.
Field Name Description
public static int EVAL_PAGE it evaluates the JSP page content after the custom
tag.
public static int SKIP_BODY it skips the body content of the tag.
public static int SKIP_PAGE it skips the JSP page content after the custom tag.
Custom URI in JSP Custom Tag
• We can use the custom URI, to tell the web container about the tld
file. In such case, we need to define the taglib element in the
web.xml. The web container gets the information about the tld file
from the web.xml file for the specified URI.
JSP Cookies Handling
• Cookies are the text files which are stored on the client machine.
• They are used to track the information for various purposes.
• It supports HTTP cookies using servlet technology
• The cookies are set in the HTTP Header.
• If the browser is configured to store cookies, it will keep information until expiry date.
• keep information until expiry date.
• Following are the cookies methods:
• Public void setDomain(String domain)It is used to set the domain to which the cookie
applies
• Public String getDomain()It is used to get the domain to which cookie applies
• Public void setMaxAge(int expiry)It sets the maximum time which should apply till the
• Public intgetMaxAge()It returns the maximum age of cookie
• Public String getName()It returns the name of the cookie
• Public void setValue(String value)Sets the value associated with the
cookie
• Public String getValue()Get the value associated with the cookie
• Public void setPath(String path)It sets the path to which cookie
applies
Pagination in JSP
• We can create pagination example in JSP easily. It is required if you have to
display many records. Displaying many records in a single page may take time, so
it is better to break the page into parts. To do so, we create pagination
application.
• In this pagination example, we are using MySQL database to fetch records.
• We have created "emp" table in "test" database. The emp table has three fields:
id, name and salary. Either create table and insert records manually or import our
sql file.
RMI (Remote Method Invocation)
• The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an object
running in another JVM.
• The RMI provides remote communication between the applications using two
objects stub and skeleton.
• Understanding stub and skeleton
• RMI uses stub and skeleton object for communication with the remote object.
• A remote object is an object whose method can be invoked from another JVM. Let's
understand the stub and skeleton objects:
• stub
• The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When the
caller invokes method on the stub object, it does the following tasks:
• It initiates a connection with remote Virtual Machine (JVM),
• It writes and transmits (marshals) the parameters to the remote Virtual Machine
(JVM),
• It waits for the result
• It reads (unmarshals) the return value or exception, and
• It finally, returns the value to the caller.
• skeleton
• The skeleton is an object, acts as a gateway for the server side object. All the
incoming requests are routed through it. When the skeleton receives the
incoming request, it does the following tasks:
• It reads the parameter for the remote method
• It invokes the method on the actual remote object, and
• It writes and transmits (marshals) the result to the caller.
Machine A Manchine B
caller Remote object
interenet
Understanding requirements for the distributed
applications
• If any application performs these tasks, it can be distributed application.
• .The application need to locate the remote method
• It need to provide the communication with the remote objects, and
• The application need to load the class definitions for the objects.
• The RMI application have all these features, so it is called the distributed application.
• Java RMI Example
• The is given the 6 steps to write the RMI program.
• Create the remote interface
• Provide the implementation of the remote interface
• Compile the implementation class and create the stub and skeleton objects using the rmic tool
• Start the registry service by rmiregistry tool
• Create and start the remote application
• Create and start the client application
How t run program
• For running this rmi example,
• javac *.java
• rmic AdderRemote
• rmiregistry 5000
• java MyServer
• java MyClient
• Struts 2 Tutorial
• struts 2 framework
• The struts 2 framework is used to develop MVC-based web application.
• The struts framework was initially created by Craig McClanahan and donated to
Apache Foundation in May, 2000 and Struts 1.0 was released in June 2001.
• The current stable release of Struts is Struts 2.3.16.1 in March 2, 2014.
• Struts 2 Framework
• The Struts 2 framework is used to develop MVC (Model View Controller) based
web applications. Struts 2 is the combination of webwork framework of
opensymphony and struts 1.
• Struts 2 provides many features that were not in struts 1. The
important features of struts 2 framework are as follows:
• Configurable MVC components
• POJO based actions
• AJAX support
• Integration support
• Various Result Types
• Various Tag support
• Theme and Template support
• ) Configurable MVC components
• In struts 2 framework, we provide all the components (view components and
action) information in struts.xml file. If we need to change any information, we
can simply change it in the xml file.
• 2) POJO based actions
• In struts 2, action class is POJO (Plain Old Java Object) i.e. a simple java class.
Here, you are not forced to implement any interface or inherit any class.
• 3) AJAX support
• Struts 2 provides support to ajax technology. It is used to make asynchronous
request i.e. it doesn't block the user. It sends only required field data to the
server side not all. So it makes the performance fast.
• 4) Integration Support
• We can simply integrate the struts 2 application with hibernate, spring, tiles etc.
frameworks.
• 5) Various Result Types
• We can use JSP, freemarker, velocity etc. technologies as the result in struts 2.
• 6) Various Tag support
• Struts 2 provides various types of tags such as UI tags, Data tags, control tags etc to
ease the development of struts 2 application.
• 7) Theme and Template support
• Struts 2 provides three types of theme support: xhtml, simple and css_xhtml. The
xhtml is default theme of struts 2. Themes and templates can be used for common
look and feel.
• Model 1 Architecture
• Servlet and JSP are the main technologies to develop the web applications.
• Servlet was considered superior to CGI. Servlet technology doesn't create process, rather it
creates thread to handle request. The advantage of creating thread over process is that it
doesn't allocate separate memory area. Thus many subsequent requests can be easily
handled by servlet.
• Problem in Servlet technology Servlet needs to recompile if any designing code is modified.
It doesn't provide separation of concern. Presentation and Business logic are mixed up.
• JSP overcomes almost all the problems of Servlet. It provides better separation of concern,
now presentation and business logic can be easily separated. You don't need to redeploy
the application if JSP page is modified. JSP provides support to develop web application
using JavaBean, custom tags and JSTL so that we can put the business logic separate from
our JSP that will be easier to test and debug.
• Disadvantage of Model 1 Architecture
• Navigation control is decentralized since every page contains the logic
to determine the next page. If JSP page name is changed that is
referred by other pages, we need to change it in all the pages that
leads to the maintenance problem.
• Time consuming You need to spend more time to develop custom
tags in JSP. So that we don't need to use scriptlet tag.
• Hard to extend It is better for small applications but not for large
applications.
• Model 2 (MVC) Architecture
• Model 2 is based on the MVC (Model View Controller) design pattern. The
MVC design pattern consists of three modules model, view and controller.
• Model The model represents the state (data) and business logic of the
application.
• View The view module is responsible to display data i.e. it represents the
presentation.
• Controller The controller module acts as an interface between view and
model. It intercepts all the requests i.e. receives input and commands to
Model / View to change accordingly.