Advanced Java Notes (1)
Advanced Java Notes (1)
CDAC BANGLORE
1
PG-DAC Advanced Java
What is HTTP
HTTP stands for hyper text transfer protocol which is use to exchange data over the web.
HTTP is stateless protocol means every request treated as new request on server.
HTTP unable to manage clients previous request data.
Examples of Servers
1. Apache Tomcat
2. Weblogic
3. Websphere
4. Glashfish
2
PG-DAC Advanced Java
3. Security
4. It support Connection pooling, Transaction Management, messaging, clustering, load
balancing and persistence. etc…
Servlet
A servlet is a Java™ technology-based Web component, managed by a container that generates
dynamic content. Like other Java technology-based components, servlets are platform-independent Java
classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a
Java technology-enabled Web server. Containers, sometimes called servlet engines, are Web server
extensions that provide servlet functionality. Servlets interact with Web clients via a request/response
paradigm implemented by the servlet container. The servlet API is a standard Java extension and is
therefore portable and platform-neutral. Servlets are secure, since they operate within the context of a
security manager.
HTTP Basics
Servlets use the HTTP protocol, so a basic understanding of the protocol is assumed when using
servlets.
Requests, Responses, and Headers
HTTP is a simple, stateless protocol. A client, such as a web browser, makes a request, the web server
responds, and the transaction is done.
When the client sends a request, the first thing it specifies is an HTTP command, called a method, that
tells the server the type of action it wants performed.
This first line of the request also specifies the address of a document (a URL) and the version of the
HTTP protocol it is using. For example:
GET /intro.html HTTP/1.0
This request uses the GET method to ask for the document named intro.html, using HTTP Version 1.0.
After sending the request, the client can send optional header information to tell the server extra
information about the request, such as what software the client is running and what content types it
understands.
After the client sends the request, the server processes it and sends back a response. The first line of
the response is a status line that specifies the version of the HTTP protocol the server is using, a status
3
PG-DAC Advanced Java
code, and a description of the status code.For example:HTTP/1.0 200 OK. This status line includes a
status code of 200, which indicates that the request was successful, hence the description “OK”.
Another common status code is 404, with the description “Not Found”—as you can guess, this means
that the requested document was not found.
Other methods
In addition to GET and POST, there are several other lesser-used HTTP methods.
There’s the HEAD method, which is sent by a client when it wants to see only the headers of the
response, to determine the document’s size, modification time, or general availability.
There’s also PUT, to place documents directly on the server, and
DELETE, to do just the opposite. These last two aren’t widely supported due to complicated policy
issues.
The TRACE method is used as a debugging aid—it returns to the client the exact contents of its
request.
Finally, the OPTIONS method can be used to ask the server which methods it supports or what
options are available for a particular resource on the server.
4
PG-DAC Advanced Java
1. A client (e.g., a Web browser) accesses a Web server and makes an HTTP request.
2. The request is received by the Web server and handed off to the servlet container.
3. Note : The servlet container can be running in the same process as the host Web server, in a different
process on the same host, or on a different host from the Web server for which it processes requests.
4. The servlet container determines which servlet to invoke based on the configuration of its servlets, and
calls it with objects representing the request and response.
5. The servlet uses the request object to find out who the remote user is, what HTTP POST parameters
may have been sent as part of this request, and other relevant data. The servlet performs whatever
logic it was programmed with, and generates data to send back to the client. It sends this data back to
the client via the response object.
6. Once the servlet has finished processing the request, the servlet container ensures that the response
is properly flushed, and returns control back to the host Web server.
5
PG-DAC Advanced Java
What is Request?
The request object encapsulates all information from the client request. In the HTTP protocol, this
information is transmitted from the client to the server in the HTTP headers and the message body of the
request.
Request parameters for the servlet are the strings sent by the client to a servletcontainer as part of its
request. The container populates the parameters from the URI query string and POST-ed data. The
parameters are stored as a set of name-value pairs. The following methods of theServletRequest interface
are available to access parameters:
getParameter
getParameterNames
6
PG-DAC Advanced Java
getParameterValues
getParameterMap
Headers
A servlet can access the headers of an HTTP request through the following methods of the
HttpServletRequest interface:
getHeader
getHeaders
getHeaderNames
Attributes
Attributes are objects associated with a request. Attributes may be set by thecontainer to express
information that otherwise could not be expressed via the API,or may be set by a servlet to communicate
information to another servlet (via theRequestDispatcher). Attributes are accessed with the following
methods of theServletRequest interface:
getAttribute
getAttributeNames
setAttribute
7
PG-DAC Advanced Java
ServletContext
The ServletContext interface defines a servlet’s view of the Web application within which the servlet
is running. The Container Provider is responsible for providing animplementation of the ServletContext
interface in the servlet container. Using theServletContext object, a servlet can log events, obtain URL
references to resources,and set and store attributes that other servlets in the context can access.A
ServletContext is rooted at a known path within a Web server. ServletContext object is global to entire web
application. Object of ServletContext will be created at the time of web application deployment. It’s Scopeis
as long as web application is executing, ServletContext object will be available, and it will be destroyed
once the application is removed from the server.
8
PG-DAC Advanced Java
Context Attributes
A servlet can bind an object attribute into the context by name. Any attribute bound into a context
is available to any other servlet that is part of the same Web application. The following methods of
ServletContext interface allow access to this functionality:
setAttribute
getAttribute
getAttributeNames
removeAttribute
ServletConfig
Servlet Container creates ServletConfig object for each Servlet during initialization, to pass information
to the Servlet. This object can be used to get configuration information such as parameter name and values
from deployment descriptor file(web.xml).ServletConfig object is one per servlet class.Object of
ServletConfig will be created during initialization process of the servlet. This Config object is public to a
particular servlet only It’s Scope is as long as a servlet is executing, ServletConfig object will be available, it
will be destroyed once the servlet execution is completed.We should give request explicitly, in order to
create ServletConfig object for the first time.
The following methods of ServletConfiginterface allow access to the functionality:
getInitParameter
getServletName
getServletContext
What is Response?
The response object encapsulates all information to be returned from the server to the client. In the
HTTP protocol, this information is transmitted from the server to the client either by HTTP headers or the
message body of the request.
Lifetime of the Response Object
Each response object is valid only within the scope of a servlet’s service method, or within the scope of
a filter’s doFilter method. Containers commonly recycle response objects in order to avoid the
performance overhead of response object creation.
Sessions
The Hypertext Transfer Protocol (HTTP) is by design a stateless protocol. To buildeffective Web
applications, it is imperative that requests from a particular client beassociated with each other. Many
strategies for session tracking have evolved overtime. The following are some approaches for tracking a
user’s sessions. The standard name of the session tracking cookie must be JSESSIONID. Containers may
allow the name of the session tracking cookie to be customized through container specific configuration.
Using Cookies
9
PG-DAC Advanced Java
Cookie,is a small amount of information sent by a servlet to a Web browser, saved by the browser, and
later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used
for session management. Cookie is a key value pair of information.
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. The servlet sends cookies to the browser by usingthe
addCookie() method, which adds fields to HTTP response headers to send cookies to the browser, one at a
time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit
cookie size to 4 KB each.The browser returns cookies to the servlet by adding fields to HTTP request
headers. Cookies can be retrieved from a request by using the getCookies() method. Several cookies might
have the same name but different path attributes.
This should be saved by the browser in its space in the client computer. Whenever the browser sends
a request to that server it sends the cookie along with it. Then the server can identify the client using the
cookie.
In java, following is the source code snippet to create a cookie:
Cookie cookie = new Cookie(“userID”, “7456”);
res.addCookie(cookie);
Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the users
can opt to disable cookies using their browser preferences. In such case, the browser will not save the
cookie at client computer and session tracking fails.
Hidden Fields
<INPUT TYPE=”hidden” NAME=”technology” VALUE=”servlet”>
Hidden fields like the above can be inserted in the webpages and information can be sent to the server
for session tracking. These fields are not visible directly to the user, but can be viewed using view source
option from the browsers. This type doesn’t need any special configuration from the browser of server and
by default available to use for session tracking. This cannot be used for session tracking when the
conversation included static resources like html pages.
URL Rewriting
Original URL: http://server:port/servlet/ServletName
Rewritten URL: http://server:port/servlet/ServletName?sessionid=1234
When a request is made, additional parameter is appended with the URL. In general added additional
parameter will be sessionid or sometimes the userid. It will suffice to track the session. This type of session
tracking doesn’t need any special support from the browser. Disadvantage is, implementing this type of
session tracking is tedious. We need to keep track of the parameter as a chain link until the conversation
completes and also should make sure that, the parameter doesn’t clash with other application parameters.
Session tracking API
Session tracking API is built on top of the first three methods. This is inorder to help the developer to
minimize the overhead of session tracking. This type of session tracking is provided by the underlying
technology. Lets take the java servlet example. Then, the servlet container manages the session tracking
10
PG-DAC Advanced Java
task and the user need not do it explicitly using the java servlets. This is the best of all methods, because
all the management and errors related to session tracking will be taken care of by the container itself.
Every client of the server will be mapped with a javax.servlet.http.HttpSession object. Java servlets can use
the session object to store and retrieve java objects across the session. Session tracking is at the best when
it is implemented using session tracking api.
11
PG-DAC Advanced Java
JSP
JavaServer Pages (JSP) technology enables you to mix regular, static HTML with dynamically generated
content from servlets. You simply write the regular HTML in the normal manner. Separating the static
HTML from the dynamic content provides a number of benefits over servlets alone, and the approach used
in JavaServer Pages offers several advantages over competing technologies such as ASP, PHP.
JSP is widely supported and thus doesn’t lock you into a particular operating system or Web
server and that JSP gives you full access to servlet and Java technology for the
dynamic part, rather than requiring you to use an unfamiliar and weaker special-purpose language.
Although what you write often looks more like a regular HTML file than a servlet, behind the scenes,
the JSP page is automatically converted to a normal servlet, with the static HTML simply being printed to
the output stream associated with the servlet’s service method. This translation is normally done the first
time the page is requested.
Aside from the regular HTML, there are three main types of JSP constructs that you embed in a page:
scripting elements, directives, and actions.
JSP Expressions
A JSP expression is used to insert values directly into the output. It has the following form:
<%= Java Expression %>
The expression is evaluated, converted to a string, and inserted in the page. For example, the following
shows the date/time that the page was requested:
Current time: <%= new java.util.Date() %>.
JSP Declarations
A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet
class (outside of the _jspService method that is called by service to process the request). A declaration
has the following form:
12
PG-DAC Advanced Java
Predefined Variables
To simplify code in JSP expressions and scriptlets, you are supplied with some automatically defined
variables, sometimes called implicit objects.
request
This variable is the HttpServletRequest associated with the request;it gives you access to the
request parameters, the request type (e.g., GET or POST), and the incoming HTTP headers (e.g.,
cookies).
response
This variable is the HttpServletResponse associated with the response to the client.
out
This is the PrintWriter used to send output to the client. However, to make the response object
useful, this is a buffered version of Print- Writer called JspWriter.
session
This variable is the HttpSession object associated with the request. Recall that sessions are
created automatically, so this variable is bound even if there is no incoming session reference.
application
This variable is the ServletContext as obtained via getServletConfig().getContext().
config
This variable is the ServletConfig object for this page.
pageContext
JSP introduced a new class called PageContext to give a single point of access to many of the page
attributes and to provide a convenient place to store shared data.
page
This variable is simply a synonym for this
JSP directives
JSP directive affects the overall structure of the servlet that results from the JSP page. In JSP, there are
three types of directives: page, include, and taglib. The page directive lets you control the structure ofthe
servlet by importing classes, customizing the servlet superclass, setting the content type, and the like.
Page Directive
The page directive lets you define one or more of the following case-sensitive attributes: import,
contentType, isThreadSafe, session, buffer, autoflush, extends, info, errorPage, isErrorPage, and language.
These attributes are explained below,
13
PG-DAC Advanced Java
14
PG-DAC Advanced Java
The isErrorPage attribute indicates whether or not the current page can act as the error page for
another JSP page.
e.g.<%@ page isErrorPage="true" %>
JavaBean
JavaBeans are reusable software components for Java that can be manipulated visually in a builder
tool. Practically, they are classes written in the Java programming language conforming to a particular
convention. They are used to encapsulate many objects into a single object (the bean), so that they can be
passed around as a single bean object instead of as multiple individual objects. A JavaBean is
Defined with following standards,
A bean class must have a zero-argument (empty) constructor.
A bean class should have no public instance variables (fields).
Persistent values should be accessed through methods called getXxx and setXxx.
15
PG-DAC Advanced Java
Sharing Beans
Although the beans are indeed bound to local variables, that is not the only behavior. They are also
stored in one of four different locations, depending on the value of the optional scope attribute of
jsp:useBean. The scope attribute has the following possible values:
Page
This is the default value. It indicates that, in addition to being bound to a local variable, the bean object
should be placed in the PageContext object for the duration of the current request.Beans created with
page scope are almost always accessed by jsp:getProperty, jsp:setProperty, scriptlets, or expressionslater
in the same page.
application
This very useful value means that, in addition to being bound to a local variable, the bean will be stored
in the shared ServletContext available through the predefined application variable or by a call to
getServletContext().Values in the ServletContext can be retrieved by the getAttribute method.
session
This value means that, in addition to being bound to a localvariable, the bean will be stored in the
HttpSession objectassociated with the current request, where it can be retrievedwith getValue.
request
This value signifies that, in addition to being bound to a localvariable, the bean object should be placed
in theServletRequest object for the duration of the current request.
16
PG-DAC Advanced Java
JSTL stands for JSP Standard Tag Library and JSTL represents a set predefined tags.The main purpose of JSTL
is to simplify the JSP development. JSTL is not language like JSP it’s a tag library by which we can write java
program in JSP, like for loop , if else statement etc.
Advantages of JSTL
1. Fast development.
2. Easy understandable for Humans.
3. No need to use scriptlet tag in JSP page.
17
PG-DAC Advanced Java
18
PG-DAC Advanced Java
Hibernate
Hibernate is an object relational mapper (ORM) Framework which is used to turn our java objects into a
way to persists them into the database and vice versa.
What is ORM
Object-Relational Mapping (ORM) is a technique which provides us facility to query and manipulate data
from a database using an object-oriented programming pradigm.
ORM binds our tables or stored procedures in java classes, so that instead of writing SQL statements to
interact with your database, you use methods and properties of objects.
Limitation of Hibernate
1. Hibernate is slower than pure JDBC driver API.
2. Hibernate is not recommended for small project.
3. Hibernate is not suitable for Batch processing
4. So Many configurations needed for simple query also.
Hibernate Architecture
Elements of Hibernate Architecture
1. Configuration
2. SessionFactory
3. Session
4. Transaction
5. Query
19
PG-DAC Advanced Java
What is Configuration?
Configuration is a class given by hibernate people to load the hibernate XML configuration file.
Configuration cfg = new Configuration();
What is SessionFactory?
SessionFactory is an interface which is used to create the session object and SessionFactory contains the
connection information, hibernate configuration information and mapping files,location path.Instances
of SessionFactory are thread-safe and typically shared throughout an application.SessionFactory holds
second level cache also.
SessionFactorysessionFactory = configurationObject.buildSessionFactory();
What is Session?
Session is an interface which is used to execute SQL queries like insert , update , delete and it is holds first
level cache.
What is Transaction?
Transaction is an interface using which we maintain transaction in hibernate application.
What is Query?
Query is an interface which is used to execute DML statement in hibernate application like select , delete
etc.
20
PG-DAC Advanced Java
Syntax
<hibernate-mapping>
<class name=“java _persistent_class“ table=“table_name“>
<!– Here id should be primary key of database –>
<id name=“field_name“ column=“database_column_name“ type=“Java_data_type“ />
<property name=“field_name“ column=“database_column_name“type=“Java_data_type“/>
</class>
</hibernate-mapping>
21
PG-DAC Advanced Java
22
PG-DAC Advanced Java
SQL in Oracle
>select roll , name from student;
HQL
selects.roll , s.name from Student s;
Here Student is class name and roll and name is fields name of Student class. HQL query will be executed
with Query interface given by hibernate.
Hibernate Criteria API
Hibernate Criteria API is used to retrieve data from database based on some criteria like greater than ,
less than where clause.We can use Hibernate Criteria API for data retrieval purpose only.
Hibernate mapping
To reduce data redundancy in our database table we will divide the properties of one class into two
classes and then we will apply relationship between objects of two classes is called Hibernate mapping.
In hibernate we can apply 4 types of relationship between two POJO classes.
1. One-to-Many
2. Many-to-One
3. Many-to-Many
4. One-to-One
In Hibernate if we want to apply relationship mapping between two classes then first we need to add Child
class object to collection and then we need to set that collection object to Parent class.We can use List, Set
or Map collection for mapping.
Hibernate Caching – First Level Cache
Hibernate supports three level of cache to optimize the performance of hibernate application.
1. First level cache
2. Second level cache
3. Query level cache
23
PG-DAC Advanced Java
24
PG-DAC Advanced Java
Spring framework
Spring is complete application development framework which is use to develop all type of application like
standalone, distributed, EJB, Enterprise application.
Advantage of spring framework
1. Spring is light-weight.
2. Spring is versatile.
3. It is non-invasive framework.
4. It provides rapid application development.
5. It has given boiler plate code to reduce development effort of programmer.
6. It has strong dependency management.
7. It provides loosely coupling.
25
PG-DAC Advanced Java
26
PG-DAC Advanced Java
2. Constructor injection
3. Interface injection
27
PG-DAC Advanced Java
Here id you have to pass in main class at the time of creating BeanFactory or ApplicationContext.
And You have to pass fully qualified class path and name in main class.
28
PG-DAC Advanced Java
29