Tuesday, 30 December 2014

Jsp and Servlet Tutorials - Jsp lifecycle - jspInit(), _jspService() & jspDestroy() (Part 5 of 8)

Jsp and Servlet Tutorials - Jsp lifecycle - jspInit(), _jspService() & jspDestroy() (Part 5 of 8)

JSP so called Java Server Pages is an important part of Java Development methodology. Jsp is used to generate dynamic content and show it as html on a web page. A JSP file contains a .jsp extension and can be places anywhere in a project where a normal web page can reside.

In this particular blog we will learn about complete life cycle of a jsp file and implementation of jsp lifecycle methods. A JSP file goes through a number of states during its execution, here is a brief introduction to those states :

JSP lifecycle is consists of jspInit(), _jspService() and jspDestroy(), and these methods are called life cycle methods of the JSP.




JSP page translation and compilation phase

Every JSP page is first translated to a servlet before going through other lifecycle states. The container than validates the syntax for correctness of jsp components used on the page. The translated servlet file is than compiles into a java class file.


JSP class loading and execution.

In execution phase of a compiled jsp file the container maintained the request-response instances occurred during the lifecycle. Jsp consists of three lifecycle methods listed below.

1) jspInit() method
2) jspService() method
3) jspDestroy() method


What is jspInit() method

Once a JSP file is successfully compiled into a class file, jsp engine calls jspInit() method to initialize class file. This method is called by the container only once during the lifecycle. jspInit() method can be overridden by the author to initialize resources such as database and network related connections.
  1. public void jspInit() {  
  2.  // initialization code or something needs to be called before JSP page  
  3.  // starts serving the requests.  
  4. }  
Now the question arises why we shouldn’t use constructor instead of init method of jsp or servlet ?. Of course ! we can use constructor instead of init() method, there is nothing to stop us. In previous versions of java it was not possible to dynamically call constructor with arguments. This does no longer applied, but servlet containers still looks for an no-argument constructor. So we  won't have access to a ServletConfig or ServletContext if we use constructor instead of init() method.


What is _jspService() method

_jspService() method is called every time a request comes to jsp during its lifecycle.  The (_) underscore sign indicates that this method is generated by Container and hence cannot be overriden. The jsp code written by us goes in _jspService() because this is implicitly implemented. In case we  tries to override it explicitly, JSP compliler will give an error saying “the method is already implemented and cannot override’.



What is jspDestroy() method()

jspDestroy() method is called when servlet(jsp) is no longer in use, with the call of this method jsp lifecycle is ended and jsp submits itself to garbage collection.
  1. public void jspDestroy() {  
  2.  // code related to release resources like database ot network  
  3.  // connections.  
  4. }  
We can always call jspDestroy() at any stage of its lifecycle but it does not make sense because even if you called jspDestroy() in the beginning, it doesn't stops the JSP to execute the _jspService() method and sending the response back to the client. This is one of the  lifecycle method which is invoked by the JSP Container when the jsp instance is removed.


In this particular blog we came across 'JSP life-cycle methods and their use and implementation', in upcoming blogs we will discuss more about java and other opensource technologies.







Thanks for reading !
Read Full

Jsp-Servlet Annotations Hello World Example Project in Eclipse

Jsp-Servlet Annotations Hello World Example Project in Eclipse

In this particular blog we will discuss about servlet annotations and how to use servlet annotations to eliminate web.xml configuration. Our objective for today's discussion is to create a simple hello world application with jsp and servlet using Servlet API 3.0 annotations.

Servlet API 3.0 included a new package called 'javax.servlet.annotation' which provides annotations to be used to annotate a servlet class and this can eliminate  the use of web.xml configuration. Servlet provides a number of useful annotations to be used, servlet containers processes these annotation classes at runtime. Some of useful annotations and their usage is listed below.
  1. @WebFilter  
  2. @WebInitParam  
  3. @WebListener  
  4. @WebServlet  
  5. @HandlesTypes  
  6. @HttpConstraint  
  7. @HttpMethodConstraint  
  8. @MultipartConfig  
  9. @ServletSecurity  


Annotating servlet using @WebServlet annotation

@WebServlet is used to declare a java class as servlet, a class still requires to extend HttpServlet. Some examples of using @WebServlet annotation are listed below.

The simplest way of declaring a servlet is annotating it with @WebServlet  and providing request mapping details in double cotes as shown below:
  1. @WebServlet("/simpleServlet")  
  2. public class TestServlet {  
  3.  // servlet code goes here  
  4. }  

Additional details can be provided to a servlet using annotations as shown in example below :
  1. @WebServlet(name = "Simple Servlet",  
  2.             description = "This is a simple servlet with annotations",  
  3.             urlPatterns = "/getServlet")  
  4. public class TestServlet {  
  5.  // servlet code goes here  
  6. }  

A servlet can have multiple request mapping to be called on, see the examplebelow:
  1. @WebServlet(  
  2.            urlPatterns = {"/getServlet", "/simpleServlet", "/coolServlet"}  
  3.            )  
  4. public class TestServlet {  
  5.  // servlet code goes here  
  6. }  


Create jsp-servlet helloworld application using annotations

Now let is create a simple helloworld application with jsp-servlet using annotations.

Project Structure

Here is overall project structure for today's discussion, create a simple 'Dynamic Web Project' from Eclipse IDE and add all required servlet and jsp files to it as mentioned in rest part of this tutorial.


\src\com\beingjavaguys\servlets\SimpleServlet.java

  1. package com.beingjavaguys.servlets;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.ServletException;  
  6. import javax.servlet.annotation.*;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. @WebServlet(name = "Simple Servlet", description = "This is a simple servlet with annotations", urlPatterns = "/getServlet")  
  12. public class SimpleServlet extends HttpServlet {  
  13.   
  14.  @Override  
  15.  protected void doGet(HttpServletRequest request,  
  16.    HttpServletResponse response) throws ServletException, IOException {  
  17.   System.out.println("get request");  
  18.   response.sendRedirect("register.jsp");  
  19.  }  
  20.   
  21.  @Override  
  22.  protected void doPost(HttpServletRequest request,  
  23.    HttpServletResponse response) throws ServletException, IOException {  
  24.   System.out.println("Name : " + request.getParameter("name"));  
  25.   System.out.println("Gender : " + request.getParameter("gender"));  
  26.   System.out.println("Email : " + request.getParameter("email"));  
  27.   System.out.println("Phone : " + request.getParameter("phone"));  
  28.   System.out.println("City : " + request.getParameter("city"));  
  29.   
  30.   request.getRequestDispatcher("details.jsp").forward(request, response);  
  31.   
  32.  }  
  33. }  

\WebContent\index.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.  pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <title>Being Java Guys | Jsp Servlet Annotation</title>  
  8. </head>  
  9. <body>  
  10.  <center>  
  11.   
  12.   <div style="color: teal; font-size: 30px">Being Java Guys | Jsp  
  13.    Servlet Annotation</div>  
  14.   <a href="getServlet">Click Here </a>  
  15.  </center>  
  16. </body>  
  17. </html>  

\WebContent\register.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.  pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <title>Being Java Guys | Registration Form</title>  
  8. </head>  
  9. <body>  
  10.  <center>  
  11.   <div style="color: teal; font-size: 30px">Being Java Guys |  
  12.    Registration Form</div>  
  13.   <form method="post" action="getServlet">  
  14.    <table>  
  15.     <tr>  
  16.      <td>Name :</td>  
  17.      <td><input type="text" name="name" />  
  18.      </td>  
  19.     </tr>  
  20.     <tr>  
  21.      <td>Gender :</td>  
  22.      <td><input type="radio" name="gender" value="male">Male  
  23.   
  24.       <input type="radio" name="gender" value="female">Feale</td>  
  25.     </tr>  
  26.     <tr>  
  27.      <td>Phone :</td>  
  28.      <td><input type="text" name="phone" />  
  29.      </td>  
  30.     </tr>  
  31.     <tr>  
  32.      <td>Email :</td>  
  33.      <td><input type="text" name="email" />  
  34.      </td>  
  35.     </tr>  
  36.     <tr>  
  37.      <td>City :</td>  
  38.      <td><select name="city">  
  39.        <option value="delhi">Delhi</option>  
  40.        <option value="mumbai">Mumbai</option>  
  41.        <option value="kolkata">Kolkata</option>  
  42.        <option value="chennai">Chennai</option>  
  43.        <option value="noida">Noida</option>  
  44.      </select>  
  45.      </td>  
  46.     </tr>  
  47.     <tr>  
  48.      <td> </td>  
  49.      <td><input type="submit" value="Save">  
  50.      </td>  
  51.     </tr>  
  52.    </table>  
  53.   </form>  
  54.  </center>  
  55. </body>  
  56. </html>  

\WebContent\details.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.  pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <title>Being Java Guys | Details</title>  
  8. </head>  
  9. <body>  
  10.  <center>  
  11.   <div style="color: teal; font-size: 30px">Being Java Guys |  
  12.    Details</div>  
  13.    <table border="1">  
  14.     <tr>  
  15.      <td>Name :</td>  
  16.      <td><%=request.getParameter("name")%></td>  
  17.     </tr>  
  18.     <tr>  
  19.      <td>Gender :</td>  
  20.      <td><%=request.getParameter("gender")%></td>  
  21.     </tr>  
  22.     <tr>  
  23.      <td>Phone :</td>  
  24.      <td><%=request.getParameter("phone")%></td>  
  25.     </tr>  
  26.     <tr>  
  27.      <td>Email :</td>  
  28.      <td><%=request.getParameter("email")%></td>  
  29.     </tr>  
  30.     <tr>  
  31.      <td>City :</td>  
  32.      <td><%=request.getParameter("city")%></td>  
  33.     </tr>  
  34.    </table>  
  35.  </center>  
  36. </body>  
  37. </html>  

Now run the project on server, if everything goes right you will get following screens.





In this particular blog we came across ‘How to create a Hibernate Project in Maven’, 'Insert table in hibernate', 'Retrieve data from db in hibernate', 'Update a row in hibernate' and 'Delete data in hibernate'. In upcoming blogs we will see more about 'jsp-servlet', Java and other opensource technologies.






Thanks for reading !
Read Full

Wednesday, 24 December 2014

Hibernate 3.0 Jars

Hibernate 3.0 Jars

In this tutorial I will explain you 1. What are the required jars for Hibernate 3.0? 2. How to set up hibernate 3.0 environment in IDE (Eclipse/Netbeans)?
After doing complete set up we can do hibernate examples easily.
When I started learning Hibernate it took me many hours to do complete Hibernate set up.
I did not find a complete resource for Hibernate 3.0 Set Up on a single website.
Reason was 1) I did not find complete jars at one place. Some were mentioning them but not providing resources from where I can download Hibernate jars. 2) Some provided Jars but missed the other ones like configuration files, mapping files.
I remember I started at 10 AM (Morning) in the morning and I ended up with my first Hibernate Example around 1 PM (Night).
Some basic knowledge will also play an important role. Moreover reading comment thread in tutorials helped me a lot.
So let us see step by step configuration of Hibernate 3.0.

List of Must have Hibernate 3.0 Jars

Below mentioned 9 jars are required to work with Hibernate 3.0
1. asm.jar
2. cglib-2.1.3.jar
3. commons-collections-2.1.1.jar
4. commons-logging-1.0.4.jar
5. dom4j-1.6.1.jar
6. ehcache-1.1.jar
7. hibernate3.jar
8. jta.jar
9. log4j-1.2.11.jar
Please download the above mentioned jars can be downloaded from sourceforge website. I would suggest to download the .zip file from sourceforge website.
Apart from the above mentioned 9 jars, we need some Database dependent jars.

Hibernate Database Dependent Jars

Apart from the above mentioned 9 jars, we need some Database dependent jars.
Developers use different databases. I use MySql. You may use Oracle, derby or any other database.
So while doing Hibernate 3.0 Set up we need to include these database dependent jars along with above 9 jars in user library.
Below you can get the specific  jars for Mysql and Derby database.

The following are required for the MySql Database :

1. mysql-connector-java-5.1.25-bin.jar

The following are required for the Derby setup :

1. Derby.jar
2. Derbyclient.jar
3. Derbynet.jar

Basic requirements

Apart from this we need some basic requirements
1. We must need JDK 1.6 or the latest version of JDK installed on our system. Please always use the latest JDK.
2. IDE – We can use the latest Eclipse, Netbeans – By using IDE tool you can do examples more quickly. In this tutorial I will explain step by step guide to set up Hibernate required jars in Eclipse. The same way we can follow in NetBeans also.
3. Database – We can use Database like MySql, Oracle or Apache Derby)

Setting Up Hibernate jars in Eclipse

So in the last we will have hibernate 3.0 required jars (List of Must have Hibernate 3.0 Jars + Database Dependent Jars) ready with us.
Now we will set up hibernate environment in Eclipse. It is nothing but adding the required jars in Eclipse library.
1. Please list out your jars and keep them in a folder like D:/lib/hibernate3.0
2. Open Eclipse and create one java project with name “Hibernate3SetUp”.
3. In Eclipse, go to Windows > Preferences > Java > Build Path > User Libraries
4. Click on New Button on the top right side of the Eclipse.
5. Now it will ask you to provide “User library name”. You can give it “hibernate3″. Say Ok.
6. After that please select “hibernate3″ in user libraries and then click on “Add External Jars”.
You can add all the hibernate jars with you in this step.

How to add user library to a Java Project

We have done with Hibernate 3.0 set up. We have added the required jars in Eclipse library.
Whenever we will create a new project we have to add this “hibernate3″ (user library) to our java project.
We can add this “hibernate3″ user library when we are creating a java project newly. We can also add this user library “hibernate3″ to existing java projects.
For adding this user library to your standalone java project please follow the following steps.
1. Create one java project. Give any name for java project. I am giving “HibernateHelloWorld”.
2. Click on next.
3. Go to Libraries tab and add the library “hibernate3″.
4. Then click on Finish.
In this way you can add user libraries to your java project.
In case you required any specific information. Please let me know by giving your comments.
Read Full

Creating Session Object Using hibernate.cfg.xml file Hibernate 3.0, MySql

Creating Session Object Using hibernate.cfg.xml file Hibernate 3.0, MySql

In this tutorial example I will demonstrate how to create org.hibernate.SessionFactory object in Hibernate 3.0 and get org.hibernate.Session object from it.
For doing this example we need hibernate configuration file (hibernate.cfg.xml) and one java class where we can write code to create org.hibernate.SessionFactory object.
Before starting I am assuming that you can set up hibernate 3.0 development environment in eclipse IDE.
So Please follow the steps to complete this example.
Create a hibernate.cfg.xml file
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
<hibernate-configuration>
    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">mysql</property>
 
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
 
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
 
        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>
 
        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
 
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
 
        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
 
        <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
        <property name="current_session_context_class">thread</property>
    </session-factory>
</hibernate-configuration>
Create one Java Class (HibernateUtils.java)
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.hibernate.dBConnection;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtils {
 
    private static final SessionFactory sessionFactory = buildSessionFactory();
 
    private static SessionFactory buildSessionFactory() {
        try {
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
 
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
 
    public static void main(String[] args) {
        SessionFactory factory = getSessionFactory();
        System.out.println("Session factory object created : " + factory);
        Session session = factory.openSession();
        try {
            System.out.println("Session object created : " + session);
            // We can use this session object for doing CRUD (inserting,
            // updating and deleting rows)
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}
Now if you are using eclipse or you are doing this example manually using Command Prompt. Please make sure Data Base services are in running mode. Also make sure the file architecture in eclipse.
** In case file hierarchy is not correct you may get error in loading hibernate.cfg.xml. means you will not get SessionObject created**
So Please below eclipse image which is showing the hierarchy of this example.
Creating Session Object Using hibernate.cfg .xml in Hibernate 3.0 Creating Session Object Using hibernate.cfg.xml file Hibernate 3.0, MySql
Eclipse Project Creating Session Object
We can see the SessionFactory object in the output like this :
Output Creating Session Object Using hibernate.cfg.xml file Hibernate 3.0, MySql
This image is showing the hibernate session object in output
Please let me know if you have any error while compiling or while running this example.
Read Full

Hibernate configuration – 3 ways to create Hibernate SessionFactory, Session Object

Hibernate configuration – 3 ways to create Hibernate SessionFactory, Session Object

In this tutorial we will explain you the mostly used three basic ways to do hibernate configuration.
After doing proper hibernate configuration we can easily get hibernate session object.
Hibernate is a ORM tool. Using Hibernate we can insert, update and delete records from Database. Before inserting, updating or deleting any object from Database using Hibernate, we need to tell Hibernate about our application settings or configuration. For example, What kind of database are we using? How do we connect to the database? What are the objects we want to persist?
You can do Hibernate configuration in three ways:

1. Hibernate Programmatic configuration using API:

While configuring Hibernate programmatic way we use Hibernate provided API to load the hbm.xml files, load the database driver and specify the database connection details.
We will demonstrate this programmatic configuration by taking one java standalone example. Here is one example to configure Hibernate session by using hibernate API.

 Eclipse Project Image for this example:

programmatically hibernate session workspace image 300x257 Hibernate configuration   3 ways to create Hibernate SessionFactory, Session Object
Hibernate Configuration Workspace
Image shown above is eclipse project image for the programmatic configuration of hibernate. You can create one simple java project with hibernate capabilities as shown in the image. Here our java project name is “programmaticallyHibernateMySql”.

HibernateUtil.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.hibernate.dbConnection;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
public class HibernateUtil {
 
    private static SessionFactory getSessionFactory() {
        // create configuration using hibernate API
        Configuration configuration = new Configuration();
        configuration.setProperty("connection.driver_class",
                "com.mysql.jdbc.Driver");
        configuration.setProperty("hibernate.connection.url",
                "jdbc:mysql://localhost/test");
        configuration.setProperty("hibernate.connection.username", "root");
        configuration.setProperty("hibernate.connection.password", "mysql");
        return configuration.buildSessionFactory();
    }
 
    public static void main(String[] args) {
        // getting session factory
        SessionFactory sessionFactory = getSessionFactory();
        System.out
                .println("Session factory object created : " + sessionFactory);
        Session session = sessionFactory.openSession();
        try {
            System.out.println("Session object created : " + session);
            // We can use this session object for doing CRUD (inserting,
            // updating and deleting rows)
 
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

Output :

Once we will run this java program the output of the code will look like below give texts. In case your configuration is incorrect you will get an exception screen.
1
2
3
4
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Session factory object created : org.hibernate.impl.SessionFactoryImpl@192b996
Session object created : SessionImpl(PersistenceContext[entityKeys=[],collectionKeys=[]];ActionQueue[insertions=[] updates=[] deletions=[] collectionCreations=[] collectionRemovals=[] collectionUpdates=[]])
This SessionFactoryImpl@192b996 may be different for you.
For me also it is changing everytime for new ouput.

2. XML configuration:

XML configuration is considered to be the best and standard way to configure hibernate session.
We use to provide database connection parameters, database driver load details, objects to be persist details in hibernate.cfg.xml.
Please read :   “how to create Hibernate Session Object using hibernate.cfg.xml”.

3. Properties file configuration:

In this method we use .properties file to configure hibernate session.
This is similar to the XML configuration but uses a .properties file. The default name is hibernate.properties.
Read Full