Wednesday, October 29, 2008

BG-Blogger by prlamnguyen

1 comments
Delicious 0

Posted by Nguyen, Lam D



This is first layout which i designed for Blogger.
Any information or coment please go to my Blogger at address http://prlamnguyen.blogspot.com.
I'm a Java Developer, love web design, base in Minnesota, US. Really happy if my design and code will be useful for everyone.

Saturday, July 19, 2008

Creating Container-managed Entity Beans with JBoss and MyEclipse

3 comments
Delicious 0

Posted by Nguyen, Lam D



Introduction
An Entity Bean is an Enterprise JavaBean (EJB) that represents a persistent object in a relational database. JBoss provides two methods of entity bean persistence, Bean Managed Persistence (BMP) and Container-Managed Persistence (CMP). With BMP, the entity bean developer must implement all the persistence logic. With CMP, the application server manages entity bean persistence; the developer provides interfaces and configuration.
Entity JavaBeans that use container-managed persistence (CMP) are convenient, because they require so little custom code to achieve automatic persistence. But that convenience carries a price: beans using CMP are also ferociously complex to configure, and often difficult to debug.

Preparing
There're many ways to create EJB with CMP method. But, why we not make it simply by using MyEclipse? In this article, you will see how can i make an CMP in MyEclipse and Jboss step by step. So, you have to install pre-requirements to make it works. I'm using:
  • Eclipse 3.2.1 with MyEclipse 5.5.1 GA
  • Database MSSQL 2000 with services pack 3 (so easily config in tutorial), you can use any SQL server you want.
  • Java SE 5.0 with Update 10 (the old version of Java SE, lastest realease is
    Java SE 6 Update 10 Beta)
  • jboss-4.0.5.GA
You sould create a working directory where you install and store all related files. In this tutorial we'll use C:\Java as working directory. If you want to store it somewhere else, then you'll have to replace every occurence of "C:\Java" throughout the tutorial by the desired directory.

Download and install Java SE JDK
You can download the lastest version of Java SE JDK is Java SE 6 JDK in Java SE download page. I'm still using Java Se 5 JDK :D
  1. Pick the latest JDK without Java EE SDK and/or Netbeans. (so, we not need NetBean for whatever :D)
  2. Accept the License Agreement and click at Windows Offline Installation, Multi-language.
  3. You will get the file jdk-xxx-windows-i586-p.exe (xxx base on your version downloaded), save it to disk.
  4. Install the JDK and JRE in C:\Java\ .Default path for install is C:\Program Files\java. You should change to C:\java because when using command, you not need to add double quote to java path.
Download and install Eclipse 3.2 with MyEclipse 5.5.1 GA
Eclipse is fee :D. You should download the lastest Eclipse IDE package Eclipse IDE for Java EE Developers
  1. Surf to the Eclipse download page.
  2. Click at Eclipse IDE for Java EE Developers.
  3. Select a mirror and you will get the file eclipse-jee-ganymede-win32.zip, save it to disk.
  4. Extract the zip to your work directory.
Well, you can download one package include Eclipse and MyEclipse at MyEclipse Download Page by Accept License Agreement: Standard/Pro License and Blue Edition License. Please download Eclipse IDE 3.2.x same as my tutorial.
  1. See MyEclipse Enterprise Workbench 5.5.1 GA for Windows 98/2000/NT/XP/Vista (05/21/2007)
  2. Choose All In One Package if you want to install MyEclipse Full Package includes Eclipse or Plug-in if want MyEclipse Standalone.
  3. Install IDE or Plug-In.

Download jboss
Download lastest version of jboss if you want or jboss version 4.0.5 GA same as mine at JBoss Application Server Downloads
Extract the package to your work directory. Done.

Install Microsoft SQL Server with Services Pack 3 (or above)
If you installed MS SQL 2000 server, you have to install services pack 3 to work with JNDI Datasource. Download the services pack at MS SQL 2000 Server with Services Pack 3a download page.
Important: You must upgrade computers running Microsoft® Windows® XP to Windows XP Service Pack 1 before applying SQL Server 2000 Service Pack 3a.

Run and configure Eclipse
  1. The first time to start Eclipse, you must select work space for Eclipse. 
  2. On the welcome screen, click at the icon with the curved arrow at the right side: Go to the workbench
  3. In the top menu, go to Window » Preferences » Java » Installed JREs. Select the current JRE (it should automatically be the same as you have installed, but we not use jre as JRE Installed, should edit it to JDK directory, in this case, click jre which automatically add to Eclipse and Edit, point the directory to JDK installed directory, and it'll automatically known what directory where jre is. Now the source code of the Java SE API is available in Eclipse.
Integrate JBoss in Eclipse
In the top menu, go to Window » Preferences » MyEclipse » Application Servers » Jboss 4. Select Enable Jboss Server, select Jboss Home Directory, others field is default. Then select JDK, choose JDK you installed, click Apply, then Ok. Now Jboss is integrated in Eclipse.

On the Toolbar of Eclipse, click  and select JBoss server to start jboss. Default port of jboss is 8080(keep in mind), you can change it later. Once it is started, go to http://localhost:8080 (where 8080 is supposed to be the HTTP/1.1 port of Tomcat). You should get the default Jboss home page.

You can simply stop jboss server by click on

Create EJB project with CMP method
In the menu, click File » New » Project...In the New Project Dialog, select MyEclipse, then choose EJB Project:

Click next to continues. Then enter the EJB project details, i choose the name as "CMPTutorial", click finish.
Ok, you prepared an EJB project, now, to create new CMP method, right click on Project at Package Eplorer panel, select New »Other...Choose MyEclipse in Wizard Dialog and select EJB » Entity Bean, click next as image below

In Entity Bean Diaplog image above, you can see the red ellip. Note: the name of package must be end with ejb folder and the class name must be end with Bean. Example, if your package is "yourpackage" the entity bean must be in "yourpackage.ejb" and the name of class entity bean of yours is YourBean or AnythingBean....Access of the EJB can be Remote/Local or Both, i select Remote in order to access from outside EJB.

Click Finish.

The Entity Bean Class
The entity bean class contains the entity bean logic. However, with CMP, the entity class is abstract, because many of the methods are defined in the class but implemented by the container. Accessor methods must be both public and abstract and the name of every method defined in CMP must be exactly with database field name.
In database:

In Entity Bean class:
/**
* @ejb.interface-method view-type="both"
* @ejb.pk-field
* @ejb.persistence
* @jboss.persistence
* not-null = "true"
* auto-increment = "true"
* @jboss.sql-type
* type = "int"
* @jboss.jdbc-type
* type = "INTEGER"
* @return
*/
public abstract Integer getArticle_ID();
/**
* @ejb.interface-method view-type="both"
* @param article_ID
*/
public abstract void setArticle_ID(Integer article_ID);

/**

* @ejb.persistence-field
* @ejb.interface-method view-type="remote"
* @return
*/

public abstract String getArticle_title();

/**
* @ejb.interface-method view-type="both"
* @param article_title
*/
public abstract void setArticle_title(String article_title);

/**
* @ejb.persistence-field
* @ejb.interface-method view-type="remote"
* @return
*/
public abstract String getArticle_desc();

/**
* @ejb.interface-method view-type="both"
* @param article_desc
*/
public abstract void setArticle_desc(String article_desc);

/**
* @ejb.persistence-field
* @ejb.interface-method view-type="remote"
* @return
*/
public abstract String getArticle_content();

/**
* @ejb.interface-method view-type="both"
* @param article_content
*/
public abstract void setArticle_content(String article_content);
So, because in database, the primary field is article_ID, the getArticle_ID must be declared as pk-field and if it's auto-increment, you have to add @jboss.persistence with not-null="true" and auto-increment = "true". Each method getter in Entity Bean class have to be added in the top with the following: @ejb.persistence-field and @ejb.interface-method view-type="remote" and each method setter, must be: @ejb.interface-method view-type="both".

Add following codes into the top of class:

/**
*
* @ejb.bean name="Article"
* display-name="Name for Article"
* description="Description for Article"
* jndi-name="ejb/Article"
* type="CMP"
* cmp-version="2.x"
* view-type="remote"
* schema="ArticlesSchema"
* primkey-field="article_ID"
*           primkey-class="java.lang.Integer"
*
* @ejb.pk class = "java.lang.Integer" generate = "False"
*
* @jboss.unknown-pk class="java.lang.Integer"
* column-name="article_ID"
* jdbc-type="INTEGER"
* sql-type="int"
* auto-increment="true"
* @jboss.entity-command name="mssql-fetch-key"
*
* @ejb.finder query="SELECT OBJECT(b) FROM ArticlesSchema AS b"
* signature="java.util.Collection findAll()"
*
* @ejb.finder query="SELECT OBJECT(b) FROM ArticlesSchema AS b WHERE b.article_ID=?1"
* signature="java.util.Collection findByArticleId(java.lang.Integer article_ID)"
*
* @ejb.persistence table-name="Articles"
* @jboss.persistence table-name="Articles"
*/
public abstract class UsersCMPBean implements EntityBean {
External clients use an entity bean's home interface to create, remove, and find instances of the entity bean. In Entity Bean class defines the following methods:

  • Create. Creates an entity bean instance.

  • Remove. (required) Removes an entity bean instance.

  • Finder methods. Find one or more entity bean instances. Finder method names must start with "find" (which i've defined in the top of the class above). For a CMP entity bean, the finder method findByPrimaryKey must be defined, but with MyEclipse, findByPrimaryKey method will be automatically generated by XDoclet.

In Entity Bean class, search for ejbCreate() method, replace by:

public Integer ejbCreate(String article_title, String article_desc, String article_content) throws CreateException {
    setArticle_title(article_title);
    setArticle_desc(article_desc);
    setArticle_content(article_content);
    return null;
}
Becasue article_ID is primary field and it's auto-increment, so you not need to set Article_ID in ejbCreate. Note: ejbCreate() method must return to primary value type(in above, primary field is article_ID, and the value type is Integer, sql-type and jdbc-type are different).

Replace ejbPostCreate() method by:

public void ejbPostCreate(String article_title, String article_desc, String article_content) throws CreateException {
}
The entity Bean Provider may use the ejbPostCreate() to set the values of cmr-fields to complete the initialization of the entity bean instance. An ejbPostCreate() method executes in the same transaction context as the previous ejbCreate() method.

Add Standard EJB module to XDoclet project properties
To generate EJB related classes using XDoclet, you have to add Standard EJB module to XDoclet project properties. Right click on Project, click on Properties. Choose MyEclipse » XDoclet. In Configuration tab, click Add Standard..., select Standard EJB, click OK.





Customize XDoclet configuration
Right click on Standard EJB was defined above, choose Add(not Add Doclet), select jboss, click OK to add jboss entity.



You can customize XDoclet with some value in order to generate EJB related classes

  • deloymentDescription

    1. destDir :src/META-INF

    2. validateXML: true


  • fileset

    1. dir: src

    2. includes: **/*.java

  • jboss

    1. version: 4.0

    2. alterTable: false

    3. creatTable: false;

    4. datasource: java:/Articles

    5. datasourceMapping: MS SQLSERVER2000

    6. destDir :src/META-INF

Following entities are required, you can remove others.





Run XDoclet
We have not completely finished the source code, but it is time for a first generation with xdoclet.

Right click on the project and choose run xdoclet.



Create JNDN Datasource
Create new XML file and deploy(simply save XML file to Jboss directoryserverdefaultdeploy) with name: xxx-ds.xml and inlcudes following codes:

<datasources>
  <local-tx-datasource>
    <jndi-name>Articles</jndi-name>
    <connection-url>jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=YourDatabase</connection-url>
    <driver-class>com.microsoft.jdbc.sqlserver.SQLServerDriver</driver-class>
    <user-name>username</user-name>
    <password>password</password>

    <metadata>
    <type-mapping>MS SQLSERVER2000</type-mapping>
    </metadata>
  </local-tx-datasource>
</datasources>

Deploy EJB to Jboss server
Right click in Project, select MyEclipse » Add and Remove Project Deployments... Following these steps below:

When completed, in console window announ that Bound EJB Home 'Article' to jndi 'ejb/Article'. That's all, you have created new EJB with CMP method successfully.
For the next article, i'll guide you how to access EJB with Java Application and Java Web Aplication
Best Rigard!

© 2008, Lam Duy Nguyen

Tuesday, July 15, 2008

Post form to clean, a tutorial with JSP/Servlet and JavaScript

0 comments
Delicious 0

Posted by Nguyen, Lam D



Rewritten URLs are valuable because they increase website usability and improve search engine optimisation (SEO), in PHP with mod_rewrite, you can rewrite URL easily and simple, when using java, you can too, just follow this article. Well, but we have a problem: HTML forms and rewrite URL were not designed to work together. So, you have to use client-side(java script) to transfer page to result page wich rewrited URL. However, you can do it by server-side script by pre-processing input from HTML Forms and transfer to result page. In this tutorial, i'll guide you how to make it work by 2 way: Client-side and Server-side.
HTML forms only have two ways to pass variables to their target page: GET and POST methods.

POST Method:


Using POST method is sercured by empty URL in address bar. If the result page is result.jsp, URL when POST is only: result.jsp. Wow, nice URL, but, the visitor or user can not reuseable for this URL, and can not simply get the same value when re-access this URL. POST method is best for inserting record to database, but worth for searching or fetching records from HTML forms.

GET Method:


Forms using the GET method send data via the URL. This means that the URL can be copied and revisited at any time. The problem with this method is the format of the parameters. The values in the URL string are ugly, verbose and unfriendly; this is what we are trying to avoid. SEO with GET method is so bad. Almost search engineers like: Google, Yahoo, Live... not love URL generated by GET method.

The Client-Side Solution: Post by JavaScript to result page.
Using javascript with windows.location. In the HTML form, you will create new event for form. When the form is submitted, the function in javascript will be called and tranfer to new page. Script will be following codes:

function getKeyword(){
   q=document.getElementById('query').value;
   window.location = "http://localhost:8080/PostCleanTut/search/"+q;
}


document.getElementById('query').value used for getting value of textfiled inside your search form. After getting the keyword value, script will transfer you to result page(JSP/Servlet) which will be created and rewrited URL yourself. Now, create your new HTML Search form name as searchform.jsp, and it likes following codes:

<html> 
<head>
<title>Search Form</title>
</head>
<body>
     <form action="" onsubmit="getKeyword(); return false;" method="post" name="searchForm" id="searchForm">
        Query:
        <input type="text" name="query" id="query">
        <input type="submit" name="btnSubmit" id="btnSubmit" value="Submit">
     </form>
</body>
</html>
onsubmit="getKeyword(); return false;" used to call getKeyword() funtion from javacript. When done all thing above, submit your form, data posted will be transfered to result page with example address: http://localhost:8080/PostCleanTut/search/yourkeyword.



The Server-side Solution: Pre-processed by a servlet or JSP self page and send redirect to Result page.

Simply processing with a single jsp or a servlet, you can POST to self jsp page include HTML Form, then send redirect to another page which will be rewrited URL. So, in this article, i will do it with a servlet page by doPost() method. In the pre-processing servlet, doPost() method gets parameter from HTML form, you can clean up by removing unwanted characters. However, this article just do simply to explaint what the servlet do with posting form to clean.

Create your new servlet, name as: SearchProcess.java, codes will be:

package prlamnguyen.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import prlamnguyen.util.StringUtil;
public class SearchProcess extends HttpServlet {
  /**
    * Constructor of the object.
    */
   public SearchProcess() {
      super();
   }

  /**
    * Pre-Processing of Search
    * @param request
    * @param response
    * @throws ServletException
    * @throws IOException
    */
   public void proccessRequest(HttpServletRequest request,
      HttpServletResponse response) throws ServletException, IOException {
      //Get parameter from HTML form
      String q = request.getParameter("query");

      // Clean up by removing unwanted characters if you want
      String newQ = StringUtil.searchInput(q);
      response.sendRedirect(request.getContextPath() + "/search/" + newQ);
   }
  /**
    * The doGet method of the servlet. <br>
    *
    * This method is called when a form has its tag value method equals to get.
    *
    * @param request the request send by the client to the server
    * @param response the response send by the server to the client
    * @throws ServletException if an error occurred
    * @throws IOException if an error occurred
    */
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

      proccessRequest(request, response);

   }
  /**
    * The doPost method of the servlet. <br>
    *
    * This method is called when a form has its tag value method equals to post.
    *
    * @param request the request send by the client to the server
    * @param response the response send by the server to the client
    * @throws ServletException if an error occurred
    * @throws IOException if an error occurred
    */
   public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {

     proccessRequest(request, response);

   }
  /**
    * Initialization of the servlet. <br>
    *
    * @throws ServletException if an error occure
    */
   public void init() throws ServletException {
      // Put your code here
   }
}
Above is java class which pre-process and transfer, new servlet which will display result and url will be rewriten have to be created such as name Search.java. Note: you can do it simply by a single jsp to handle and display result, but with a servlet, you can handle data easily by doPost() or doGet() methods, so, it's reason i'm using servlet for this tutorial.

Searching in website is not simply like: where id=?, title=? or onething=?. You should use Full-text Searching, a full-text search allows a search of multiple text columns. If you are setting up a search of a series of articles or a site with lots of product-related content, a MySQL FULLTEXT search can make it very easy to find articles or products related to the keywords used by a searcher. This search method does exactly what its name implies–it allows a full search of large text fields. If you're new to Full-text Search, please follow this link to know how MySQL does with Full-text search.

Following codes bellows are written almost important steps to make search works with URL Rewriter, something like database connection, JNDI...please do it yourself.



Codes of Search.java:



package prlamnguyen.servlet;
/**
* @author Nguyen Duy Lam
*/
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import prlamnguyen.connector.PrlConnection;
import prlamnguyen.model.Article;
public class Search extends HttpServlet {


    Connection con = null;
    PreparedStatement prst = null;
    ResultSet rs = null;
    //Here is my Connection class
    // please create your one class to get connection or write it inside this servlet
    PrlConnection prlcon = null;

    /**
    * Constructor of the object.
    */
    public Search() {
       super();
    }

    /**
    *
    * @param request
    * @param response
    * @throws ServletException
    * @throws IOException
    */
    public void proccessRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        
        //Init my new connection
        prlcon = new PrlConnection();

        //Display articles in result list in result jsp page which will be created before
        try {
            //Get database connection
            con=prlcon.getConnection();
            //Prepare Statement with Full-text search query, i'm using MySQL.
            prst=con.prepareStatement("SELECT * FROM articles WHERE MATCH(article_title, article_desc, article_content) AGAINST (?)");
            //Get query parameter
            String keyword = request.getParameter("query");
            prst.setString(1, keyword);
            rs=prst.executeQuery();
            ArrayList<Article> articleList = new ArrayList<Article>();

            while(rs.next()){
                Article article = new Article(rs.getInt("article_ID"), rs.getString("article_title"), rs.getString("article_desc"), rs.getString("article_content"));
                articleList.add(article);
            }
            request.setAttribute("keyword", keyword);
            request.setAttribute("articles", articleList);
        } catch (ClassNotFoundException e) {
            
            e.printStackTrace();
        } catch (SQLException e) {
            
            e.printStackTrace();
        } catch (NamingException e) {
            
            e.printStackTrace();
        } finally {
            try {
                if(!con.isClosed()) {
                    con = prlcon.closeConnection(con, prst, rs);
                }
            } catch (SQLException e) {
                
                e.printStackTrace();
            }
        }

        ServletContext context = getServletContext();
        context.getRequestDispatcher("/result_search.jsp").forward(request, response);
    }



    /**
    * The doGet method of the servlet. <br>
    *
    * This method is called when a form has its tag value method equals to get.
    *
    * @param request the request send by the client to the server
    * @param response the response send by the server to the client
    * @throws ServletException if an error occurred
    * @throws IOException if an error occurred
    */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        proccessRequest(request, response);

    }


    /**
    * The doPost method of the servlet. <br>
    *
    * This method is called when a form has its tag value method equals to post.
    *
    * @param request the request send by the client to the server
    * @param response the response send by the server to the client
    * @throws ServletException if an error occurred
    * @throws IOException if an error occurred
    */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    
        proccessRequest(request, response);
    
    }



    /**
    * Initialization of the servlet. <br>
    *
    * @throws ServletException if an error occure
    */
    public void init() throws ServletException {
        // Put your code here
    }
}


To display data records, you have to have one data model class. Bellow is one use for above:



package prlamnguyen.model;
/**
* @author Nguyen Duy Lam
*/

public class Article {
    
   private int article_ID;
   private String article_title;
   private String article_desc;
   private String article_content;
    


   /**
   * @return the article_content
   */
   public String getArticle_content() {
       return article_content;
   }
    
   /**
   * @return the article_desc
   */
   public String getArticle_desc() {
       return article_desc;
   }
    
   /**
   * @return the article_ID
   */
   public int getArticle_ID() {
       return article_ID;
   }
    
   /**
   * @return the article_title
   */
   public String getArticle_title() {
       return article_title;
   }
    

   /**
   * @param article_content the article_content to set
   */
   public void setArticle_content(String article_content) {
       this.article_content = article_content;
   }
    
   /**
   * @param article_desc the article_desc to set
   */
   public void setArticle_desc(String article_desc) {
       this.article_desc = article_desc;
   }
    
   /**
   * @param article_ID the article_ID to set
   */
   public void setArticle_ID(int article_ID) {
       this.article_ID = article_ID;
   }
    
   /**
   * @param article_title the article_title to set
   */
   public void setArticle_title(String article_title) {
       this.article_title = article_title;
   }
    

   public Article() {

   }
    

   /**
   * Article model for search result
   * @param article_ID
   * @param article_title
   * @param article_desc
   */
   public Article(int article_ID, String article_title, String article_desc, String article_content) {
       this.article_ID=article_ID;
       this.article_title=article_title;
       this.article_desc=article_desc;
        this.article_content=article_content;
   }
}


Ok, almost important about bussiness logic are done, to be continue, create new JSP page to display search result. Search.java is a servlet, and when fetched data records, it forward to JSP result page name as result_search.jsp, you have to create this jsp page, something likes this:



<%@ page contentType="text/html; charset=utf-8" language="java" import="java.util.*" errorPage="" %>
<%@ page import="prlamnguyen.model.Article" %>

<%
    ArrayList articleList = null;
    Iterator iterator;
    Article article;

%>
<html>
<head>
<title>Result search page</title>
</head>
<body>
<p>Search result for: <strong><%=request.getAttribute("keyword") %></strong></p>
<%
    if(request.getAttribute("articles")!=null) {
        articleList = (ArrayList)request.getAttribute("articles");
        request.removeAttribute("articles");
        iterator = articleList.iterator();
        if(articleList.isEmpty()) {
            out.print("<i>Found nothing, sorry ^^!</i>");
        } else {
            out.print("<ul>");
            while ( iterator.hasNext() ) {
                article = (Article) iterator.next();
                out.print("<li><strong>" + article.getArticle_title() +"</strong><br />");
                out.print("<i>" + article.getArticle_desc() + "</i></li>");
            }
            out.print("</ul>");
        }
    }
%>
</body>
</html>




URL Rewrite


Follow this article to know how to rewrite URL in java, it will guide you step by step hwo to install URLRewriter and make it work in Java Web Application. When installed, insert into your urlrewrite.xml following codes to make URL rewrite work for search in this tutorial.

Add new rule somewhere between <urlrewrite>..</urlrewrite> tag

<rule enabled="true">
   <from>/search/([^/.]+)</from>
   <to>/search?query=
</to>
</rule>
All thing seem to be done, oh, please edit your HTML form. In the Client-side case, form was submitted by javascript, but in Server-side case, please remove onsubmit event, and point action of the form to "<%=request.getContextPath() %>/searchProcess". Example:

<%@ page language="java" pageEncoding="ISO-8859-1"%>

<html>
<head>
<title>Search Form</title>
</head>
<body>
     <form action="<%=request.getContextPath() %>/searchProcess" method="post" name="searchForm" id="searchForm">
        Query:
        <input type="text" name="query" id="query">
        <input type="submit" name="btnSubmit" id="btnSubmit" value="Submit">
     </form>
</body>
</html>
Ok, deploy your web application into web server, example url for testing will be http://localhost:8080/PostCleanTut/searchform.jsp
Note: when coding for a search, you have to handle data inputed from user, should replace Statement with PrepareStatement and set parameter for it to avoid SQL Injection
Best Rigard!
©2008 Lam Duy Nguyen

Monday, July 7, 2008

Using a MySQL Full-Text Search

0 comments
Delicious 0

Posted by Nguyen, Lam D



A full-text search allows a search of multiple text columns. If you are setting up a search of a series of articles or a site with lots of product-related content, a MySQL FULLTEXT search can make it very easy to find articles or products related to the keywords used by a searcher. This search method does exactly what its name implies–it allows a full search of large text fields. A FULLTEXT search is easy to set up if you just follow these simple instructions.


Basic FULLTEXT search has been available in MySQL since version 3.23.23. MySQL version 4 introduced more complex fulltext search functions that include boolean searches. This MySQL tutorial covers basic text searches, which is the type of search most commonly used. MySQL refers to this simple type of search as Natural Language Full-Text Searches.

FULLTEXT searches are only available with a MyISAM table type, which is MySQL’s default table type unless another type is specified. One of the nice things about this type of search is that it supports stop words (search words that are ignored for efficiency) and the results are sorted by relevancy.

First, you will need to create a FULLTEXT index using one or more text-type data columns (TEXT, CHAR or VARCHAR). An index organizes data and makes it more efficient to find whatever you are searching for. It’s common to set up a search that includes the content in an article, as well as the article title, but other relevant text columns can also be included. Just do not overload the index or the search by including columns that are not absolutely necessary. There are two easy ways to set up a FULLTEXT index with an existing database table–either through an SQL statement or by using phpMyAdmin.

If you like working with MySQL from a command line, the following statement will create an index for an existing table called ‘products’. Both the product name and description columns are included in the index.

ALTER TABLE products ADD FULLTEXT (product_name, product_description);  


You can also use phpMyAdmin to create the index.







  1. Select the table, go to the index section of the Table page, enter the number of columns you wish to index, and click Go.

  2. On the Create a New Index page, select FULLTEXT as the index type, then select the columns you want to include in the index. You can name the index if you wish, but it is not necessary.

  3. Click Save.

There are a few things you should know about the basic FULLTEXT search. First, all MySQL stopwords are ignored in the keyword phrase used in a search. Stopwords are commonly used words that generally do not add anything useful to a search phrase. Second, alphabetic character case is ignored in a MySQL search, so you do not have to convert anything to all upper or lower case in order to search. Third, any word found in more than 50% of the rows in the index will be ignored when you use the basic text search. Fourth, the results will be automatically sorted by relevancy, so the more times the search words appear in a row in the index, the more relevant that particular entry will be. Fifth, remember that MySQL does not index any words that are 3 or less characters in length, so very short words are ignored. Sixth, hyphenated words are treated as separate words.



OK. Lets set up a search to look for a particular product. A FULLTEXT search use MATCH and AGAINST verbs. You will MATCH the column fields AGAINST the text word or phrase you are searching for.



Let’s say that the web site’s product offering is machine tools and you are searching for a drill press. Your query may look like the following:



SELECT * FROM products WHERE  MATCH ( product_name, product_description ) AGAINST ('drill press');  

That’s all there is to it. The results should display all rows in the table that refer to drill presses. The results will display in descending order of relevancy, which means the most relevant products will display first.

Useful link:

Sunday, July 6, 2008

How to read XML file in Java

0 comments
Delicious 0

Posted by Nguyen, Lam D



This sample code reads the XML file using DOM parser. DOM parser loads the XML file into the memory and makes an object model of it. This Object modal can be traversed to get its elements.

This code will parse the following MyXMLFile.xml file and print its elements to the console.



XML file: MyXMLFile.xml
<?xml version="1.0"?>
<company>
  <employee>
    <firstname>Tom</firstname>
    <lastname>Cruise</lastname>
  </employee>
  <employee>
    <firstname>Paul</firstname>
    <lastname>Enderson</lastname>
  </employee>
  <employee>
    <firstname>George</firstname>
    <lastname>Bush</lastname>
  </employee>
</company>
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLReader {
public static void main(String argv[]) {
try {
File file = new File("c:\MyXMLFile.xml");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(file);
        doc.getDocumentElement().normalize();
        System.out.println("Root element " + doc.getDocumentElement().getNodeName());
        NodeList nodeLst = doc.getElementsByTagName("employee");
        System.out.println("Information of all employees");
        for (int s = 0; s < nodeLst.getLength(); s++) {
           Node fstNode = nodeLst.item(s);
          if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
              Element fstElmnt = (Element) fstNode;
              NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("firstname");
              Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
              NodeList fstNm = fstNmElmnt.getChildNodes();
              System.out.println("First Name : " + ((Node) fstNm.item(0)).getNodeValue());
              NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("lastname");
              Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
              NodeList lstNm = lstNmElmnt.getChildNodes();
              System.out.println("Last Name : " + ((Node) lstNm.item(0)).getNodeValue());
           }
        }
     } catch (Exception e) {
        e.printStackTrace();
     }
   }
}