0% found this document useful (0 votes)
100 views22 pages

JSP Session Hibernate

JSP technology is used to create web applications like Servlets. It provides more functionality than Servlets such as expression language and JSTL. A JSP page consists of HTML tags and JSP tags, making it easier to separate design from development than Servlets. There are several advantages to using JSP over Servlets, including that JSP pages are extensions of Servlets, JSP pages are easier to maintain by separating business logic from presentation logic, and JSP pages do not require recompiling and redeploying when modified.

Uploaded by

devendra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views22 pages

JSP Session Hibernate

JSP technology is used to create web applications like Servlets. It provides more functionality than Servlets such as expression language and JSTL. A JSP page consists of HTML tags and JSP tags, making it easier to separate design from development than Servlets. There are several advantages to using JSP over Servlets, including that JSP pages are extensions of Servlets, JSP pages are easier to maintain by separating business logic from presentation logic, and JSP pages do not require recompiling and redeploying when modified.

Uploaded by

devendra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

JSP

JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet
such as expression language, JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain
than Servlet because we can separate designing and development. It provides some
additional features such as Expression Language, Custom Tags, etc.

Advantages of JSP over Servlet


There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the features of the
Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the
presentation logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The
Servlet code needs to be updated and recompiled if we have to change the look and
feel of the application.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces
the code. Moreover, we can use EL, implicit objects, etc.

The Lifecycle of a JSP Page


The JSP pages follow these phases:
o Translation of JSP Page
o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP
translator. The JSP translator is a part of the web server which is responsible for
translating the JSP page into Servlet. After that, Servlet page is compiled by the compiler
and gets converted into the class file. Moreover, all the processes that happen in Servlet
are performed on JSP later like initialization, committing response to the browser and
destroy.
Creating a simple JSP Page
To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in
the web-apps directory in apache tomcat to run the JSP page.

index.jsp

Let's see the simple example of JSP where we are using the scriptlet tag to put Java code
in the JSP page. We will learn scriptlet tag later.

<html>  
<body>  
<% out.print(2*5); %>  
</body>  
</html>  

It will print 10 on the browser.

How to run a simple JSP Page?


Follow the following steps to execute this JSP page:

o Start the server


o Put the JSP file in a folder and deploy on the server
o Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example,
http://localhost:8888/myapplication/index.jsp

Do I need to follow the directory structure to run a simple


JSP?
No, there is no need of directory structure if you don't have class files or TLD files. For
example, put JSP files in a folder directly and deploy that folder. It will be running fine.
However, if you are using Bean class, Servlet or TLD file, the directory structure is
required.
The JSP API
The JSP API consists of two packages:

1. javax.servlet.jsp
2. javax.servlet.jsp.tagext

javax.servlet.jsp package
The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as
follows:

1. JspPage
2. HttpJspPage

The classes are as follows:

o JspWriter
o PageContext
o JspFactory
o JspEngineInfo
o JspException
o JspError

Difference between Servlet and JSP


In brief, it can be defined as Servlet are the java programs that run on a Web server and
act as a middle layer between a request coming from HTTP client and databases or
applications on the HTTP server.While JSP is simply a text document that contains two
types of text: static text which is predefined and dynamic text which is rendered after
server response is received.
The following are the important differences between ArrayList and HashSet.

Sr. Key Servlet JSP


No.

Implementation Servlet is developed on Java JSP is primarily written in


language. HTML language although
1 Java code could also be
written on it but for it, JSTL or
other language is required.

MVC In contrast to MVC we can state On the other hand, JSP plays
servlet as a controller which the role of view to render the
2
receives the request process and response returned by the
send back the response. servlet.

Request type Servlets can accept and process JSP on the other hand is
3 all type of protocol requests. compatible with HTTP
request only.

Session In Servlet by default session On the other hand in JSP


4 Management management is not enabled, the session management is
user has to enable it explicitly. automatically enabled.

5 Performance Servlet is faster than JSP. JSP is slower than Servlet


because first the translation
of JSP to java code is taking
Sr. Key Servlet JSP
No.

place and then compiles.

Modification Modification in Servlet is a time- On the other hands JSP


reflected consuming task because it modification is fast as just
includes reloading, recompiling need to click the refresh
6
and restarting the server as we button and code change
made any change in our code to would get reflected.
get reflected.

Get vs. Post


There are many differences between the Get and Post request. Let's see these
differences:

GET POST

1) In case of Get request, only limited amount of In case of post request, large amount of


data can be sent because data is sent in header. data can be sent because data is sent in
body.

2) Get request is not secured because data is Post request is secured because data is not
exposed in URL bar. exposed in URL bar.

3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent . It means second Post request is non-idempotent.


request will be ignored until response of first request
is delivered

5) Get request is more efficient and used more than Post request is less efficient and used less
Post. than get.
GET and POST
Two common methods for the request-response between a server and client are:

o GET- It requests the data from a specified resource


o POST- It submits the processed data to a specified resource

Anatomy of Get Request


The query string (name/value pairs) is sent inside the URL of a GET request:

1. GET/RegisterDao.jsp?name1=value1&name2=value2  

As we know that data is sent in request header in case of get request. It is the default
request type. Let's see what information is sent to the server.
Some other features of GET requests are:

o It remains in the browser history


o It can be bookmarked
o It can be cached
o It have length restrictions
o It should never be used when dealing with sensitive data
o It should only be used for retrieving the data

Anatomy of Post Request


The query string (name/value pairs) is sent in HTTP message body for a POST request:

1. POST/RegisterDao.jsp HTTP/1.1  
2. Host: www. javatpoint.com  
3. name1=value1&name2=value2  

As we know, in case of post request original data is sent in message body. Let's see how
information is passed to the server in case of post request.
Some other features of POST requests are:

o This requests cannot be bookmarked


o This requests have no restrictions on length of data
o This requests are never cached
o This requests do not retain in the browser history

Hibernate Framework
Hibernate is a Java framework that simplifies the development of Java application to
interact with the database. It is an open source, lightweight, ORM (Object Relational
Mapping) tool. Hibernate implements the specifications of JPA (Java Persistence API) for
data persistence.
ORM Tool
An ORM tool simplifies the data creation, data manipulation and data access. It is a
programming technique that maps the object to the data stored in the database.

The ORM tool internally uses the JDBC API to interact with the database.

What is JPA?
Java Persistence API (JPA) is a Java specification that provides certain functionality and
standard to ORM tools. The javax.persistence package contains the JPA classes and
interfaces.

Advantages of Hibernate Framework


Following are the advantages of hibernate framework:

1) Open Source and Lightweight

Hibernate framework is open source under the LGPL license and lightweight.

2) Fast Performance

The performance of hibernate framework is fast because cache is internally used in


hibernate framework. There are two types of cache in hibernate framework first level
cache and second level cache. First level cache is enabled by default.

3) Database Independent Query

HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the
database independent queries. So you don't need to write database specific queries.
Before Hibernate, if database is changed for the project, we need to change the SQL
query as well that leads to the maintenance problem.

4) Automatic Table Creation

Hibernate framework provides the facility to create the tables of the database
automatically. So there is no need to create tables in the database manually.

5) Simplifies Complex Join

Fetching data from multiple tables is easy in hibernate framework.

6) Provides Query Statistics and Database Status

Hibernate supports Query cache and provide statistics about query and database status.

Hibernate Architecture
The Hibernate architecture includes many objects such as persistent object, session
factory, transaction factory, connection factory, session, transaction etc.

The Hibernate architecture is categorized in four layers.

o Java application layer


o Hibernate framework layer
o Backhand api layer
o Database layer

Let's see the diagram of hibernate architecture:


This is the high level architecture of Hibernate with mapping file and configuration file.
Hibernate framework uses many objects such as session factory, session, transaction etc.
alongwith existing Java API such as JDBC (Java Database Connectivity), JTA (Java
Transaction API) and JNDI (Java Naming Directory Interface).

Elements of Hibernate Architecture


For creating the first hibernate application, we must know the elements of Hibernate architecture. They are
follows:

SessionFactory

The SessionFactory is a factory of session and client of ConnectionProvider. It holds


second level cache (optional) of data. The org.hibernate.SessionFactory interface
provides factory method to get the object of Session.

Session

The session object provides an interface between the application and data stored in the
database. It is a short-lived object and wraps the JDBC connection. It is factory of
Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data. The
org.hibernate.Session interface provides methods to insert, update and delete the
object. It also provides factory methods for Transaction, Query and Criteria.

Transaction

The transaction object specifies the atomic unit of work. It is optional. The
org.hibernate.Transaction interface provides methods for transaction management.

ConnectionProvider

It is a factory of JDBC connections. It abstracts the application from DriverManager or


DataSource. It is optional.

TransactionFactory

It is a factory of Transaction. It is optional.

Hibernate Example using XML in Eclipse


Here, we are going to create a simple example of hibernate application using eclipse
IDE. For creating the first hibernate application in Eclipse IDE, we need to follow the
following steps:

1. Create the java project


2. Add jar files for hibernate
3. Create the Persistent class
4. Create the mapping file for Persistent class
5. Create the Configuration file
6. Create the class that retrieves or stores the persistent object
7. Run the application

1) Create the java project


Create the java project by File Menu - New - project - java project . Now specify the
project name e.g. firsthb then next - finish .
2) Add jar files for hibernate
To add the jar files Right click on your project - Build path - Add external archives.
Now select all the jar files as shown in the image given below then click open.

4.3M
79
Triggers in SQL (Hindi)

In this example, we are connecting the application with oracle database. So you must
add the ojdbc14.jar file.

download the ojdbc14.jar file


3) Create the Persistent class
Here, we are creating the same persistent class which we have created in the previous
topic. To create the persistent class, Right click on src - New - Class - specify the class
with package name (e.g. com.javatpoint.mypackage) - finish .

Employee.java
package com.javatpoint.mypackage;  
public class Employee {  
private int id;  
private String firstName,lastName;  
public int getId() {  
    return id;  
}  
public void setId(int id) {  
    this.id = id;  
}  
public String getFirstName() {  
    return firstName;  
}  
public void setFirstName(String firstName) {  
    this.firstName = firstName;  
}  
public String getLastName() {  
    return lastName;  
}  
public void setLastName(String lastName) {  
    this.lastName = lastName;  
}  
}  
4) Create the mapping file for Persistent class
Here, we are creating the same mapping file as created in the previous topic. To create
the mapping file, Right click on src - new - file - specify the file name (e.g.
employee.hbm.xml) - ok. It must be outside the package.
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-mapping PUBLIC  
 "-//Hibernate/Hibernate Mapping DTD 5.3//EN"  
 "http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">  
 <hibernate-mapping>  
  <class name="com.javatpoint.mypackage.Employee" table="emp1000">  
    <id name="id">  
     <generator class="assigned"></generator>  
    </id>       
    <property name="firstName"></property>  
    <property name="lastName"></property>       
  </class>          
 </hibernate-mapping>  
5) Create the Configuration file
The configuration file contains all the informations for the database such as
connection_url, driver_class, username, password etc. The hbm2ddl.auto property is
used to create the table in the database automatically. We will have in-depth learning
about Dialect class in next topics. To create the configuration file, right click on src - new
- file. Now specify the configuration file name e.g. hibernate.cfg.xml.

hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>  
<!DOCTYPE hibernate-configuration PUBLIC  
          "-//Hibernate/Hibernate Configuration DTD 5.3//EN"  
          "http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">  
<hibernate-configuration>  
    <session-factory>  
        <property name="hbm2ddl.auto">update</property>  
        <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>  
        <property name="connection.username">system</property>  
        <property name="connection.password">oracle</property>  
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>  
    <mapping resource="employee.hbm.xml"/>  
    </session-factory>  
</hibernate-configuration>  
6) Create the class that retrieves or stores the persistent
object
In this class, we are simply storing the employee object to the database.

package com.javatpoint.mypackage;  
import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.Transaction;  
import org.hibernate.boot.Metadata;  
import org.hibernate.boot.MetadataSources;  
import org.hibernate.boot.registry.StandardServiceRegistry;  
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;    
public class StoreData {  
    public static void main( String[] args )  
    {  
         StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.x
ml").build();  
            Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();  
        SessionFactory factory = meta.getSessionFactoryBuilder().build();  
        Session session = factory.openSession();  
        Transaction t = session.beginTransaction();  
         Employee e1=new Employee();    
            e1.setId(1);    
            e1.setFirstName("Gaurav");    
            e1.setLastName("Chawla");    
       session.save(e1);  
       t.commit();  
       System.out.println("successfully saved");    
        factory.close();  
        session.close();     
    }  
}  
7) Run the application
Before running the application, determine that directory structure is like this.

To run the hibernate application, right click on the StoreData class - Run As - Java Application.

session implicit object


Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking


techniques. Each time user requests to the server, server treats the request as the new
request. So we need to maintain the state of an user to recognize to particular user.

HTTP is stateless that means each request is considered as the new request. It is shown
in the figure given below:

Why use Session Tracking?

To recognize the user It is used to recognize the particular user.

Session Tracking Techniques


There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

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.

Example of session implicit object


index.html
<html>  
<body>  
<form action="welcome.jsp">  
<input type="text" name="uname">  
<input type="submit" value="go"><br/>  
</form>  
</body>  
</html>  
welcome.jsp
<html>  
<body>  
<%   
  
String name=request.getParameter("uname");  
out.print("Welcome "+name);  
session.setAttribute("user",name);  
<a href="second.jsp">second jsp page</a>   
%>  
10. </body>  
11. </html>  
second.jsp
<html>  
<body>  
<%   
String name=(String)session.getAttribute("user");  
out.print("Hello "+name);  
%>  
</body>  
</html>  

You might also like