Thursday 30 March 2023

How to Implement Fuzzy Search or Approximate String Search in Java

What Is Fuzzy Matching ?

Fuzzy Matching or Approximate String Matching is among the most discussed issues in IT.
It is a method that offers an improved ability to identify two elements of text, strings, or entries that are approximately similar but are not precisely the same.
In other words, a fuzzy method may be applied when an exact match is not found for phrases or sentences on a database. Indeed, this method attempts to find a match greater than the application-defined match percentage threshold.

As below mentioned code you can implement Fuzzy Search. 


import org.apache.commons.codec.language.Soundex;
import org.apache.commons.text.similarity.LevenshteinDistance;
import me.xdrop.fuzzywuzzy.FuzzySearch;

public class FuzzySearch {

   public boolean searchFuzzy(String searchableName, String targetName) {
       boolean matches=false;
       int  fuzzySearchNameThreashold=70;
        System.out.println("FuzzySearch.tokenSetRatio(searchableName, targetName) >> "+FuzzySearch.tokenSetRatio(searchableName, targetName));
        System.out.println("levenshteinDistanceMatch(searchableName, targetName) >> "+levenshteinDistanceMatch(searchableName, targetName));
       if((soundexMatch(searchableName,targetName)
        || FuzzySearch.tokenSetRatio(searchableName, targetName) >= fuzzySearchNameThreashold
        || levenshteinDistanceMatch(searchableName, targetName) >= fuzzySearchNameThreashold)) {    
              matches = true;
        }
       return matches;
    }

   public boolean soundexMatch(String searchableName, String targetName) {
         Soundex soundex = new Soundex();
         return soundex.soundex(searchableName).equals(soundex.soundex(targetName));
   }

     public double levenshteinDistanceMatch(String searchableName, String targetName) {
         LevenshteinDistance levenshteinDistance = new LevenshteinDistance();
         return (100 - Math.round((((double) levenshteinDistance.apply(searchableName, targetName) / searchableName.length()) * 100)));
       }

 public static void main(String aa[]) {
       FuzzySearchUtil fuzzySearchUtil = new FuzzySearchUtil();
       boolean flag = fuzzySearchUtil.searchFuzzy("Amn","Aman Kumar");
       System.out.println("flag >> "+flag);
 }

    }
}

----------------------- Maven Dependency -------------------------

           <dependency>
                <groupId>me.xdrop</groupId>
                <artifactId>fuzzywuzzy</artifactId>
                <version>1.3.1</version>
             </dependency>

        <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
             <dependency>
                 <groupId>commons-codec</groupId>
                 <artifactId>commons-codec</artifactId>
                 <version>1.10</version>
             </dependency>

           <dependency>
              <groupId>org.apache.commons</groupId>
              <artifactId>commons-text</artifactId>
              <version>1.3</version>
           </dependency>




Saturday 26 November 2022

Create Rest APT to Encrypt and Decrypt message using AES/CBC/PKCS5PADDING algorithm

Project Structure



Calling Response from Postman tool





------------------------------------------- Controller ---------------------------------------------
package com.ramsis.encrypt.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ramsis.encrypt.util.EncryptionDecryption;
import com.ramsis.encrypt.dto.POJO;

@RestController
public class Controller {
   
@Autowired
EncryptionDecryption ecndnc;

@Value("${EncDncKey}")
String publickey;

@CrossOrigin(origins = "*")
@PostMapping("/Ngdecrypt")
public POJO NGdecrypt(@RequestBody POJO pojo) throws Exception {

String msg = pojo.getMessage();
String enckey = pojo.getKeys();
String decryptString = null;
// String publickey = "3K4G2pb4dl8M/7YaOrGiPA=="; // 128 bit key
try {
if (!enckey.equalsIgnoreCase(publickey)) {
System.out.println("You are not Authorised.");
pojo.setMessage("Not Authorised.");
System.out.println(pojo.getMessage());
return pojo;
}

decryptString = ecndnc.decrypt(publickey, null, msg);
pojo.setMessage(decryptString);
} catch (Exception ex) {
ex.getMessage();
}

return pojo;
}

@CrossOrigin(origins = "*")
@PostMapping("/Ngencrypt")
public POJO Ngencrypt(@RequestBody POJO pojo) throws Exception {

String msg = pojo.getMessage();
String enckey = pojo.getKeys();
String encryptString = null;
try {
if (!enckey.equalsIgnoreCase(publickey)) {
System.out.println("You are not Authorised.");
pojo.setMessage("Not Authorised.");
return pojo;
}
encryptString = ecndnc.encrypt(publickey, null, msg);
pojo.setMessage(encryptString);
//System.out.println(encryptString);
} catch (Exception ex) {
ex.getMessage();
}
return pojo;
}
}

----------------------------------------EncryptionDecryption----------------------------------------

package com.ramsis.encrypt.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

@Component
public class EncryptionDecryption {

public static String encrypt(String key, String initVector, String value) {
byte[] encrypted =null;
try {
initVector = key.substring(0, 16); // 16 bytes IV
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

   encrypted = cipher.doFinal(value.getBytes());
System.out.println("encrypted string: " + Base64.encodeBase64String(encrypted));
} catch (Exception ex) {
ex.printStackTrace();
}
return Base64.encodeBase64String(encrypted);
}

public static String decrypt(String key, String initVector, String encrypted) {
byte[] original =null;
try {
initVector = key.substring(0, 16);
IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
   original = cipher.doFinal(Base64.decodeBase64(encrypted));
} catch (Exception ex) {
ex.printStackTrace();
}
return new String(original);
}

}

------------------------------------------------ CallAPI ----------------------------------------------
package com.ramsis.encrypt.callApi;

import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class CallAPI {

public void restAPITest(String url, String message) {

String key = "3K4G2pb4dl8M/7YaOrGiPA==";
try {
RestTemplate restTemplate = new RestTemplate();
JSONObject personJsonObject = new JSONObject();
personJsonObject.put("keys", key);
personJsonObject.put("message", message);

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<String> entityHttp = new HttpEntity<String>(personJsonObject.toString(), headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entityHttp, String.class);
/*
* String answer = restTemplate.postForObject(url, entity, String.class);
* System.out.println(answer);
*/
if (response.getStatusCodeValue() == 200) {
System.out.println(response.getBody());
}

} catch (Exception ex) {
ex.printStackTrace();
}
}

public static void main(String args[]) throws Exception {
CallAPI call = new CallAPI();
//call.restAPITest("http://localhost:8080/Ngencrypt", "ramsis-code");
call.restAPITest("http://localhost:8080/Ngdecrypt", "TaZydiy5PHtA4ME8744bOA==");

}
}

Sunday 20 November 2022

Spring Boot Rest API OneToMany Relationship with JPA Repository

In this Post I am showing how you can easily create a Rest API using JPA Repository with OneToMany Relationships between two Entities.

Project Structure



Calling Response from Postman tool














------------------------------------------ json ------------------------------------------------

{
"title":"Linux",
"author": "Jimmy",
"isbn": "890900",
    "pages" : [{ "number": "30", "content": "Switches", "chapter" : "3"},{ "number": "125", "content":          "Router", "chapter" : "8"}]
}


------------------------------------------ pom.xml -------------------------------------------

# Changing the server port
server.port=9090

# MySQL connection properties
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=cctns@123
spring.datasource.url=jdbc:mysql://localhost:3306/testdb?createDatabaseIfNotExist=true&useSSL=false

# Log JPA queries
# Comment this in production
spring.jpa.show-sql=true

# Drop and create new tables (create, create-drop, validate, update)
# Only for testing purposes - comment this in production
spring.jpa.hibernate.ddl-auto=update

# Hibernate SQL dialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect


---------------------------------------- Book Entity ------------------------------------------------

package com.ramsis.onetomany.entity;

import java.io.Serializable;
import java.util.Objects;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@Entity
@Table(name = "books")
public class Book implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    @Column(name = "title" ,nullable = false)
    private String title;
    @Column(name = "author" ,nullable = false)
    private String author;
    @Column(name = "isbn" ,unique = true)
    private String isbn;
    @JsonIgnoreProperties("book")
    @OneToMany(mappedBy = "book", fetch = FetchType.LAZY,
            cascade = CascadeType.ALL)
    private Set<Page> pages;

    public Book() {
    }

    public Book(String title, String author, String isbn) {
        this.title = title;
        this.author = author;
        this.isbn = isbn;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public Set<Page> getPages() {
        return pages;
    }

    public void setPages(Set<Page> pages) {
        this.pages = pages;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book book = (Book) o;
        return id.equals(book.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", isbn='" + isbn + '\'' +
                '}';
    }
}

------------------------------------------ Page Entity -----------------------------------------------

package com.ramsis.onetomany.entity;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;

@Entity
@Table(name = "pages")
public class Page implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
   
    @Column(name = "number", nullable = false)
    private int number;
   
    @Column(name = "content" ,nullable = false)
    private String content;
   
    @Column(name = "chapter", nullable = false)
    private String chapter;
   
    @ManyToOne(fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = "book_id", nullable = false)
    private Book book;

    public Page() {
    }

    public Page(int number, String content, String chapter, Book book) {
        this.number = number;
        this.content = content;
        this.chapter = chapter;
        this.book = book;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getChapter() {
        return chapter;
    }

    public void setChapter(String chapter) {
        this.chapter = chapter;
    }

    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Page page = (Page) o;
        return id.equals(page.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }

    @Override
    public String toString() {
        return "Page{" +
                "id=" + id +
                ", number=" + number +
                ", content='" + content + '\'' +
                ", chapter='" + chapter + '\'' +
                ", book=" + book +
                '}';
    }
}

----------------------------------------------- BookService -----------------------------------------

package com.ramsis.onetomany.service;

import java.util.List;
import java.util.Set;

import com.ramsis.onetomany.dto.BookDto;
import com.ramsis.onetomany.entity.Book;
import com.ramsis.onetomany.entity.Page;

public interface BookService {

public List<Book> getBooks();
public Book addBook(BookDto book);
public Book updateBook(BookDto book);
public Book getBookByIsbn(String id);

}

-------------------------------------------------BookServiceImpl ----------------------------------

package com.ramsis.onetomany.service;

import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ramsis.onetomany.dto.BookDto;
import com.ramsis.onetomany.dto.PageDto;
import com.ramsis.onetomany.entity.Book;
import com.ramsis.onetomany.entity.Page;
import com.ramsis.onetomany.repository.BookRepository;
import com.ramsis.onetomany.repository.PageRepository;

@Service
public class BookServiceImpl implements BookService {

@Autowired
BookRepository bookRepo;

@Autowired
PageRepository pageRepo;

@Override
public Book getBookByIsbn(String id) {
// TODO Auto-generated method stub
return bookRepo.findByIsbn(id);
}

@Override
public Book addBook(BookDto book) {
Book bookEntity = new Book();
Page pageEntity = null;
bookEntity.setAuthor(book.getAuthor());
bookEntity.setIsbn(book.getIsbn());
bookEntity.setTitle(book.getTitle());
Set<PageDto> pageList = book.getPages();
Book bookEntityobj = bookRepo.save(bookEntity);

for (PageDto pagedata : pageList) {
pageEntity = new Page(
pagedata.getNumber(),
pagedata.getContent(),
pagedata.getChapter(),
bookEntityobj);
pageRepo.save(pageEntity);
}

return bookEntityobj;
}

@Override
public Book updateBook(BookDto book) {
Book bookEntity = new Book();
Page pageEntity = null;
bookEntity.setAuthor(book.getAuthor());
bookEntity.setIsbn(book.getIsbn());
bookEntity.setTitle(book.getTitle());
Set<PageDto> pageList = book.getPages();
Book bookEntityobj = bookRepo.save(bookEntity);

for (PageDto pagedata : pageList) {
pageEntity = new Page(
pagedata.getNumber(),
pagedata.getContent(),
pagedata.getChapter(),
bookEntityobj);
pageRepo.save(pageEntity);
}

return bookEntityobj;
}

@Override
public List<Book> getBooks() {
// TODO Auto-generated method stub
return  (List<Book>) bookRepo.findAll();
}

}

---------------------------------------------- Controller ---------------------------------------------

package com.ramsis.onetomany.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.ramsis.onetomany.dto.BookDto;
import com.ramsis.onetomany.entity.Book;
import com.ramsis.onetomany.service.BookService;

@RestController
public class PageBookController {
   
@Autowired
BookService bookService;

@GetMapping("/home")
public String home() {
return "Welcome in RestApi with OneToMany Relation, home Page";
}

@PostMapping("/addBook" )
public Book addBook(@RequestBody  BookDto book) {
return this.bookService.addBook(book);
}

@PostMapping("/updateBook" )
public Book updateBook(@RequestBody  BookDto book) {
return this.bookService.updateBook(book);
}

@GetMapping("/getBookIsbn/{eid}")
public Book getBookByIsbn(@PathVariable("eid") String eid) {
return this.bookService.getBookByIsbn(eid);
}

@GetMapping("/getBooks")
public List<Book> getBooks() {
return this.bookService.getBooks();
}
}

------------------------------------------------- BookDto --------------------------------------------

package com.ramsis.onetomany.dto;

import java.util.Set;

public class BookDto {
private Long id;
private String title;
private String author;
private String isbn;
private Set<PageDto> pages;

public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Set<PageDto> getPages() {
return pages;
}
public void setPages(Set<PageDto> pages) {
this.pages = pages;
}

}

-------------------------------------------------- PageDto -------------------------------------------

package com.ramsis.onetomany.dto;

public class PageDto {
private Long id;
private int number;
private String content;
private String chapter;
private BookDto book;

public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getChapter() {
return chapter;
}
public void setChapter(String chapter) {
this.chapter = chapter;
}
public BookDto getBook() {
return book;
}
public void setBook(BookDto book) {
this.book = book;
}

}


------------------------------------------------- OnetomanyApplication -------------------------

package com.ramsis.onetomany;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

import com.ramsis.onetomany.repository.BookRepository;
import com.ramsis.onetomany.repository.PageRepository;

@SpringBootApplication
@EnableJpaAuditing
public class OnetomanyApplication {

public static void main(String[] args) {
SpringApplication.run(OnetomanyApplication.class, args);
}


@Bean
   public CommandLineRunner mappingDemo(BookRepository bookRepository,
                                        PageRepository pageRepository) {
       return args -> {
        /*
        System.out.print( bookRepository.findById(Long.valueOf(1)));
           // create a new book
           Book book = new Book("Linux", "Cdac", "99844");

           // save the book
           bookRepository.save(book);

           // create and save new pages
           pageRepository.save(new Page(2, "Introduction contents of Linux", "Intro", book));
           pageRepository.save(new Page(102, "Switches", "Switches WAN", book));
           pageRepository.save(new Page(70, "Router", "Router WAN", book));
         
           */
       };
   }
}

-------------------------------------------- BookRepository ---------------------------------------

package com.ramsis.onetomany.repository;

import org.springframework.data.repository.CrudRepository;

import com.ramsis.onetomany.entity.Book;

public interface BookRepository extends CrudRepository<Book, Long> {

    Book findByIsbn(String isbn);
    Book save(Book book);
}

--------------------------------------------------------

Saturday 10 September 2022

Enabling Cross Origin Requests for a RESTful Web Service
How to Resolve Cross Origin Error in Java Spring Application




This Cross Origin Error Occurs then you are trying to access your Spring boot or Spring Application from outer source. Like Angular, React and other ways.
you can resolve this Error by creating A Cross CORSFilter or you can create simpleCorsFilter Bean in Configuration class

------------------------------------------- CORSFilter ----------------------------------------------------------

import javax.servlet.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
 
 @Component
  public class CORSFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException{
  HttpServletResponse response = (HttpServletResponse) res;
  response.setHeader("Access-Control-Allow-Origin", "*");
  response.setHeader("Access-Control-Allow-Methods", "POST, GET");
  response.setHeader("Access-Control-Max-Age", "3700");
  response.setHeader("Access-Control-Allow-Headers","Content-Type");
  response.setHeader("Access-Control-Allow-Credentials","true");
  chain.doFilter(req, res);
  }
  public void init(FilterConfig filterConfig) {
  }
  public void destroy() {
  }
  }

------------------------------------------------------ simpleCorsFilter  Bean -------------------------------------

@Bean
public FilterRegistrationBean simpleCorsFilter() {  
   UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();  
   CorsConfiguration config = new CorsConfiguration();  
   config.setAllowCredentials(true);
   // *** URL below needs to match the Vue client URL and port ***
   config.setAllowedOrigins(Collections.singletonList("https://192.168.1.204:4200"));
   config.setAllowedMethods(Collections.singletonList("*"));  
   config.setAllowedHeaders(Collections.singletonList("*"));  
   source.registerCorsConfiguration("/**", config);
   
   FilterRegistrationBean bean = new FilterRegistrationBean<>(new CorsFilter(source));
   bean.setOrder(Ordered.HIGHEST_PRECEDENCE);  
   return bean;  
}  


Wednesday 3 August 2022

How to create A Pagination using Hibernate in Java








----------------------------- DAO.java ---------------------------------------

package com.ramsiscode;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Projections;


public class DAO {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
private static int pageSize = 8;
Session session = null;
public  List getData(int pageNumber) {
 
  //Session session = sessionFactory.getCurrentSession();
 
  List result = null;
  try {
session = sessionFactory.openSession();
    session.beginTransaction();
   
    Query query = session.createQuery("from Employee");
     query = query.setFirstResult(pageSize * (pageNumber - 1));
     query.setMaxResults(pageSize);
     
    result = query.list();
    session.getTransaction().commit();
  } catch (Exception e) {
    e.printStackTrace();
  }finally{
  if(session!=null){
  session.close();
  }
  }
  return result;
}
 

  public  Long getMaxRow() {
  Long result = 0l;
 // SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  //Session session =null;
  try{
  session = sessionFactory.openSession();  
  session.beginTransaction();
  Criteria crit = session.createCriteria(Employee.class);
  crit.setProjection(Projections.rowCount());
 
  //result = session.createCriteria(Employee.class).setProjection(Projections.rowCount());
  //Query query = session.createQuery("select COUNT(empId) from Employee");
  session.getTransaction().commit();
 
  if(crit.list().size()>0)
  {
  result=   (Long) crit.list().get(0);
  }
 
  System.out.println("--------- rowCount -------- "+result);
 
 
  }catch(Exception e)
  {e.printStackTrace();}
  finally{
 if(session!=null){
  session.close();
  }
  }
  return result;
  }


private static Integer parseInt(Object object) {
// TODO Auto-generated method stub
return null;
}
}

------------------------------ Employee.java ------------------------

package com.ramsiscode;
import java.io.*;
public class Employee {
public long empId;
public String empName=null;
public String empJob=null;
public long empSal;
public long getEmpId() {
return empId;
}
public void setEmpId(long empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public String getEmpJob() {
return empJob;
}
public void setEmpJob(String empJob) {
this.empJob = empJob;
}
public long getEmpSal() {
return empSal;
}
public void setEmpSal(long empSal) {
this.empSal = empSal;
}

}

---------------------------- PaginationCreateQueryControl.java -------------------------------

package com.ramsiscode;
import java.io.DataInputStream;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class PaginationCreateQueryControl {
private static  SessionFactory sessionFactory;
 private Session getSession()
 {
 Session s =null;
    try{
sessionFactory = new Configuration().configure("com\\xml\\hibernate.cfg.xml").buildSessionFactory();
s=sessionFactory.openSession();
}catch(HibernateException e){
System.out.println(e.getMessage());
  }finally{
  if(s!=null){
  s.close();
  }
  }
  return s;
 }

 public  List param(String[] args) throws Exception
{
List list = null;
Session s = getSession();
try{
DataInputStream ds=new DataInputStream(System.in);
System.out.println("*********************\n");
System.out.println("Enter the Degree to Search");
String first=ds.readLine();

Query query = s.createQuery("from Student stu where stu.degree = :deg order by stu.id ASC");
query.setString("deg",first);
query.setFirstResult(0);
query.setMaxResults(3);
list = query.list();
}catch(HibernateException e)
  {
    System.out.println(e.getMessage());
     }finally{
  if(s!=null){
  s.close();
  }
  }
  return list;
  }
}

---------------------------- Employee.hbm.xml ------------------------

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
   "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
 <class name="com.ramsiscode.Employee" table="emp">
   <id name="empId" column="EMPNO" type="long">
     <generator class="native"/>
   </id>
   <property name="empName" column="ENAME" />
   <property name="empJob" column="JOB" />
   <property name="empSal" column="SAL" type="long"/>
 </class>
</hibernate-mapping>

----------------------------- hibernate.cfg.xml ------------------------

<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="studentFactory">
       <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://10.68.238.96:3306/exampledb</property>
<property name="connection.username">cctns_app</property>
<property name="connection.password">cctns@123</property>
       <property name="connection.pool_size">5</property>
       <!-- SQL dialect -->
       <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
       <!-- Echo all executed SQL to stdout -->
       <property name="show_sql">true</property>
  <property name="hbm2ddl.auto">update</property>
<mapping resource="\com\\xml\\Student.hbm.xml"/>
<mapping resource="\com\\xml\\Employee.hbm.xml"/>

</session-factory>
</hibernate-configuration>

--------------------------- pagingEmp.jsp --------------------------


  <%@page import="com.ramsiscode.DAO" %>
  <%@page import="java.util.List" %>
  <%@page import="java.lang.Math" %>
  <%@page import="java.util.ArrayList" %>
  <%@ taglib uri='http://java.sun.com/jsp/jstl/core' prefix='c'%>
  <jsp:directive.page contentType="text/html; charset=UTF-8" />
 <link rel="stylesheet" type="text/css" href="css/screen.css" />
 <%
     int pageNumber=1;
     int footerPageLimit =4;
     String  prePage ="1";
     String nextPage ="1";
   
     int empListSize = 0;
     List sizeList =(List)  session.getAttribute("EmpList");
     if(sizeList!=null){
    empListSize = ((Integer) sizeList.size());
     }
     
     DAO dao = new DAO();
     Long   maxRow = dao.getMaxRow();
     System.out.println("maxRow size ------------"+maxRow);
     Integer pageLinks = Math.round(maxRow/8)+1;
     System.out.println("pageLinks ------------"+pageLinks);
     session.setAttribute( "pageLinks", pageLinks);

     
     if(request.getParameter("page") != null) {
       session.setAttribute("page", request.getParameter("page"));
       pageNumber = Integer.parseInt(request.getParameter("page"));
       
        Integer pageLinks_Session = (Integer) session.getAttribute("pageLinks");
        if(pageNumber>(pageLinks_Session)){
      pageNumber=1;
       }
       
        if(empListSize==0){
      pageNumber=1;
       }
       
       nextPage = (pageNumber +1) + "";
       prePage = (pageNumber -1) + "";
 
       String pages = request.getParameter("page");
      if(pages.equalsIgnoreCase("1")){
      prePage="1";
       }
     } else {
       session.setAttribute("page", "1");
     }
     
     /**********************************/
   
     session.setAttribute( "EmpList", dao.getData(pageNumber));

     
     /**********************************/

     
     System.out.println("empListSize : "+empListSize);
     if(empListSize==0){
    session.setAttribute("page", "1");
    nextPage ="1";
    prePage ="1";
     }
     
     int  prePages = (pageNumber)- 1;
     prePage =(String.valueOf(prePages));
     if(pageNumber==1){
    prePage ="1";
     }
     
     /**********************************/
     int startPage=  pageNumber;
     int endPage =  startPage+footerPageLimit-1;
     if(empListSize==0){
    startPage = 1;
    endPage = startPage+footerPageLimit-1;
     }
     /* if(pageNumber>=pageLinks){
    startPage=pageNumber;
    endPage=pageNumber;
     } */
     /**********************************/
     
     String myUrl = "pagingEmp.jsp?page=" + nextPage;
     String preUrl = "pagingEmp.jsp?page=" + prePage;
     System.out.println(myUrl);
 
     pageContext.setAttribute("myUrl", myUrl);
     pageContext.setAttribute("preUrl", preUrl);
%>
 <h2 align="center">Hibernate Pagination</h2>
<%--  <jsp:useBean id="EmpList" scope="request" type="java.util.List"></jsp:useBean> --%>

 <table>
   <tr>
     <th>Emp Id</th>
     <th>Name</th>
     <th>Job</th>
     <th>Salary</th>
   </tr>
   <c:forEach items="${EmpList}" var="emp" begin="0" end="10">
     <tr>
       <td><c:out value="${emp.empId}"></c:out></td>
       <td><c:out value="${emp.empName}"></c:out></td>
       <td><c:out value="${emp.empJob}"></c:out></td>
       <td><c:out value="${emp.empSal}"></c:out></td>
     </tr>
   </c:forEach>
 </table>
 <BR/>
 <Table>
 <tr>
 <td colspan="2"><a href="${pageScope.preUrl}"><<&nbsp;previous</a>&nbsp;
     <c:forEach  var="i" begin="<%=startPage %>" end="<%=endPage %>">
        <a href="?page=${i}"> <c:out value="${i}"></c:out></a>
     </c:forEach>
     &nbsp; <a href="${pageScope.myUrl}">nextPage&nbsp;>></a></td>
 </tr>
 </Table>

Download Code

Create A Struts2 CRUD Application with Tiles configuration











-----------------------------------------  Auth.java -------------------------------------

package com.ramsis.actions;
import java.io.Serializable;

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

@Entity
@Table(name = "auth")
public class Auth implements Serializable {
@Id
@GeneratedValue
@Column(name="uid")
private int uid;
@Column(name="username")
private String username;
@Column(name="pass")
private String pass;

public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}


-------------------------------- CustomerAction.java ----------------------------------
package com.ramsis.actions;

import com.opensymphony.xwork2.ActionSupport;

public class CustomerAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private Integer age;
private String email;
private String telephone;

public String addCustomer() {
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}

}

-------------------------- LoginAction.java -------------------------

package com.ramsis.actions;

import com.opensymphony.xwork2.ActionSupport;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import org.hibernate.*;
import org.hibernate.cfg.AnnotationConfiguration;

public class LoginAction extends ActionSupport implements SessionAware {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private String pass;
private String u;
private String p;
Map m;
public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPass() {
return pass;
}

public void setPass(String pass) {
this.pass = pass;
}



public String getU() {
return u;
}

public void setU(String u) {
this.u = u;
}

public String getP() {
return p;
}

public void setP(String p) {
this.p = p;
}



public String logOut(){
m.remove("loginId");
addActionMessage("You Have Been Successfully Logged Out");
return SUCCESS;
}

public String execute() {
try{
SessionFactory cfg = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = cfg.openSession();
Transaction t = session.beginTransaction();
//Auth auth = new Auth();
//auth.setUsername("pavan");
//auth.setPass("pavan");
//session.save(auth);
//t.commit();

Query u= session.createQuery("from Auth where username= '"+username+"' and pass= '"+pass+"'");
List<Auth> li = u.list();
if(li.size()>0){
Iterator<Auth> itr = li.iterator();
while(itr.hasNext()){
Auth a = itr.next();
m.put("loginId", a.getUsername());
}

System.out.println("session name is :"+m.get("loginId"));
t.commit();
session.close();


return "success";
}else{

addActionError(getText("Your User name and Password is not valid. "));
return "error";
}
}catch(Exception e){
e.printStackTrace();
addActionError(getText("Some technical error has been occured, Please login after some time.  "));
return "error";

}
}


@Override
public void setSession(Map<String, Object> arg0) {
this.m=arg0;

}

}

-------------------------------- LoginAction-Validation.xml ------------------------

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
  "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
  "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="username">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message>User Name is required.</message>
</field-validator>
</field>
<field name="pass">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message key="password.required" />
</field-validator>
</field>
</validators>

----------------------------- ClearCacheInterceptor.java ---------------------------

package com.ramsis.clearcache.interceptor;

import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class ClearCacheInterceptor  extends AbstractInterceptor{
private static final long serialVersionUID = 1L;

@Override
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext context=(ActionContext)invocation.getInvocationContext();
HttpServletResponse response=(HttpServletResponse)context.get(StrutsStatics.HTTP_RESPONSE);
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
String result=invocation.invoke();
return result;
}
}

--------------------------- ClientForSave.java -------------------------------

package com.ramsis.hibernate.contact.util;

import org.hibernate.*;
import org.hibernate.cfg.*;

import com.opensymphony.xwork2.ActionSupport;
public class ClientForSave extends ActionSupport {

private Long id;
private String name;
private int age;
private String email;
private String telephone;

public Long getId() {
return id;
}

public String getName() {
return name;
}

public int getAge() {
return age;
}

public String getEmail() {
return email;
}

public String getTelephone() {
return telephone;
}

public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
   

    public String addCustomer()
    {
   
        Configuration cfg = new AnnotationConfiguration().configure();
 
        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();
        Contact p=new Contact();
       
        p.setName(getName());
        p.setAge(getAge());
        p.setEmail(getEmail());
        p.setTelephone(getTelephone());
 
        Transaction tx = session.beginTransaction();
        session.save(p);
        System.out.println("Object saved successfully.....!!");
        tx.commit();
        session.close();
        factory.close();
       
        return "success";
    }
 
}

---------------------------------- Contact.java ---------------------------

package com.ramsis.hibernate.contact.util;

public class Contact{

private Long id;
private String name;
private Integer age;
private String email;
private String telephone;
private String username;


public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
private String password;

public Long getId() {
return id;
}

public String getName() {
return name;
}

public Integer getAge() {
return age;
}

public String getEmail() {
return email;
}

public String getTelephone() {
return telephone;
}

public void setId(Long id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public void setEmail(String email) {
this.email = email;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
   

}

------------------------------ DeleteData.java ---------------------------------

package com.ramsis.hibernate.contact.util;

import com.opensymphony.xwork2.ActionSupport;
import java.util.ArrayList;
import java.util.List;


import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;

public class DeleteData extends ActionSupport{

    private String telephone;
private String msg="Records found.";
private String q;
public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

public String getTelephone() {
return telephone;
}

public void setTelephone(String telephone) {
this.telephone = telephone;
}

public String execute(){
try{
SessionFactory cfg = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = cfg.openSession();
Transaction t = session.beginTransaction();
Transaction t1 = session.beginTransaction();
Query qr1 = session.createQuery("from Contact where telephone='"+telephone+"'");
List<Contact> li = qr1.list();
//System.out.println("telephone : "+telephone);
if(telephone==(null)||telephone==("")||li.size()==0){
    System.out.println("No record Deleted!!");
    msg="No record Deleted!!";
    return "success";
}
else{
   q ="delete from Contact where telephone='"+telephone+"'";

Query qr = session.createQuery(q);
qr.executeUpdate();
t.commit();
session.close();
System.out.println("Record has been Deleted.");
    msg="Record has been Deleted!!";
      return "success";
}
}
catch(Exception e){
e.printStackTrace();
return "error+'"+e+"'";
}

}
  }

------------------------------------- Product.java ----------------------------------------

package com.ramsis.hibernate.contact.util;
public class Product{

private int productId;
private String proName;
private double price;

public void setProductId(int productId)
{
   this.productId = productId;
}
public int getProductId()
{
   return productId;
}

public void setProName(String proName)
{
   this.proName = proName;
}
public String getProName()
{
   return proName;
}

public void setPrice(double price)
{
   this.price = price;
}
public double getPrice()
{
   return price;
}
}

----------------------------------- ShowData.java -------------------------------------

package com.ramsis.hibernate.contact.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.hibernate.*;
import org.hibernate.cfg.AnnotationConfiguration;

import com.opensymphony.xwork2.ActionSupport;

public class ShowData extends ActionSupport {
private List<Contact> comboMeals = new ArrayList<Contact>();

public List<Contact> getComboMeals() {
return comboMeals;
}
 
public void setComboMeals(List<Contact> comboMeals) {
this.comboMeals = comboMeals;
}
public String execute(){
try{
SessionFactory cfg = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = cfg.openSession();
Transaction t = session.beginTransaction();

Query s = session.createQuery("from Contact");

List<Contact> li = s.list();
Iterator<Contact> itr = li.iterator();

while(itr.hasNext()){
Contact c = itr.next();
//System.out.println(c.getName());
// c.getName();
// c.getEmail();
// c.getPassword();
// c.getTelephone();
// c.getUsername();
comboMeals.add(c);
//System.out.println(t.wasCommitted());
}

t.commit();
session.close();

}
catch(Exception e){
e.printStackTrace();
}
if(comboMeals.size()>0){
return "success";
}
else{
return "error";
}

 }

}

----------------------------------------- ShowTest.java -----------------------

package com.ramsis.hibernate.contact.util;

import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;

public class ShowTest extends ActionSupport {
private List<String> comboMeals;

public List<String> getComboMeals() {
return comboMeals;
}
 
public void setComboMeals(List<String> comboMeals) {
this.comboMeals = comboMeals;
}
 
public String execute() {
 
comboMeals = new ArrayList<String>();
comboMeals.add("Snack Plate");
comboMeals.add("Dinner Plate");
comboMeals.add("Colonel Chicken Rice Combo");
comboMeals.add("Colonel Burger");
comboMeals.add("O.R. Fillet Burger");
comboMeals.add("Zinger Burger");
 
return SUCCESS;
}

}


------------------------------------ Update.java ------------------------

package com.ramsis.hibernate.contact.util;

import org.hibernate.*;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.opensymphony.xwork2.ActionSupport;

public class Update extends ActionSupport {

private int id;
private String name;
private String age;
private String telephone;
private String email;
private String msg="";


public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email=email;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}

public String execute(){

 try{
SessionFactory cfg = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = cfg.openSession();
Transaction t =  session.beginTransaction();
Query u = session.createQuery("update Contact set name='"+name+"', age='"+age+"', email='"+email+"' , telephone='"+telephone+"' where id ='"+id+"'");
       u.executeUpdate();
   t.commit();
   session.close();
   //System.out.println(t.wasCommitted());
   boolean ck = t.wasCommitted();
   
   if(ck==(false)){
    System.out.println("Record has not updated.");
    msg="Record has not updated.";
    return "error";
   }
   
   else
    System.out.println("Record has been updated.");
       msg="Record has been updated.";
       return "success";
   }  
catch(Exception e){
e.printStackTrace();
return "error";
}

}

}

---------------------------------- UpdateData.java --------------------------------

package com.ramsis.hibernate.contact.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Iterator;
import org.hibernate.*;
import org.hibernate.annotations.*;
import org.hibernate.cfg.AnnotationConfiguration;

import com.opensymphony.xwork2.ActionSupport;

public class UpdateData extends ActionSupport{

private String name;
private String telephone;
private String msg="";
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}

private List<Contact> list = new ArrayList<Contact>();

public List<Contact> getList() {
return list;
}
public void setList(List<Contact> list) {
this.list = list;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}

public String execute(){
       try{
SessionFactory cfg = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = cfg.openSession();
Transaction t = session.beginTransaction();

Query q = session.createQuery("from Contact where telephone='"+telephone+"' and name='"+name+"'");

List <Contact> li = q.list();

Iterator <Contact> itr = li.iterator();
System.out.println(name);
System.out.println(telephone);
if(li.size()==0){
msg="No record found!!";
System.out.println(msg);
return "error";
}
System.out.println("size : "+li.size());
msg="Records found.";
while(itr.hasNext()){

Contact c = itr.next();

System.out.println(msg);
list.add(c);
}

t.commit();

       }
       catch(Exception e){
      e.printStackTrace();
       }
    return "success";
}

public String click(){
return "success";
}
}

---------------------------------------- ClientForSave-validation.xml ----------------------

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
  "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
  "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name="name">
<field-validator type="requiredstring">
<param name="trim">true</param>
<message key="name.required" />
</field-validator>
</field>
<field name="age">
<field-validator type="required">
<message key="error.required" />
</field-validator>
<field-validator type="int">
<param name="min">1</param>
<param name="max">100</param>
<message key="age.range"/>
</field-validator>
</field>
<field name="email">
<field-validator type="requiredstring">
<message key="email.required" />
</field-validator>
<field-validator type="email">
<message key="email.invalid" />
</field-validator>
</field>
<field name="telephone">
<field-validator type="requiredstring">
<message key="errors.required" />
</field-validator>
</field>
</validators>

------------------------------------ LoginInterceptor.java -------------------------

package com.ramsis.loginapi.interceptor;

import java.util.Map;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class LoginInterceptor implements Interceptor {
private static final long serialVersionUID = 1L;
@Override
public void destroy() {
// TODO Auto-generated method stub

}

@Override
public void init() {
// TODO Auto-generated method stub

}

@Override
public String intercept(ActionInvocation invocation) throws Exception {
Map<String, Object> sessionAttributes = invocation.getInvocationContext().getSession();

if (sessionAttributes == null || sessionAttributes.get("loginId") == null) {
return "login";
} else {
if (!((String) sessionAttributes.get("loginId")).equals(null)) {
return invocation.invoke();
} else {
return "login";
}
}

}

}

------------------------------------ Contact.hbm.xml --------------------------------

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
<class name="com.ramsis.hibernate.contact.util.Contact" table="Contact">

<id name="id" column="Id"  >
<generator class="increment"/>
</id>
<property name="name" column="Name" length="30"/>
<property name="age" column="Age" length="10"/>
<property name="email" column="Email" length="20"/>
<property name="telephone" column="Telephone" length="30"/>

</class>
</hibernate-mapping>

------------------------------------ hibernate.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>

<!-- Database connection settings -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/exampledb
</property>
<property name="connection.username">cdb</property>
<property name="connection.password">1234</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>

<!--  <mapping class="com.ramsis.hibernate.contact.model.Contact" /> -->
          <mapping class="com.ramsis.actions.Auth" />
          <mapping resource="Contact.hbm.xml" />
       
</session-factory>

</hibernate-configuration>

----------------------------------- struts.xml -----------------------------------

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>
    <constant name="struts.enable.DynamicMethodInvocation" value="false" />
    <constant name="struts.devMode" value="false" />
    <constant name="struts.custom.i18n.resources" value="ApplicationResources" />
   
    <package name="default" extends="struts-default" namespace="/" >
         <result-types>
            <result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
        </result-types>
       
      <interceptors>
<interceptor name="loginInterceptor" class="com.ramsis.loginapi.interceptor.LoginInterceptor1" ></interceptor>
<interceptor name="clear-cache" class="com.ramsis.clearcache.interceptor.ClearCacheInterceptor" ></interceptor>
<interceptor-stack name="loginStack">
<interceptor-ref name="loginInterceptor" />
<interceptor-ref name="defaultStack" />
</interceptor-stack>
 </interceptors>
     
         <global-results>
<result name="login">/Login.jsp</result>
</global-results>

        <action name="login"
            class="com.ramsis.actions.LoginAction" method="execute">
           
            <result name="success" type="tiles">/welcome.tiles</result>
              <result name="error">/Login.jsp</result>
            <result name="input">/Login.jsp</result>
        </action>
      <!--  <action name="customer"
            class="com.ramsis.actions.CustomerAction">
    <interceptor-ref name="loginStack" />
            <result name="success" type="tiles">/customer.success.tiles</result>
            <result name="input" type="tiles">/customer.tiles</result>
        </action> -->
        <action name="customer-form">
            <interceptor-ref name="loginStack" />  
            <result name="success" type="tiles">/customer.tiles</result>
        </action>
        <!--   logout action  -->
<action name="logOut" class="com.ramsis.actions.LoginAction" method="logOut">
       <interceptor-ref name="clear-cache" />
       <interceptor-ref name="loginStack" />
<result name="success">/Login.jsp</result>
</action>

      <action name="customer" class="com.ramsis.hibernate.contact.util.ClientForSave" method="addCustomer">
    <interceptor-ref name="loginStack" />
<result name="success" type="tiles">/customer.success.tiles</result>
<result name="input" type="tiles">/customer.tiles</result>
</action>

<action name="ShowTest" class="com.ramsis.hibernate.contact.util.ShowData">
    <interceptor-ref name="loginStack" />
    <result name="error">/error.jsp</result>
<result type="tiles" name="success" >/ShowTest.success.tiles</result>
</action>

<action name="DeleteData" class="com.ramsis.hibernate.contact.util.DeleteData">
    <interceptor-ref name="loginStack" />
   <result name="error">/error.jsp</result>
<result type="tiles" name="success" >/DeleteData.success.tiles</result>
</action>

<action name="DeleteDataClick" class="">
    <interceptor-ref name="loginStack" />
   <result name="error">/error.jsp</result>
<result type="tiles" name="success" >/DeleteDataClick.success.tiles</result>
</action>

<action name="BeforeUpdate" class="com.ramsis.hibernate.contact.util.UpdateData" method="click">
    <interceptor-ref name="loginStack" />
    <result name="error">/error.jsp</result>
<result type="tiles" name="success" >/BeforeUpdate.success.tiles</result>
</action>

<!-- <action name="BeforeUpdate" class="com.ramsis.hibernate.contact.util.UpdateData" method="execute">
    <interceptor-ref name="loginStack" />
    <result name="error">/error.jsp</result>
<result type="tiles" name="success" >/BeforeUpdate.success.tiles</result>
</action> -->

<action name="UpdateData" class="com.ramsis.hibernate.contact.util.UpdateData" method="execute">
    <interceptor-ref name="loginStack" />
    <result type="tiles" name="error">/BeforeUpdate.error.tiles</result>
<result type="tiles" name="success" >/Update.success.tiles</result>
</action>

         <action name="Updated" class="com.ramsis.hibernate.contact.util.Update" method="execute">
    <interceptor-ref name="loginStack" />
    <result name="error">/error.jsp</result>
<result type="tiles" name="success" >/Updated.success.tiles</result>
</action>

    </package>
</struts>

--------------------------------------- tiles.xml -----------------------------------------

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE tiles-definitions PUBLIC
       "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
       "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">

<tiles-definitions>

<definition name="baseLayout" template="/BaseLayout.jsp">
<put-attribute name="title" value="" />
<put-attribute name="header" value="/Header.jsp" />
<put-attribute name="menu" value="/Menu.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/Footer.jsp" />
</definition>

<definition name="/welcome.tiles" extends="baseLayout">
<put-attribute name="title" value="Welcome" />
<put-attribute name="body" value="/Welcome.jsp" />
</definition>

<definition name="/customer.tiles" extends="baseLayout">
<put-attribute name="title" value="Customer Form" />
<put-attribute name="body" value="/Customer.jsp" />
</definition>
<definition name="/customer.success.tiles" extends="baseLayout">
<put-attribute name="title" value="Customer Added" />
<put-attribute name="body" value="/SuccessCustomer.jsp" />
</definition>
<definition name="/ShowTest.success.tiles" extends="baseLayout">
<put-attribute name="title" value="ShowTest" />
<put-attribute name="body" value="/ShowTest.jsp" />
</definition>
    <definition name="/DeleteData.success.tiles" extends="baseLayout">
<put-attribute name="title" value="DeleteData" />
<put-attribute name="body" value="/DeleteData.jsp" />
</definition>
<definition name="/DeleteDataClick.success.tiles" extends="baseLayout">
<put-attribute name="title" value="DeleteDataClick" />
<put-attribute name="body" value="/DeleteData.jsp" />
</definition>
<definition name="/BeforeUpdate.success.tiles" extends="baseLayout">
<put-attribute name="title" value="BeforeUpdate" />
<put-attribute name="body" value="/BeforeUpdate.jsp" />
</definition>
<definition name="/BeforeUpdate.error.tiles" extends="baseLayout">
<put-attribute name="title" value="UpdateError" />
<put-attribute name="body" value="/BeforeUpdate.jsp" />
</definition>
<definition name="/Update.success.tiles" extends="baseLayout">
<put-attribute name="title" value="Update" />
<put-attribute name="body" value="/Update.jsp" />
</definition>
<definition name="/Updated.success.tiles" extends="baseLayout">
<put-attribute name="title" value="Updated" />
<put-attribute name="body" value="/BeforeUpdate.jsp" />
</definition>

</tiles-definitions>

----------------------------------------- web.xml -----------------------------

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

<display-name>Struts2 Application</display-name>
<listener>
<listener-class>
org.apache.struts2.tiles.StrutsTilesListener
</listener-class>
</listener>
<context-param>
<param-name>tilesDefinitions</param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</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>

---------------------------------------- BaseLayout.jsp ----------------------------------

<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles"%>
<!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=UTF-8">
<title><tiles:insertAttribute name="title" ignore="true" /></title>
</head>
<body>
<table border="1" cellpadding="2" cellspacing="2" align="center">
<tr>
<td height="30" colspan="3"><tiles:insertAttribute name="header" />
</td>
</tr>
<tr>
<td height="300" width="100"><tiles:insertAttribute name="menu" /></td>
<td width="350"><tiles:insertAttribute name="body" /></td>
<td height="300"><tiles:insertAttribute name="menu" /></td>
</tr>
<tr>
<td height="30" colspan="3"><tiles:insertAttribute name="footer" />
</td>
</tr>
</table>
</body>
</html>

--------------------------------- BeforeUpdate.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">
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Check Data which you have to update.</title>
</head>
<body>
<h2>Update your data.</h2>
<p><s:property value="msg" /></p>

<s:form action="UpdateData.action" method="Post" >
    <s:textfield  name="name"  size="20" label="Name" />
    <s:textfield  name="telephone" size="20" label="Telephone" />
    <s:submit method="execute" key="Submit" />
</s:form>
</body>
</html>

------------------------------- body.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>
<p> sample body content.</p>
</body>
</html>

----------------------------- Customer.jsp ----------------------------------------

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Customer Form - Struts2 Demo </title>
</head>

<body>
<h2>Customer Form</h2>

<s:form action="customer.action" method="post" validate="true">
<s:textfield name="name" key="name" size="20" label="Name" />
<s:textfield name="age" key="age" size="20" label="Age" />
<s:textfield name="email" key="email" size="20" label=" Email" />
<s:textfield name="telephone" key="telephone" size="20" label="Telephome" />
<s:submit method="addCustomer" key="submit" align="center" />
</s:form>
</body>
</html>

--------------------------- DeleteData.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">
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Delete Data</h2>
<s:property value="msg" />
<s:form action="DeleteData.action" method="post" >
 
  <s:textfield  name="telephone" size="20" label="Enter Telephone Number " />
  <s:submit method="execute" key="Submit" />
 
</s:form>

</body>
</html>

------------------------------- error.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>
<h2>Error has been occur. Try again. </h2>
</body>
</html>

------------------------------------ Footer.jsp -------------------------

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
Copyright &copy; ramsis-code.blogspot.in

------------------------------------ Header.jsp -------------------------

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<center><h2>Ramsis-Code</h2></center>
<table width="100%" border="0">
<tr>
<td>
Hello <s:property value="%{#session['loginId']}"/>&nbsp;|&nbsp;<a href="<s:url action="logOut"/>">LogOut</a>
&nbsp;|&nbsp;<a href="<s:url action="logOut"/>">Log In</a>
</td>
</tr>
</table>

--------------------------------- Login.jsp ----------------------------


<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Struts 2 - Login Application | ViralPatel.net</title>
</head>
<body>
<h2>Struts 2 - Login Application</h2>
<s:actionmessage />
<s:actionerror />
<s:form action="login.action" method="post" namespace="LoginUser">
<s:textfield name="username" key="label.username" size="20" label="User Name" />
<s:password name="pass" key="label.password" size="20" label="Password" />
<s:submit method="execute" value="Submit" key="label.login" align="center"  />
</s:form>
</body>
</html>


--------------------------------- Logout.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="Refresh" CONTENT="0;URL=Test.action">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <p> Logout Successfully...</p>
</body>
</html>

------------------------------- Menu.jsp --------------------------

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<s:a href="customer-form">Submit Form</s:a><br/>
<s:a href="ShowTest">Show Data</s:a><br/>
<s:a href="DeleteDataClick">Delete Data</s:a><br/>
<s:a href="BeforeUpdate">Update Data</s:a>

----------------------------- ShowTest.jsp ------------------------

<%@ taglib prefix="s" uri="/struts-tags" %>
 
<html>
<head>
</head>
 
<body>
<!--  <h1>Struts 2 Iterator tag example</h1>-->
 
<h3>Show Records</h3>
<table border="1" style="border-collapse:collapse;">
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Telephone</th>
<s:iterator value="comboMeals" status="comboMealsStatus" >
<tr>
  <!--  <s:if test="comboMealsStatus.odd == true" />  -->
  <td style="background: #CCCCCC"> <s:property value="name" /></td>
  <td> <s:property value="age" /></td>
  <td> <s:property value="email" /></td>
  <td> <s:property value="telephone" /></td>
</tr>  
</s:iterator>
</table>

</body>
</html>

-------------------------- SuccessCustomer.jsp -----------------------

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Customer Page - Struts2 Demo | ViralPatel.net</title>
</head>

<body>
<h2>Customer Added Successfully.</h2>
</body>
</html>

--------------------------- Update.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">
<%@ taglib prefix="s" uri="/struts-tags" %>

<html>
<head>
<title>Check Data which you have to update.</title>
</head>
<body>
<h2>Update your data.</h2>
<p><s:property value="msg" /></p>
<p><s:set var="strmsg" value="msg"/></p>
<s:form action="Updated.action" method="Post" >
    <s:iterator value="list" var="list">
    <s:hidden name="id" value="%{#list.id}" />
    <s:textfield  name="name" value="%{#list.name}" size="20" label="Name" />
    <s:textfield  name="age" value="%{#list.age}" size="20" label="Age " />
    <s:textfield  name="email" value="%{#list.email}"  size="20" label="Email" />
    <s:textfield  name="telephone" value="%{#list.telephone}"  size="20" label="Telephone" />
    </s:iterator>
    <s:submit method="execute" key="Submit" />
     
</s:form>
</body>
</html>

--------------------------- Welcome.jsp ----------------------------------

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Welcome</title>
</head>

<body>
<h2>Howdy, <s:property value="username" />...!</h2>

</body>
</html>

Download Code