Archive for the ‘JavaEE’ Category

NetBeans Database Explorer

May 26, 2011

  1. Are you working on sql queries often?
  2. Are you executing queries with different database servers (MySQL, PostgreSQL, Oracle)?
  3. Are you working on an application which should be tested on multiple databases?

Answer to all the 3 questions is : NetBeans Database Explorer.

Yes, NetBeans Database Explorer is the correct choice for you. Database Explorer is a simple database administrative tool which allows you to manage the live database connections, browse and visualize the database structures represented in the organized hierarchical form.
It allows you to perform common operations on database structures. This includes

  • execute sql statements and queries.
  • create, modify & delete tables
  • add, delete columns, indexes.
  • populating tables data
  • view tables data.
  • grabbing and recreating table structures.

Database Explorer
This blog illustrates how to set up a connection with MySQL database from the NetBeans IDE. Once connected, you can start use the SQL editor to execute queries, view the table data.

Go to Window -> Services(Short cut : Ctrl+5) –  This will open a Services window, select Databases

NetBeans Services Window - Database Explorer

Select New Connection by right click the Databases.

DB New Connection

Database Driver Selection
The IDE comes bundled with drivers for MySQL, PostgreSQL, Oracle database servers. Select an appropriate JDBC drivers from the Driver combo box. NetBeans provides an option New Driver, with this you can import other database JDBC drivers and start interact with them.

New Connection Wizard

Connection Wizard
Driver Name – JDBC Driver used to connect to the database server.
Host – Machine where the database server is running. It can be a remote machine also.
Port – Port number that the db server listens on.
Database – Name of the database you want to connect.(Optional)
Username/Password – Authentication credentials to connect & access the database.

Connection Customize Wizard

Exploring Tables
Once the database connection was succeeded, browse and explore the tables/views present in the database. You can select a particular table and execute in the SQL editor by clicking View Data

Table View Data

Browse and select required columns of the table and view the data.

View Selected Column Data

Query Output Window
This will display the executed query results. From here, you can Insert or Delete Rows.

Query Output Window

SQL Editor
The advantage of this SQL Editor, you can execute multiple queries in a single shot and every query results are shown in tabbed views.

SQL Editor

Multiple SQL Command Editors
With this you can connect and execute queries from different databases in different SQL command editors. Select a required connection db from the Connection combo box to execute the query.

Multiple SQL Command Tab

SQL History
It’s very useful to execute some of the queries which was written previously.

SQL History

Overall, It is a good tool to manage the databases easily. Henceforth no need to go with separate tool for SQL editor, lets use NetBeans as both Java IDE as well as SQL IDE.

This document completely demonstrates with latest version(7.0) 0f  NetBeans. You can download it from here.



Advertisements

Hibernate Basics & Simple Example

April 13, 2011

Hibernate is an open source Object Relational Mapping framework used to transform from object oriented programming to relational databases.

It supports object oriented concepts Association, Polymorphism, Inheritance & Composition through persistent classes. Also Hibernate facilitates to write queries in variant forms,  HQL(Hibernate Query Language), Native SQL, or Criteria API.

The following question may raise while learning about Hibernate.

What’s the difference between JDBC & Hibernate?

JDBC API’s are easy to use for small projects. But Hibernate framework is well suited for enterprise level applications and acts as mediator between object & relational approaches.

Hibernate Architecture
Hibernate performs the following operations;

  • opens a database connection
  • converts HQL statements to database specific statements
  • execute it  & receive data from the database
  • result set being mapped to equivalent java objects to be processed by application.
Hibernate Architecture

Hibernate Architecture

This blog gives you a basic idea about how to connect and use Hibernate with a database.

Simple Application : BookApps

BookApps is an example application. This application main function is to add, update, delete, retrieve books from the database.

Note : This application uses a PostgreSQL database, therefore run an instance of PostgreSQL. Go through this blog, to know the basics of PostgreSQL. Also download and run the same.

Click here to download the hibernate & unzip the file hibernate-distribution-3.6.0.Final-dist.zip

Hibernate configuration file : hibernate.cfg.xml
This will have all the information to connect Hibernate to a database. In this example, PostgreSQL database is used.
Note : Hibernate configurations can also be done through hibernate.properties file.

 <!--<span class="hiddenSpellError" pre=""-->DOCTYPE hibernate-configuration PUBLIC
 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 <a href="http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"</a>>

 <hibernate-configuration>
 <session-factory>
 <!-- Database connection settings -->
 jdbc:postgresql://localhost:5432/postgres
 <property name="connection.driver_class">org.postgresql.Driver</property>
 <property name="connection.username">postgres</property>
 <property name="connection.password">******</property>
 <property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>

 <!-- SQL dialect - generate SQL for a particular database -->
 <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>

 <!-- Echo all executed SQL statements -->
 <property name="show_sql">true</property>

 <!-- Enable Hibernate's automatic session context management -->
 <property name="current_session_context_class">thread</property>
<!-- Mapping resource configuration files -->
 <mapping resource="src/com/bookstore/bookapp.hbm.xml"/>
 </session-factory>
 </hibernate-configuration>
 

Property to drop and re-create the database schema on startup

<property name="hbm2ddl.auto">create</property>

By adding this property, hibernate will create tables for you. This will be executed only once ie) after first run comment this code. because every time tables will get dropped.

Hibernate mapping file : bookapp.hbm.xml
For all objects to be persisted in the database,  Hibernate needs this XML file. The mapping file tells Hibernate how to load and store objects, what table in the database it has to access and what columns in the table should use.
This file should be saved with .hbm.xml file extension.

 <?xml version="1.0"?>
 <!--<span class="hiddenSpellError" pre=""-->DOCTYPE hibernate-mapping PUBLIC
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 <a href="http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"</a>>

 <hibernate-mapping package="com.bookstore">
 BookDetails" table="BookStore">
 BookId">
 <generator/>
 </id>
 bookName" type="string" column="BookName"/>
 authorName" type="string" column="AuthorName"/>
 bookCost" type="int" column="BookCost"/>
 </class>
 </hibernate-mapping>
 

Persistent class : BookDetails.java
The persistent class works in the form of POJO(Plain Old Java Object) model. It’s a java bean class having getter and setter methods to access the properties of an app.

 package com.bookstore;

 public class BookDetails{
 private int bookId;
 private String bookName;
 private String authorName;
 private int bookCost;

 BookDetails(){
 }

 public int getBookId(){
 return bookId;
 }
 public void setBookId(int bookId){
 this.bookId = bookId;
 }

 public String getBookName(){
 return bookName;
 }
 public void setBookName(String bookName){
 this.bookName = bookName;
 }

 public String getAuthorName(){
 return authorName;
 }
 public void setAuthorName(String authorName){
 this.authorName = authorName;
 }

 public int getBookCost(){
 return bookCost;
 }
 public void setBookCost(int bookCost){
 this.bookCost = bookCost;
 }

 public String toString(){
 StringBuffer sb = new StringBuffer();
 sb.append("BookName : ").append(bookName);
 sb.append(" ,AuthorName : ").append(authorName);
 sb.append(" , BookCost : ").append(bookCost);
 return sb.toString();
 }
 }
 

Hibernate communication with database : HibernateUtil.java
Load the hibernate configuration file and mapping files automatically, create a session factory from the configured object, create a session to execute the HQL query and get the result set of java objects.

 package com.bookstore;

 import org.hibernate.SessionFactory;
 import org.hibernate.cfg.Configuration;

 public class HibernateUtil {

 private static final SessionFactory sessionFactory;

 static {
 try {
 // Create the SessionFactory from hibernate.cfg.xml
 sessionFactory = new Configuration().configure().buildSessionFactory();
 } catch (Throwable ex) {
 // Make sure you log the exception, as it might be swallowed
 System.err.println("Initial SessionFactory creation failed." + ex);
 throw new ExceptionInInitializerError(ex);
 }
 }

 public static SessionFactory getSessionFactory() {
 return sessionFactory;
 }

 }

Application class : BookApp.java
A simple application class which performs CRUD operations in the database through HQL, Persistent Objects, Native SQL & Criteria API.

package com.bookstore;

 import java.util.List;
 import java.util.Iterator;
 import org.hibernate.Session;
 import org.hibernate.Query;
 import org.hibernate.Criteria;
 import org.hibernate.criterion.Restrictions;
 public class BookApp{
 public static void main(String args[]){
 BookMethods bm = new BookMethods();

 //Adding books
 bm.addBook("Professional Hibernate","Eric Pugh, Gradecki", 350);
 bm.addBook("Hibernate in Action","Christian Bauer, Gavin King", 499);
 bm.addBook("Java Persistence With Hibernate","Bauer, Gavin King", 423);
 bm.addBook("Begining Hibernate","Dave Minter, Jeff Linwood", 1500);

 //Listing added books
 bm.listBooks();

 //Getting book details for a particular book name.
 bm.getBookDetails("Hibernate in Action");

 //To see no. of books
 bm.countBook();

 //Update particular book cost
 bm.updateBook("Begining Hibernate",1000);

 //Listing available books
 bm.listBooks();

 //Deleting a book
 bm.deleteBook("Java Persistence With Hibernate");

 //Listing available books After executing delete
 bm.listBooks();
 }
 }

 class BookMethods{
 //Using persistent objects to store data into the database.
 public void addBook(String bookName, String authorName, int bookCost){
 Session session = HibernateUtil.getSessionFactory().getCurrentSession();
 session.beginTransaction();
 BookDetails bd = new BookDetails();
 bd.setBookName(bookName);
 bd.setAuthorName(authorName);
 bd.setBookCost(bookCost);
 session.save(bd);
 session.getTransaction().commit();
 }

 //Using persistence object to delete a row from the database.
 public void deleteBook(String bookName){
 Session session = HibernateUtil.getSessionFactory().getCurrentSession();
 session.beginTransaction();
 List list = session.createQuery("from BookDetails where bookName='"+bookName+"'").list();
 Iterator itr = list.iterator();
 while(itr.hasNext()){
 BookDetails bd = (BookDetails)itr.next();
 System.out.println("delete : "+bd);
 session.delete(bd);
 }
 session.getTransaction().commit();
 }

 //Using Criteria API to update the book cost
 public void updateBook(String bookName, int bookCost){
 Session session = HibernateUtil.getSessionFactory().getCurrentSession();
 session.beginTransaction();
 Criteria cri = session.createCriteria(BookDetails.class);
 cri = cri.add(Restrictions.eq("bookName", bookName));
 List list = cri.list();
 BookDetails bd = (BookDetails)list.iterator().next();
 bd.setBookCost(bookCost);
 session.update(bd);
 session.getTransaction().commit();
 }

 //Using HQL - Hibernate Query Language
 public void getBookDetails(String bookName){
 Session session = HibernateUtil.getSessionFactory().getCurrentSession();
 session.beginTransaction();
 Query q = session.createQuery("from BookDetails where bookName=:bn");
 q.setString("bn", bookName);
 List list = q.list();
 System.out.println("Getting Book Details using HQL. \n"+list);

 //The above query can also be achieved with Criteria & Restrictions API.
 Criteria cri = session.createCriteria(BookDetails.class);
 cri = cri.add(Restrictions.eq("bookName", bookName));
 list = cri.list();
 System.out.println("Getting Book Details using Criteria API. \n"+list);

 session.getTransaction().commit();
 }

 //Aggregate function.
 public void countBook(){
 Session session = HibernateUtil.getSessionFactory().getCurrentSession();
 session.beginTransaction();
 List list = session.createQuery("select count(*) from BookDetails").list();
 System.out.println("Aggregate function count \n"+list);
 session.getTransaction().commit();
 }

 //Native SQL Query
 public void listBooks(){
 Session session = HibernateUtil.getSessionFactory().getCurrentSession();
 session.beginTransaction();
 List list = session.createSQLQuery("select * from BookStore").addEntity(BookDetails.class).list();
 Iterator itr = list.iterator();
 while(itr.hasNext()){
 BookDetails bd = (BookDetails)itr.next();
 System.out.println(bd);
 }
 session.getTransaction().commit();

 }
 }

Compile & Run the simple application : BookApp.

Setting classpath
Following jars are required to compile and run the code. Copy the below code and save it in a file called classpath.bat & run this batch file.

set HIBERNATE_HOME=C:\Hibernate\hibernate-distribution-3.6.0.Final
set CLASSPATH=%HIBERNATE_HOME%\hibernate3.jar;%HIBERNATE_HOME%\lib\required\dom4j-1.6.1.jar;%HIBERNATE_HOME%\lib\required\slf4j-api-1.6.1.jar;%HIBERNATE_HOME%\lib\jpa\hibernate-jpa-2.0-api-1.0.0.Final.jar;%HIBERNATE_HOME%\lib\required\commons-collections-3.1.jar;%HIBERNATE_HOME%\lib\required\javassist-3.12.0.GA.jar;%HIBERNATE_HOME%\lib\required\jta-1.1.jar;%HIBERNATE_HOME%\lib\required\antlr-2.7.6.jar;.;C:\PostgreSQL\postgresql-9.0-801.jdbc3.jar

Compile all the java files

C:\Hibernate\hibernate-distribution-3.6.0.Final\example\booksapp>javac -d . src\com\bookstore\*.java

Run the app

C:\Hibernate\hibernate-distribution-3.6.0.Final\example\booksapp>java com.bookstore.BookApp

Output

SLF4J: Failed to load class “org.slf4j.impl.StaticLoggerBinder”.
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

Hibernate: select max(BookId) from BookStore
Hibernate: insert into BookStore (BookName, AuthorName, BookCost, BookId) values (?, ?, ?, ?)
Hibernate: insert into BookStore (BookName, AuthorName, BookCost, BookId) values (?, ?, ?, ?)
Hibernate: insert into BookStore (BookName, AuthorName, BookCost, BookId) values (?, ?, ?, ?)
Hibernate: insert into BookStore (BookName, AuthorName, BookCost, BookId) values (?, ?, ?, ?)

Hibernate: select * from BookStore

BookName : Professional Hibernate ,AuthorName : Eric Pugh, Gradecki , BookCost : 350
BookName : Hibernate in Action ,AuthorName : Christian Bauer, Gavin King , BookCost : 499
BookName : Java Persistence With Hibernate ,AuthorName : Bauer, Gavin King , BookCost : 423
BookName : Begining Hibernate ,AuthorName : Dave Minter, Jeff Linwood , BookCost : 1500

Hibernate: select bookdetail0_.BookId as BookId0_, bookdetail0_.BookName as BookName0_, bookdetail0_.AuthorName as AuthorName0_, bookdetail0_.BookCost as BookCost0_ from BookStore bookdetail0_ where bookdetail0_.BookName=?
Getting Book Details using HQL.
[BookName : Hibernate in Action ,AuthorName : Christian Bauer, Gavin King , BookCost : 499]

Hibernate: select this_.BookId as BookId0_0_, this_.BookName as BookName0_0_, this_.AuthorName as AuthorName0_0_, this_.BookCost as BookCost0_0_ from BookStore this_ where this_.BookName=?
Getting Book Details using Criteria API.
[BookName : Hibernate in Action ,AuthorName : Christian Bauer, Gavin King , BookCost : 499]

Hibernate: select count(*) as col_0_0_ from BookStore bookdetail0_
Aggregate function count
[4]

Hibernate: select this_.BookId as BookId0_0_, this_.BookName as BookName0_0_, this_.AuthorName as AuthorName0_0_, this_.BookCost as BookCost0_0_ from BookStore this_ where this_.BookName=?
Hibernate: update BookStore set BookName=?, AuthorName=?, BookCost=? where BookId=?

Hibernate: select * from BookStore
BookName : Professional Hibernate ,AuthorName : Eric Pugh, Gradecki , BookCost : 350
BookName : Hibernate in Action ,AuthorName : Christian Bauer, Gavin King , BookCost : 499
BookName : Java Persistence With Hibernate ,AuthorName : Bauer, Gavin King , BookCost : 423
BookName : Begining Hibernate ,AuthorName : Dave Minter, Jeff Linwood , BookCost : 1000

Hibernate: select bookdetail0_.BookId as BookId0_, bookdetail0_.BookName as BookName0_, bookdetail0_.AuthorName as AuthorName0_, bookdetail0_.BookCost as BookCost0_ from BookStore bookdetail0_ where bookdetail0_.BookName=’Java Persistence With Hibernate’
delete : BookName : Java Persistence With Hibernate ,AuthorName : Bauer, Gavin King , BookCost : 423
Hibernate: delete from BookStore where BookId=?

Hibernate: select * from BookStore
BookName : Professional Hibernate ,AuthorName : Eric Pugh, Gradecki , BookCost : 350
BookName : Hibernate in Action ,AuthorName : Christian Bauer, Gavin King , BookCost : 499
BookName : Begining Hibernate ,AuthorName : Dave Minter, Jeff Linwood , BookCost : 1000

C:\Hibernate\hibernate-distribution-3.6.0.Final\example\booksapp>

Click here to view/download the source of book apps.


Struts Example

December 7, 2010

Let’s see, how to develop a simple web application using Struts. Prior to this, want to learn about Struts basics go through these blogs Struts Basics & Struts Dispatch Action.
Before starting the application, download Tomcat-6.0.29.zip & Struts-1.3.10.zip

Follow the basic steps to configure struts in tomcat.

  • Unzip the tomcat zip file, you can get the folder apache-tomcat-6.0.29
  • Unzip the struts zip file, from that copy all jars from struts-1.3.10\lib directory to apache-tomcat-6.0.29\lib directory.
  • Copy the struts-1.3.10\src\taglib\src\main\resources\META-INF\tld\struts-html.tld file and place it under apache-tomcat-6.0.29\webapps\examples\WEB-INF directory.

Tomcat zip has the sample examples of jsp/servlet, which has been present under webapps/examples directory. We can use the same for developing our simple struts web application(Books Store).

In this app you are able to view the complete details of available books by accessing the url http://localhost:8080/examples/showbooks.do. From this page, you can do the basic operations like Add/Edit/Delete book.

Following steps are tell you how to implement this web app, what are the settings required to configure and where to place the action classes & jsp files.

web.xml or Deployment Descriptor.
We have to configure about ActionServlet in web application. This can be done by adding the following servlet definition to the apache-tomcat-6.0.29\webapps\examples\WEB-INF\web.xml file.

 <servlet>
 <servlet-name>action</servlet-name>
 <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
 <init-param>
 <param-name>config</param-name>
 <param-value>/WEB-INF/struts-config.xml</param-value>
 </init-param>
 <init-param>
 <param-name>validate</param-name>
 <param-value>true</param-value>
 </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>
 

Servlet Mappings tells when the action should be executed.

 <servlet-mapping>
 <servlet-name>action</servlet-name>
 <url-pattern>*.do</url-pattern>
 </servlet-mapping>
 

To use HTML tag lib, you must add the following tag library entries into web.xml file.

 <taglib>
 <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>
 <taglib-location>/WEB-INF/struts-html.tld</taglib-location>
 </taglib>
 

struts-config.xml
This file is used to configure the struts framework details of a web application contains form-bean, action-mappings definitions.Add this file under apache-tomcat-6.0.29\webapps\examples\WEB-INF directory.

 <?xml version="1.0" encoding="ISO-8859-1" ?>
 <!DOCTYPE struts-config PUBLIC
 "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
 "http://struts.apache.org/dtds/struts-config_1_3.dtd" >

 <struts-config>
 <!-- Form Bean Definitions -->
 <form-beans>
 <form-bean name="BookForm" type="com.books.BookForm"/>
 </form-beans>

 <!--  Action Mapping Definitions  -->
 <action-mappings>
 <action path="/showbooks"
 type="com.books.ShowBooks"
 validate="false"
 scope="session">
 <forward name="success" path="/jsp/books/books.jsp"/>
 </action>

 <!-- Example of Struts Dispatch Action : has the extra attribute parameter-->
 <action path="/bookaction"
 type="com.books.BookActions"
 parameter="actionMethod"
 name="BookForm"
 validate="false"
 scope="session">
 <forward name="addBook" path="/jsp/books/addbook.jsp"/>
 <forward name="editBook" path="/jsp/books/editbook.jsp"/>
 <forward name="deleteBook" path="/jsp/books/deletebook.jsp"/>
 </action>
 </action-mappings>
 </struts-config>
 

ShowBooks.java
Action class used to show the book details page. In this example, I used class objects to store the book details you can use database to store the content of your app. This class been invoked when you access this url http://localhost:8080/examples/showbooks.do from the web browser.

 package com.books;

 import org.apache.struts.action.ActionForm;
 import org.apache.struts.action.ActionMapping;
 import org.apache.struts.action.ActionForward;
 import org.apache.struts.action.Action;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 public class ShowBooks extends Action
 {
 public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Show Books List");
 Books b = Books.getInstance();
 request.setAttribute("booksList", b.getBookList());
 return mapping.findForward("success");
 }
 }
 

Books.java
Class used to store the book details i.e., app data is persisted in jvm memory, this will get lost once you restarted the tomcat server. So you can use databases to store your application data.

 package com.books;

 import java.util.Map;
 import java.util.HashMap;
 import java.util.List;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.Set;

 class Books {

 int bookIdCount = 1000;
 Map<Integer, StoreBook> bookMap = new HashMap<Integer, StoreBook>();
 private static Books books = null;

 private Books() {
 }

 public static Books getInstance() {
 if (books == null) {
 books = new Books();
 }
 return books;
 }

 public void storeBook(String bookName, String authorName, int bookCost) {
 StoreBook sb = new StoreBook();
 bookIdCount++;
 sb.addBook(bookIdCount, bookName, authorName, bookCost);
 bookMap.put(bookIdCount, sb);
 }

 public void updateBook(int bookId, String bookName, String authorName, int bookCost) {
 StoreBook sb = bookMap.get(bookId);
 sb.updateBook(bookName, authorName, bookCost);
 }

 public Map searchBook(int bookId) {
 return bookMap.get(bookId).getBooks();
 }

 public void deleteBook(int bookId) {
 bookMap.remove(bookId);
 }
 // Inner Class used to persist the app data ie) book details.
 class StoreBook {

 private String bookName;
 private String authorName;
 private int bookCost;
 private int bookId;

 StoreBook() {
 }

 public void addBook(int bookId, String bookName, String authorName, int bookCost) {
 this.bookId = bookId;
 this.bookName = bookName;
 this.authorName = authorName;
 this.bookCost = bookCost;
 }

 public void updateBook(String bookName, String authorName, int bookCost) {
 this.bookName = bookName;
 this.authorName = authorName;
 this.bookCost = bookCost;
 }

 public Map getBooks() {
 Map books = new HashMap();
 books.put("BookId", this.bookId);
 books.put("BookName", this.bookName);
 books.put("AuthorName", this.authorName);
 books.put("BookCost", this.bookCost);
 return books;
 }
 }

 public List getBookList() {
 List booksList = new ArrayList();
 Set s = bookMap.keySet();
 Iterator itr = s.iterator();
 while (itr.hasNext()) {
 booksList.add(bookMap.get((Integer)itr.next()).getBooks());
 }
 return booksList;
 }
 }
 


BookForm.java

Form bean class has the getter & setter methods of corresponding form input elements. With this, you can get and set the value of form elements in the Action class.

 package com.books;

 import org.apache.struts.action.ActionForm;

 public class BookForm extends ActionForm {

 private String bookName;
 private String authorName;
 private int bookCost;
 private int bookId;

 public BookForm() {
 super();
 }

 public String getBookName() {
 return bookName;
 }
 public void setBookName(String bookName) {
 this.bookName = bookName;
 }

 public String getAuthorName() {
 return authorName;
 }
 public void setAuthorName(String authorName) {
 this.authorName = authorName;
 }

 public int getBookCost() {
 return bookCost;
 }
 public void setBookCost(int bookCost) {
 this.bookCost = bookCost;
 }

 public int getBookId() {
 return bookId;
 }
 public void setBookId(int bookId) {
 this.bookId = bookId;
 }
 }
 

BookActions.java
It’s an example of struts DispatchAction class, each and every action/function of book has equivalent methods to process it. This class been invoked when you access these url’s from the web browser.
Add Book : http://localhost:8080/examples/bookaction.do?actionMethod=AddBook
Edit Book : http://localhost:8080/examples/bookaction.do?actionMethod=EditBook&bookId=1008
Delete Book : http://localhost:8080/examples/bookaction.do?actionMethod=DeleteBook

 package com.books;

 import org.apache.struts.action.ActionForm;
 import org.apache.struts.action.ActionMapping;
 import org.apache.struts.action.ActionForward;
 import org.apache.struts.actions.DispatchAction;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;

 import java.util.Map;

 public class BookActions extends DispatchAction
 {
 public ActionForward AddBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Add Book Page");
 return mapping.findForward("addBook");
 }

 public ActionForward EditBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Edit Book Page");
 int bookId = Integer.parseInt(request.getParameter("bookId"));

 Books b = Books.getInstance();
 Map bookDet = b.searchBook(bookId);

 //Used form bean class methods to fill the form input elements with selected book values.
 BookForm bf = (BookForm)form;
 bf.setBookName(bookDet.get("BookName").toString());
 bf.setAuthorName(bookDet.get("AuthorName").toString());
 bf.setBookCost((Integer)bookDet.get("BookCost"));
 bf.setBookId((Integer)bookDet.get("BookId"));
 return mapping.findForward("editBook");
 }

 public ActionForward SaveBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Save Book");
 //Used form bean class methods to get the value of form input elements.
 BookForm bf = (BookForm)form;
 String bookName = bf.getBookName();
 String authorName = bf.getAuthorName();
 int bookCost = bf.getBookCost();

 Books b = Books.getInstance();
 b.storeBook(bookName, authorName, bookCost);
 return new ActionForward("/showbooks.do", true);
 }

 public ActionForward UpdateBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Update Book");
 BookForm bf = (BookForm)form;
 String bookName = bf.getBookName();
 String authorName = bf.getAuthorName();
 int bookCost = bf.getBookCost();
 int bookId = bf.getBookId();

 Books b = Books.getInstance();
 b.updateBook(bookId, bookName, authorName, bookCost);
 return new ActionForward("/showbooks.do", true);
 }

 public ActionForward DeleteBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Delete Book");
 int bookId = Integer.parseInt(request.getParameter("bookId"));
 Books b = Books.getInstance();
 b.deleteBook(bookId);
 return new ActionForward("/showbooks.do", true);
 }
 }
 

books.jsp
File used to show the available books in the app store. This page is being forwarded from the ShowBooks action class.

 <%@ page import="java.util.HashMap"%>
 <%@ page import="java.util.Map"%>
 <%@ page import="java.util.List"%>
 <%@ page import="java.util.ArrayList"%>
 <%@ page import="java.util.Iterator"%>
 <html>
 <body>
 <p><b>Struts Example - Simple Book Store App</b></p>
 <b>Available Books</b>
 <form name="bookform" action="/examples/bookaction.do">
 <table style="background-color:#82CAFA;">
 <tr style="color:yellow;"><th>&nbsp;</th><th>Book Name</th><th>Author Name</th><th>Book Cost</th></tr>
 <%List bookList = (ArrayList)request.getAttribute("booksList");
 Iterator itr = bookList.iterator();
 while(itr.hasNext()){
 Map map = (HashMap)itr.next();
 %>
 <tr><td><input type="radio" name="bookId" value='<%=map.get("BookId")%>' onclick="javascript:enableEditDelete();"></td>
 <td><%=map.get("BookName")%></td><td><%=map.get("AuthorName")%></td><td><%=map.get("BookCost")%></td>
 </tr>
 <%}%>
 </table>
 </p>
 <p>
 <table><tr>
 <td><input type="submit" name="actionMethod" value="AddBook" /></td>
 <td><input type="submit" name="actionMethod" id="editbutton" value="EditBook" disabled="true" /></td>
 <td><input type="submit" name="actionMethod" id="deletebutton" value="DeleteBook" disabled="true" onclick="return checkDelete();" /></td>
 </tr></table>
 </form>
 </p>
 <script>
 function checkDelete(){
 return confirm("Are u sure to delete this book..?");
 }
 function enableEditDelete(){
 document.getElementById('editbutton').disabled=false;
 document.getElementById('deletebutton').disabled=false;
 }
 </script>
 </body>
 </html>
 

addbook.jsp
Web page used to add a new book to the app store.

 <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
 <html>
 <body>
 <p><b>Struts Example - Simple Book Store App</b></p>
 <b>Add Book</b>
 <html:form>
 <table style="background-color:#82CAFA;">
 <tr><td>Book Name</td><td><html:text property="bookName" value=""/></td></tr>
 <tr><td>Author Name</td><td><html:text property="authorName" value=""/></td></tr>
 <tr><td>Book Cost</td><td><html:text property="bookCost" value=""/></td></tr>
 </table>
 </p>
 <p>
 <table><tr>
 <td><input type="submit" name="actionMethod" value="SaveBook" /></td>
 </tr></table>
 </html:form>
 </p>
 </body>
 </html>
 


editbook.jsp

In this page, used HTML tag lib, form bean class(BookForm) will take care of filling the form input elements.

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
 <html>
 <body>
 <p><b>Struts Example - Simple Book Store App</b></p>
 <b>Edit Book</b>
 <html:form>
 <table style="background-color:#82CAFA;">
 <tr><td>Book Id</td><td><html:text property="bookId" disabled="true"/></td></tr>
 <tr><td>Book Name</td><td><html:text property="bookName"/></td></tr>
 <tr><td>Author Name</td><td><html:text property="authorName"/></td></tr>
 <tr><td>Book Cost</td><td><html:text property="bookCost"/></td></tr>
 </table>
 </p>
 <p>
 <table><tr>
 <td><input type="submit" name="actionMethod" value="UpdateBook" /></td>
 </tr></table>
 </html:form>
 </p>
 </body>
 </html>
 

Note:

  • All the jsp files should present under directory apache-tomcat-6.0.29\webapps\examples\jsp\books.
  • Compile all the java files, and place the created class files to apache-tomcat-6.0.29\webapps\examples\WEB-INF\classes

All the codes specified in this blog will compile & work perfectly without any issues. Just download and try it. It’s very easy to learn and build applications in Struts.

Sample Output of Book Store Apps.

Available Books in Store

Add Book Web Page

Add Book

Edit Book Web Page

Edit Book


Struts Dispatch Action

November 29, 2010

DispatchAction provides a mechanism to group related functions/actions into a single Action class. Therefore each and every action has to be specified in separate methods. This eliminates the creation of multiple independent action classes for each function/action.

DispatchAction class itself has the implementation of execute() method and its being used to managed to delegating the request to one of the methods in the derived Action class. This method invocation can be done based on the request “parameter“.

Let’s see an example of DispatchAction.

struts-config.xml

parameter – attribute is used to delegate the request to corresponding method of the BookAction class. So define this value with appropriate name.

 <action path="/books"
 type="com.books.BookAction"
 parameter="actionMethod"
 validate="false"
 scope="request">
 <forward name="addBook" path="/jsp/book/addbook.jsp"/>
 <forward name="editBook" path="/jsp/book/updatebook.jsp"/>
 <forward name="saveBook" path="/jsp/book/save.jsp"/>
 <forward name="deleteBook" path="/jsp/book/deletebook.jsp" />
 </action>
 

BookAction.java

It eliminates the execute method entirely.  Because it directly implements the desired methods, those custom methods have same signature as execute method.

The class BookAction extends org.apache.struts.actions.DispatchAction

 import org.apache.struts.action.ActionForm;
 import org.apache.struts.action.ActionMapping;
 import org.apache.struts.action.ActionForward;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import org.apache.struts.actions.DispatchAction;

 public class BookAction extends DispatchAction
 {
 public ActionForward addBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Add Book Page");
 return mapping.findForward("addBook");
 }

 public ActionForward editBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Edit Book Page");
 return mapping.findForward("editBook");
 }

 public ActionForward saveBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Save Book Page");
 return mapping.findForward("saveBook");
 }

 public ActionForward deleteBook(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
 System.out.println("Delete Book Page");
 return mapping.findForward("deleteBook");
 }
 }
 

bookdetails.jsp

This page has four different links for doing different actions say Add/Edit/Save/Delete books. Every individual action has to be uniquely represented by the request parameter actionMethod.

 <html>
 <head>
 Book Details
 <body>
 <a href="/books.do?actionMethod=addBook">Add Book</a>
 <a href="/books.do?actionMethod=editBook">Edit Book</a>
 <a href="/books.do?actionMethod=saveBook">Save Book</a>
 <a href="/books.do?actionMethod=deleteBook">Delete Book</a>
 </body>
 </head>
 </html>

Note: I didn’t enclosed addBook, editBook, saveBook, deleteBook jsp files with this post. You can design and implement in your own way. Here am just explaining the flow of how DispatchAction class works in Struts.

New to Struts, want to learn Struts Basics. Go here https://manikandanmv.wordpress.com/2010/11/18/struts-basics/

Complete Struts Example, go here  https://manikandanmv.wordpress.com/2010/12/07/struts-example/

Struts Basics

November 18, 2010

Why do we need to go struts.?
Normal Java EE web applications works in this form.

Flow of Servlet & JSP Web Applications
drawbacks

  • difficult to maintenance.
  • application logic mingled with presentation.(inadequate for large projects).

Struts

Its an open-source framework for developing the web applications in Java EE. The goal of struts is to cleanly separate Business logic from User Interface and Program flow using MVC(Model View Controller) design pattern.

MVC Architecture

MVC Design Pattern Architecture

Image Courtesy : Sun/Oracle

Model – The model represents the data and the business logic to process the data of an application. Any data that an application will persist becomes a part of model.

View – The view represents the presentation of the application. The view can get data from the model and decide on how to present them to the client.

Controller – The controller intercepts the requests from view and passes it to the model for appropriate action. It also decides on the next view to be presented depending on the last client action and the outcome of the model operations.

Struts component classes

ActionServlet
ActionServlet is a backbone of all struts applications. This class plays the role of Controller and is responsible for handling all requests. All incoming requests are mapped to the central controller in the deployment descriptor.

Action
Action is a part of the Model and is a wrapper around the business logic.Purpose of this class is to translate the Http servlet request to the business logic that should be executed to process the request. It can also perform Authorization, Logging before invoking business operation.

execute() is the important method in this class. This has been called by the controller when a request is received from the client, process the request and return to an appropriate action forward.

ActionForm
ActionForm is a Java bean, maintains the session state for web applications. It has setters/getters method used to capture input data from an HTML form(View) and transfer it to the Action class. It also used to transfer data from the Action class back to the HTML form. It also a place to put data conversion and error handling logics.

Struts Configuration File
struts-config.xml is a central configuration file binds together model, view and controller. Five important sections/definitions of config file as follows.

Form bean Definitions
You will write one of these for each HTML form your app needs to process.

 <form-beans>
 <form-bean name="BookForm" type="com.book.BookForm" />
 </form-beans>
 

Global Forward Definitions
A set of forward elements describing generally available forward URIs.

 <global-forwards>
 <forward name="logon" path="/books/jsp/logon.jsp" />
 </global-forwards>
 

Action Mappings
It contains the mapping from URL path to an Action class and also have association with Form Bean. A set of action elements describing a request to action mapping.

<action-mappings>
<action path="/books"
type="com.book.action.BookAction"
name="BookForm"
validate="false"
scope="session">
<forward name="success" path="/books/success.jsp"/>
<forward name="failure" path="/books/failure.jsp"/>
</action>
</action-mappings>

type – fully qualified class name of action.
name – name of the form bean associated with this action.
scope – specifies how long the form bean should live, either session or request.
validate – if true form bean is validated on submission.Otherwise validation is skipped.
forward – the page of which the control should be forwarded, these are all local forwards can be accessed only within the ActionMapping.

Controller Configurations
Its an optional one, default controller is org.apache.struts.action.RequestProcessor.

ActionServlet still receives the requests, but then delegates the request handling to an instance of the RequestProcessor class that has been installed. You can subclass the RequestProcessor with you own version and modify how the request is processed.

<controller processorClass="org.apache.struts.action.RequestProcessor" />

Message Resources
It has built-in support for Internationalization(I18N). You can also define different resource bundles simulatenously in your web application.

<message-resources parameter="resources/ApplicationResources" />

parameter – name of the resource bundle. Optional attributes are className, factory, key, null, escape

Configuring struts application in Deployment Descriptor
We have to configure about ActionServlet in web application. This can be done by adding the following servlet definition in web.xml file.

<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>validate</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

Servlet Mappings tells when the action should be executed. All request URIs with the pattern *.do are mapped to this servlet. ie) specified servlet action should service all the requests with URL pattern *.do.

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

Advantages of Struts

  • Enables clean separation of code between functionality and presentation.
  • Built in internationalization – have the capability to display input in multiple languages.
  • Built in extensible authentication and validation.
  • Promotes modularity ie) Allows modular development and easy integration with new components.
  • Allowing developer to concentrate on the Business Logic.
  • More easily maintainable and extensible.(reduce the code complexity and duplication).

See the complete example of Struts App(Book Store) here : https://manikandanmv.wordpress.com/2010/12/07/struts-example/