Archive for the ‘JSP’ Category

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/

Handling Timezone in webclient Timer

March 24, 2009

This post is the continuation of my previous post “Showing Timer in webclient”. – i could not handled timezone in my previous code. In detail if you are running a server in one timezone, say US(GMT-08:00)  and you are accessing the server webclient in different machine which has different timezone, say, India(GMT+05:30). So already written code is failed to show the correct server time.
First analyze, what was the problem in previous code:

var time = <%=System.currentTimeMillis()%>
var date = new Date(time);

In the above code, am getting server time in milliseconds and set the same in javascript Date object.
var date = new Date(time) – while executing this line, server will get browser timezone and set that timezone into this date object. Due to this we are getting incorrect server time.

Solution to this problem is by setting year, month, day, hours, minutes & seconds separately to Date class.  Here Date class does not take browser timezone.

<%
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
int hrs = c.get(Calendar.HOUR);
int mins = c.get(Calendar.MINUTE);
int secs = c.get(Calendar.SECOND);
%>
var date = new Date(<%=year%> , <%=month%> , <%=date%> , <%=hrs%> , <%=mins%> , <%=secs%> );

For better understanding, once again i put the entire code here with the updated one.

Sample code with Timezone handling.

<div id=”showTimer“></div> <!– Used to show the Digital Timer –>

<%
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
int hrs = c.get(Calendar.HOUR);
int mins = c.get(Calendar.MINUTE);
int secs = c.get(Calendar.SECOND);
%>

<script>

var months = new Array(”Jan”, “Feb”, “Mar”, “Apr”, “May”, “Jun”, “Jul”, “Aug”, “Sep”, “Oct”, “Nov”, “Dec”);
function showCurrentTime(){
var date = new Date(<%=year%> , <%=month%> , <%=date%> , <%=hrs%> , <%=mins%> , <%=secs%> );
var showdate = date.getDate() + ” ” + months[date.getMonth()] + ” ” +date.getFullYear() + “, ” ;
var hrs = date.getHours();
var mins = date.getMinutes();
var secs = date.getSeconds();
hrs = (hrs > 9) ? hrs : “0″+hrs;
mins = (mins > 9) ? mins : “0″+mins;
secs = (secs > 9) ? secs : “0″+secs;
var showtime = hrs + ” : ” + mins + ” : ” + secs;
time = time+1000;
document.getElementById(”showTimer“).innerHTML=showdate + showtime;
}
setInterval(”showCurrentTime()”, 1000);
</script>

Ajax Search

November 14, 2008

With Ajax you can able to dynamically showing the searching results for a search item. Instead of entering a search value in the text box and submit the value after that get a search results in a list. Its an old model. Now web technologies are growing rapidly. So we move to the current trend is an important one. In Ajax Search, the implementation should be like this; type a character sequence in the text box during that time we will query the database for that search value and retrieve & showing the matching results dynamically. The below example will explain you clearly.

Example.

Database Name : Books
Table Name : BookDetails

BookId BookName Author Price
1001 Ajax Nicolas Zakas 1000
1002 Java Herbert Schildt 800
1003 JSP & Servlet James Gosling 1200
1004 C Programming Dennis Ritchie 300
1005 C++ Programming Bjarne Stroustroup 600
1006 Operating Donald 750

Action Class : BookDetails.java

File contains search logic to retrieve data from the database and send results to the client in XML format.

import java.sql.*;
import java.util.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class BookDetails extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//Details of DB
String driverName="org.gjt.mm.mysql.Driver";
String url="jdbc:mysql://localhost:2345/Books";
String username="root";
String password="";
Connection con=null;
try
{
Class.forName(driverName);
con = DriverManager.getConnection(url,username,password);
}
catch( SQLException e )
{
e.printStackTrace();
}
Statement stmt = conn.createStatement();;
ResultSet res = null;
String input = request.getParameter("searchtext");
res = stmt.executeQuery("select BookName from BookDetails where BookName like '%"+input+"%'");
Sting output = "";
String result = "";
while( res.next() )
{
String bookname = res.getString("BookName ");
result = ""+bookname+"";
}
output = output + result + "";
System.out.println("Search Output is : "+output);
stmt.close();
conn.close();
response.setContentType("text/xml");
PrintWriter out = response.getWriter();
out.println(output);
out.close();
}
}

Client File : book.jsp

File used to get the input of search value and shows the matching search results.

<html>
<script src=”ajax.js” language=”javascript”></script>
<script src=”ajaxsearch.js” language=”javascript”></script>
<body>
<form action=”BookDetails” name=”book”>
Enter Search value : <input type=”text” name=”searchtext” value=”” onkeyup=”showSearchItems(this.value)”/>
</form>
<div id=”showdetails”>
</div>
</body>
<script>
function showSearchItems(val)
{
sendAjaxSearchRequest(“\BookDetails”, “showdetails”);
}
</script>
</html>

Script File : ajaxsearch.js

function sendAjaxSearchRequest(url, divid)
{
url = url + getNoCacheValue(url);
var req = getXMLHttpRequest();
req.onreadystatechange = function(){ processResponse(req, divid) };
req.open(’GET’, url, true);
req.send(null);
}

function processResponse(req, divid)
{
if (req.readyState == 4) {
if (req.status == 200) {
var response = req.responseXML;
var tags = response.getElementsByTagName(BookDetails)[0];
var result = “”;
for(i=0; i<tags.length; i++)
{
var bookdet = tags[i];
var bookname = bookdet.childNodes[0].firstChild.data
result += “<div>”+bookname+”</div>”;
}
document.getElementById(divid).innerHTML = result;
}
}
}

onkeyup – is one of the property of  html tags. method specified in this property gets fired when you type any characters in the search input box. In our example javascript method showSearchItems called and this should produce the search results for your entered search input.

Ajax Basics – https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/
Ajax Example – https://manikandanmv.wordpress.com/2008/09/29/ajax-example/