Skip to main content

Struts2 and Hibernate Example using Annotation

Hi Guys,

Today we are going to create an example using Struts2 and Hibernate using Annotation. For the database, we are going to use MySQL. This example will register a record for a user in the mysql database, which later will be used to login to the application.

First of all we need to create our database table in MySQL.

Log into your mysql database and type the following command to create a database in the mysql prompt.

create database mydb;

Use the above created database to create table.

use mydb;

Now we need to create a database table named "users".

create table users(
uid int primary key auto_increment,
uname char(15),
password char(20),
email char(20),
phone long,
city char(15));

Now to create this application, we are going to use eclipse.

Open your eclipse and create a dynamic web project.

Put the following jars related to Struts2 and Hibernate in the WEB-INF/lib folder


Now create the following packages in the src folder for the Struts and Hibernate classes. The folder structure of the entire application is as follows:



Now first of all we are going to create our hibernate configuration xml file which will do the configuration required to connect to the database( in our case it is mysql database).

For this I have created a configuration file named "myhibernate.cfg.xml", you can name whatever you feel convenient.


myhibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/mydb</property>
    <property name="connection.username">root</property>
    <property name="connection.password">mypass</property>

    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="show_sql">true</property>
    
    <mapping class="com.rohan.hibernate.User"/>
    </session-factory>
</hibernate-configuration>


Now, we will create a Hibernate Util class, We will place this class in the com.rohan.hibernate package as follows:

AHibernateUtil.java

package com.rohan.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

public class AHibernateUtil { 
static SessionFactory factory;

static {
AnnotationConfiguration cfg = new AnnotationConfiguration();
cfg = (AnnotationConfiguration) cfg.configure("myhibernate.cfg.xml");
factory = cfg.buildSessionFactory();
}

public static SessionFactory getFactory() {
return factory;
}
}



In the same package we will create a persistent class named user.java as follows:


User.java


package com.rohan.hibernate;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name="users")
public class User {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="uid")
private int uid;

@Column(name="uname")
private String uname;

@Column(name="password")
private String password;

@Column(name="email")
private String email;

@Column(name="phone")
private Long phone;

@Column(name="city")
String city;

public User() {
}

public User(String uname, String password, String email, Long phone, String city) {
super();
this.uname = uname;
this.password = password;
this.email = email;
this.phone = phone;
this.city = city;
}

// setters and getters for all the fields.

}

Now update the web.xml for the with FilterDispatcher information.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>AStruts1</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
<init-param>
<param-name>actionPackages</param-name>
<param-value>com.rohan.struts2</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>

</web-app>


Now create an Action class named AnnotatedRegisterSubmit.java, which will handle the request coming from the register.jsp.
Create the following AnnotaionRegisterSubmit.java class in the com.rohan.struts2 package as follows.

AnnotationRegisterSubmit.java

package com.rohan.struts2;

import org.apache.struts2.config.Result;
import org.apache.struts2.config.Results;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import com.opensymphony.xwork2.ActionSupport;
import com.rohan.hibernate.AHibernateUtil;
import com.rohan.hibernate.User;
import com.rohan.struts2.bean.RegisterBean;

@Results({ @Result(name = "success", value = "/register.jsp"),
@Result(name = "regsuccess", value = "/regsuccess.jsp"),
@Result(name = "nothing", value = "/register.jsp"),
@Result(name = "failed", value = "/register.jsp")
})
public class AnnotatedRegisterSubmit extends ActionSupport {

private static final long serialVersionUID = 4690088112946511642L;

RegisterBean reg;

public RegisterBean getReg() {
return reg;
}

public void setReg(RegisterBean reg) {
this.reg = reg;
}

public String execute() {
if(reg == null) {
reg = new RegisterBean();
}
String un = reg.getUsername();
String pw = reg.getPassword();
String em = reg.getEmail();
String ph = reg.getPhone();
String ct = reg.getCity();

String result = "";
if (!"".equals(un) || !un.equals(null)) {
try {
SessionFactory sf = AHibernateUtil.getFactory();
Session session = sf.openSession();
Transaction tx = (Transaction) session.beginTransaction();
User user = new User(un, pw, em, Long.parseLong(ph), ct);
session.save(user);
tx.commit();
session.close();
result = "regsuccess";
} catch (Exception e) {
e.printStackTrace();
result = "failed";
}
} else {
result = "nothing";
}
return result;
}

}

As you can see, we have used Bean class to bind the jsp elements, so create Bean class named RegisterBean.java in the com.rohan.sturts2.bean package as follows:

RegisterBean.java

package com.rohan.struts2.bean;

import java.io.Serializable;

public class RegisterBean implements Serializable {
private String username;
private String password;
private String email;
private String phone;
private String city;

// setters and getters for all these fields.
}


Now we will create the presentation layer for our application, create the following login.jsp, regiseter.jsp and regsuccess.jsp as follows:


login.jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Account Login</title>
<s:head />
</head>
<body>
<h2>Account Login</h2>
<s:actionerror />
<s:form action="annotatedLoginSubmit">
<s:textfield key="username" cssStyle="font-size=3 color=red" />
<s:password key="password" cssStyle="font-size=3 color=red" />
<s:submit cssStyle="font-size=3 color=red" />
</s:form>
<s:form action="annotatedRegisterSubmit">
<s:submit name="Register" cssStyle="font-size=3 color=red" />
</s:form>
</body>
</html>

register.jsp

<%@taglib uri="/struts-tags" prefix="s"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Account Login</title>
<s:head />
</head>
<body>
<h2>Account Register</h2>
<s:form action="annotatedRegisterSubmit">
<table>
<tr><td>UserName</td><td><input type="text" name="username" /></td></tr>
<tr><td>Email</td><td><input type="text" name="email" /></td></tr>
<tr><td>Password</td><td><input type="password" name="password" /></td></tr>
<tr><td>Phone</td><td><input type="text" name="phone" /></td></tr>
<tr><td>city</td><td><input type="text" name="city" /></td></tr>

<tr><td><input type="submit" name="Register" /> </td></tr>
</table>
</s:form>
</body>
</html>


regsuccess.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Registration successful.</h1>
</body>
</html>


That's all. All the required files are created.

Now make sure that Tomcat server is up and all the necessary configuration have already been done.
Now just run the Sturts application. It will go to the login.jsp page, click the register link to go to the register page and fill the form and click on submit.

The url is as follows (I have given port no 7000 for the tomcat server, plz check with yours):

http://localhost:7000/AStruts1/


After clicking on the submit button the page will be redirected to the regsuccess.jsp and data will be saved in the databases users table.

http://localhost:7000/AStruts1/annotatedRegisterSubmit.action;jsessionid=EC2E9B533E9854A8A17972A1A051AD04




















Comments

  1. Nice example.. helped a lot :-)

    ReplyDelete
  2. Hi Rohan..

    can you share spring MVC with Hibernate example[annotations]

    ReplyDelete
    Replies
    1. Hi Sasikumar,

      I am planning to create Spring MVC with Hibernate example. Very soon I will try to post.

      Delete
  3. Hey Rohan,

    i have one doubt in AnnotatedRegisterSubmit.java ,

    Struts2 API is loosely coupled r8, and it will automatically maps the form bean to action class java bean properties.

    but in your logic, you instantiating bean, and accessing bean properties.
    then where is loosely coupling concept. and you using setters & getters mechanism, that is enough to get the bean object, am i r8?,

    can you explain, what is your intention? is it required to instantiating the bean in action class?

    ReplyDelete
    Replies
    1. Implementation is developer dependent. I have used one approach for my program and could be lots of better approach for doing the same thing.

      Delete
  4. Hey Rohan.. above example was nice.

    In view page(login.jsp)

    but you forget to use struts provided html tags, instead of that you used plain html tags.
    then what is use of struts framework.

    ReplyDelete
    Replies
    1. Will create one with Struts tags example in the future :)

      Delete
  5. Replies
    1. Please don't imitate blindly. Please correct while creating your program. There could be typo mistakes.
      Will try to improve in the future posts :)

      Delete

Post a Comment

Popular posts from this blog

Java program to create staircase

Observe that its base and height are both equal to  , and the image is drawn using  #  symbols and spaces.  The last line is not preceded by any spaces. Write a program that prints a staircase of size  . Input Format A single integer,  , denoting the size of the staircase. Output Format Print a staircase of size   using  #  symbols and spaces. Note : The last line must have   spaces in it. package com.rohan.test; import java.util.Scanner; public class StaircaseTest {     public static void main(String[] args) {         Scanner in = new Scanner(System.in);         int n = in.nextInt();                  for(int i = 0; i< n; i++) {         for(int k = 0; k < n; k++) {         if(k < n-i-1)         System.out.p...

Java program to print the maximum hourglass value of the matrix

Context   Given a    2D Array ,  : 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 We define an hourglass in   to be a subset of values with indices falling in this pattern in  's graphical representation: a b c d e f g There are   hourglasses in  , and an  hourglass sum  is the sum of an hourglass' values. Task   Calculate the hourglass sum for every hourglass in  , then print the  maximum  hourglass sum. Note:  If you have already solved the Java domain's  Java 2D Array  challenge, you may wish to skip this challenge. Input Format There are   lines of input, where each line contains   space-separated integers describing  2D Array   ; every value in   will be in the inclusive range of   to  . Constraints Output Format Print the largest (maximum) hourglass sum f...