leejeok

The Remarkable Everyday

Archive for the ‘Struts’ Category

Simple JNDI Accessing MySQL Datasource

Posted by leejeok on May 27, 2008

Base on the previous post, I have used the struts-config.xml to define the datasource to access to the MySQL database. The datasource class is code within the Action class (controller layer) and map to the struts-config.xml.

 

In order to improve the programming pratice, the datasource can be created via JNDI and the java code should be sit within the model layer. As a result, business logic will separate from the controller layer and making the Action class without knowing any relation with business class at all.

 

I am using Apache Tomcat 5.x and so, I will define the datasource resource via JNDI within the context.xml.

 

<Context path=”/bookstore”>

<ResourceLink global=”jdbc/bookstoreDB” name=”jdbc/bookstoreDB” type=”javax.sql.DataSource”/>

</Context>

 

The java code to make the database connection accessing the JNDI would be look like this:

 

    Connection cn(){

        DataSource ds = null;

       

        try {

            Context ctx = new InitialContext();

            if ( ctx == null ) {

                throw new RuntimeException(“JNDI Context could not be found.”);

            }

            ds = (DataSource)ctx.lookup(“java:comp/env/jdbc/bookstorDB”);

           

            if ( ds == null ) {

                throw new RuntimeException(“DataSource could not be found.”);

            }

            return ds.getConnection();

            // Handle any JNDI errors

        } catch (NamingException ne) {

            throw new RuntimeException(“A JNDI error occured. ” + ne.getMessage());

           

        }catch(Exception e){

            System.err.println(“Boom – No Context”);

        }

        return null;

}

 

Alternative, you can use JSP Standard Tag Library (JSTL) without embedding any Java code. I am using JSTL SQL tag here and may look like this:

 

<%@ taglib prefix=”sql” uri=”http://java.sun.com/jsp/jstl/sql&#8221; %>

<%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core&#8221; %>

 

<sql:setDataSource dataSource=”jdbc/bookstoreDB” />

 

<sql:query var=”qryBooks” >

    SELECT bookID, bookTitle, bookAuthor, bookPublisher FROM book

</sql:query>

 

<table>

    <c:forEach var=”row” items=”${qryBooks.rows}”>

        <tr>

            <td>${row.bookID}</td>

            <td>${row.bookTitle}</td>

            <td>${row.bookAuthor}</td>

            <td>${row.bookPublisher}</td>

        </tr>

    </c:forEach>

</table>

Advertisements

Posted in JDBC, JSTL, MySQL, Struts | 1 Comment »

Struts – Database Access with struts-config.xml

Posted by leejeok on May 26, 2008

A sample program which connecting to the MySQL database to display the data. I am using the Struts framework to developed this program. The main idea is of this post is to use the struts-config.xml to define the datasource and using Action class to access and select the data.

Please bear in mind, the Action class which represent as controller layer, should not contain any business logic code and database access code. The best pratice is to apply the DAO mechanism by putting your business logic or database access code within the model layer.

The datasource should only define within the struts-config.xml when there is a limitation of connectivity to the database within the model layer. Alternative, you can use the JNDI to define the datasource and that would be the best recommendation in best pratice. However, that will be my next post on my blog.

 

Sample of the datasource used within the struts-config.xml:

    <data-sources>
        <data-source type=”org.apache.commons.dbcp.BasicDataSource” key=”dbSource”>
            <set-property property=”driverClassName” value=”com.mysql.jdbc.Driver” />
            <set-property property=”url” value=”jdbc:mysql://localhost:3306/bookstore” />
            <set-property property=”username” value=”someuser” />
            <set-property property=”password” value=”somepassword” />
        </data-source>
    </data-sources>

 

Here are the summary of development been used.

  • Struts 1.2.9 framework
  • index.jsp, selectBook.jsp, SelectBookActionForm.java – view layer
  • SelectBookAction.java – controller layer
  • Book.java – data layer
  • Defining datasouce at struts-config.xml
  • MySQL database

Source Code: Click Here

Posted in Struts | 5 Comments »

Struts: Build HTML Options Tag Elements from MySQL data

Posted by leejeok on May 25, 2008

Some sample program developed using STRUTS framework to access the MySQL database and retrieve data to build the html options elements. This post is consider as an enhancement from the previous post Struts: HTML Options Tag Sample Code.

 

The previous post was hardcoded to build the html options tag. Meanwhile, this post will build the html options’ elements by retrieving data from MySQL database.

 

I have used the struts-config.xml to define the datasouce to access to the MySQL database. Some simple explanation will be define within this blog here.

 

1. Defining the datasource within the struts-config.xml.

 

    <data-sources>

        <data-source type=”org.apache.commons.dbcp.BasicDataSource” key=”dbSource”>

            <set-property property=”driverClassName” value=”com.mysql.jdbc.Driver” />

            <set-property property=”url” value=”jdbc:mysql://localhost:3306/itemdb” />

            <set-property property=”username” value=”someuser” />

            <set-property property=”password” value=”somepassword ” />

        </data-source>

</data-sources>

 

2. Code the ActionForm and Action class.

 

Within this tutorial, the ActionForm and Action class will not do any much of process. In real world programming, you may want to use both class for building you validation process here.

 

I have use the Action class to create the datasource and map to the struts-config.xml.

 

    public ActionForward execute(ActionMapping mapping, ActionForm  form,

            HttpServletRequest request, HttpServletResponse response)

            throws Exception {

       

        /** Here ‘dbSource’ maps to the datasource key defined in struts-config.xml: */

        DataSource dataSource = (DataSource)servlet.getServletContext().getAttribute(“dbSource”);

       

        ArrayList menuList = new ArrayList();

        MenuData menuData = new MenuData();

       

        //pass the dataSource to menuList within MenuData class.

        //assign elements to menuList.

        menuList = menuData.menuList(dataSource);

 

        //set the attribute to be use for the menu.jsp

        HttpSession session = request.getSession();

        session.setAttribute( “menuList”, menuList);

       

        return mapping.findForward(SUCCESS);

       

    }

 

3. Code the database access and business logic.

 

The created datasource will be pass to the MenuData class to be override by menuList. The business logic and database access will be developed within the MenuData class.

 

public ArrayList menuList(DataSource dataSource) {

       

        Connection conn = null;

        Statement  stmt = null;

        PreparedStatement prpStmt = null;

        ResultSet rs = null;

       

        ArrayList menuList = new ArrayList();

        Menu menu = null;

       

        try{

           

            conn = dataSource.getConnection();

            String sqlQuery = “SELECT itemid, itemname FROM itemtable”;

            prpStmt = conn.prepareStatement(sqlQuery);

            rs = prpStmt.executeQuery();

           

            while (rs.next()) {

                menu = new Menu(rs.getString(1), rs.getString(2));

                menuList.add(menu);

            }

           

            rs.close();

            prpStmt.close();

            conn.close();

           

        } catch ( SQLException e ) {

            System.err.println(“SQL Exception occured while accessing the table.” );

            e.printStackTrace();

            return null;

           

        } finally {

            try {

                conn.close();

            } catch (SQLException e) {

                System.err.println(“Unable to close connection.” );

                e.printStackTrace();

            }

        }

       

        return menuList;

       

    }

 

4. Remark

  • I am using the NetBeans IDE tool to developed the code and MySQL as the database.
  • Create the database, table and insert some data. I had included the database and please use the MySQLAdministrator to restore the data.
  • Within the struts-config.xml, you may want to change the value of username and password. Remember within the struts-config.xml, the element type of <data-sources> must define earlier <form-beans>.

Overall, there is 6 pieces code have been used for this Struts tutorial.

 

View Layer

  • index.jsp
  • begin.jsp
  • ManuForm.java

 

Controller Layer

  • MenuAction.java

 

Data Layer

  • MenuData.java
  • Menu.java

Download Sample Code and Database: Click Here

Posted in Struts | 1 Comment »

Struts: HTML Options Tag Sample Code

Posted by leejeok on May 14, 2008

I have been doing some research on the internet recently and notice not much of the sample code been provided to build the drop down menu using struts html options tag.

Here are the sample program which I develop using Struts framework by applying the html options tag. The screenshot will look similar as below.

 

Here are the list of pieces code been used.

index.jsp

<%@ taglib uri=”http://struts.apache.org/tags-html&#8221; prefix=”html” %>

 

<html>

    <head>

        <title>HTML Options Tag</title>

    </head>

    <body>

        <h1>Struts: Using HTML Options Tag Example</h1>

        <html:link action=”login”>Begin</html:link>

    </body>

</html>

 

 

menu.jsp

 

<%@ taglib uri=”http://jakarta.apache.org/struts/tags-html&#8221; prefix=”html” %>

 

<html>

    <head>

        <title>HTML Options Tag</title>

    </head>

    <body>

        <h1>Struts: Using HTML Options Tag Example</h1>

        Please select the menu.

        <html:form action=”login”>

            <html:select property=”menu” >

                <html:option value=””>–SELECT–</html:option>

                <html:options collection=”menuList” property=”value” labelProperty=”label” />

            </html:select> 

        </html:form>

    </body>

</html>

 

 

MenuForm.java

 

package com.selection.struts;

 

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionMessage;

 

public class MenuForm extends org.apache.struts.action.ActionForm {

   

    public String menu;

   

    public String getMenu() {

        return menu;

    }

   

    public void setMenu(String menu) {

        this.menu = menu;

    }

   

  

    public MenuForm() {

        super();

        // TODO Auto-generated constructor stub

    }

   

}

 

MenuAction.java

 

package com.selection.struts;

 

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

import org.apache.struts.action.Action;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionForward;

 

import javax.servlet.http.HttpSession;

import java.util.ArrayList;

 

public class MenuAction extends Action {

   

    private final static String SUCCESS = “success”;

   

    public ActionForward execute(ActionMapping mapping, ActionForm  form,

            HttpServletRequest request, HttpServletResponse response)

            throws Exception {

       

        ArrayList menuList = new ArrayList();

        MenuData menuData = new MenuData();

        menuList = menuData.menuList();

       

        HttpSession session = request.getSession();

        session.setAttribute( “menuList”, menuList);

       

        return mapping.findForward(SUCCESS);

       

    }

}

 

In real world programming, some developer would prefer to display the options to be retrieved from the database. Here, I will hardcode the options and you may want to change the code to suit yourself.

 

 

 

MenuData.java

 

package com.selection.struts;

 

import java.util.ArrayList;

 

public class MenuData {

   

    public MenuData() {

    }

   

    public ArrayList menuList() {

                

        ArrayList menuList = new ArrayList();

       

        Menu menu = null;

        menu = new Menu(“1”, “First Option”);

        menuList.add(menu);

        menu = new Menu(“2”, “Second Option”);

        menuList.add(menu);

        menu = new Menu(“3”, “Third Option”);

        menuList.add(menu);

        menu = new Menu(“4”, “Forth Option”);

        menuList.add(menu);

       

        return menuList;

       

    }

   

}

 

Menu.java

 

package com.selection.struts;

 

public class Menu {

   

    /** Creates a new instance of Menu */

    public Menu() {

    }

   

    String value;

    String label;

   

    public Menu(String value, String label){

        this.value = value;

        this.label = label;

    }

   

   

    public String getValue() {

        return value;

    }

   

    public void setLabel(String label) {

        this.label = label;

    }

   

    public String getLabel() {

        return label;

    }

}

 

 

Each code contains some comments inside. Hope it helps. I have been using NetBeans 5.5 to build this sample. You can get the full code here or deploy the war to your web services.

Click Here

 

Posted in Struts | 8 Comments »

Struts for navigation between JSP pages

Posted by leejeok on May 8, 2008

I will use the ActionClass to navigate the client to the proper JSP pages. The ActionClass will decide which JSP page to be display on the browser.

By having the configurations file, I will specified the pages within here.

 

<action

          path= “/somerequest”

          type=”com.somepackage.someAction”

          scope=”request”

          name=”someForm”

          validate=”true”

          input=”somePage.jsp”>

          <forward name=”Success” path=”/successPage.jsp” redirect=”true”/>

             <forward name=”Failure” path=”/errorPage.jsp” redirect=”true”/>

</action>

 If you are building a login page and would like to redirect client to the menu page after success login, perhaps your configuration file would look similar like this:

<action

input=”/login.jsp”

name=”loginForm”

path=”/myapplication”

scope=”request”

type=”com.myapplication.struts.loginAction”>

      <forward name=”success” path=”/mainmenu.jsp”/>       

</action>

Here, I included with the program which require client to enter some input before allow to proceed to the next page. Click HERE

Posted in Struts | Leave a Comment »

Struts for validation field in JSP

Posted by leejeok on May 8, 2008

One of the reasons to use Struts is the capabilities to validate the entries of data which pass from the user input. The validation process will be code within the ActionClass and pass it back to the ActionForm class. 

Generally, ActionForm:
1. encapsulate the data from the View to be transafer to the Controller.
2. having the getter and setter method to allow input to be mapped from the JSP.
3. having the validate() method which will perform the validation process.
3. represent as VIEW components within the MVC design pattern.
In other word, ActionForm Bean Populating the view, Provide Input to Action class, and Perform Validation.

Generally, the ActionClass:
1. Represent as the Controller components. Serve as the bridge to communicate between View and Model components.
2. Contain the execute() method which will interface with Model for business process and forward the control to View to display.

I have a sample of program which will only perform the validation process.  Click Here.

After processing the validation, the ActionClass will redirect to the proper page and this will be explain on the next blog.

Posted in Struts | Leave a Comment »