Archive for the ‘HTML’ 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


Advertisements

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/

Efficient Javascript Programming

May 29, 2010

I am not an expert in Javascript. Though, I can share some points which are more significant when you use javascript in your applications.

  • Cache element property when access multiple times. In DOM, it’s an extensive search of the element to find the same property over and over again. Perfect example is document object

var divelt = document.getElementById(“div1”);
var img = document.getElementByTagName(“img”);

instead use

var doc = document
var divelt = doc.getElementById(“div1”);

  • Use Local variables rather than Global variables, because local variables are fast, global variables are little performance penalty.

for(i=0; i < array.count; i++){
alert(“array data : ” +array[i]);
}

store array.count into local variable like count = array.count and use it.

for(i=0; i < count; i++){
alert(“array data : ” +array[i]);
}

  • Don’t use eval() when not necessary
    • eval statement is expensive in terms of performance
    • eval parameters are executed dynamically. So it’s hard to understand the program and the program is not more reliable.
  • Don’t wrap try/catch within loops. – Every catch statement, javascript creates dynamically scope.
  • Don’t pass function as a string to setTimeout()setTimeout(“myFunction()”,””) – Internally this will use eval statement instead use function reference like setTimeout(myFunction,….).
  • Don’t use symbol + for concatenating strings, use String.concat() or Array.join
  • Don’t use function constructor like new Function() –  as equal to eval method.
  • Don’t use “with” statement. – Used to define the new scope of the element. It is more expensive to look up variables in other scope.

with(document.getElementById(“divid”).style){
color = ‘#fff’;
width = ‘150px’;
backgroundcolor =’#000′;
}

Javascript has better alternatives for this.

var divobj = document.getElementById(“divid”);
divobj.style.color = ‘#fff’;
divobj.style.width = ‘150px’;
divobj.style.backgroundcolor = ‘#000’;

  • Cache offsetHeight/offsetWidth before using computation – Every time there is an internal re-flow happening

Re-flow happens at Initial page load, Browser window resize, Layout style changes, Add/Remove DOM nodes.

  • Use innerHTML to insert the element into the node

Getting Iframe content in Javascript

November 6, 2009

Iframe is an inline frames, allow you to load the separate html file into an existing document. You can also load the file dynamically with “src” attribute. Suppose there is a need to get the iframe content and process it using javascript. The following example helps you to do it and this has been a cross browser solutions for Firefox & IE browsers.
Let’s load a simple html file inside the iframe, and get that file content with javascript method getIframeContent.

GetIframeDetails.html


<html>
 <body>
 <iframe id="testFrame" src="FrameContent.html" >
 </iframe>
<a href="#" onclick="getIframeContent('testFrame');">Get the content of Iframe</a>
 </body>
<script>
 function getIframeContent(frameId){
 var frameObj = document.getElementById(frameId);
 var frameContent = frameObj.contentWindow.document.body.innerHTML;
 alert("frame content : "+frameContent);
 }
 </script>
 </html>
 

FrameContent.html


<html><body>
 <div id="testFrameContent" style="border:1px;">
 This is simple HTML file which is loaded inside the iframe.
 </div>
 </body>
 </html>

what getIframeContent method do?


function getIframeContent(frameId){
 var frameObj = document.getElementById(frameId);
 var frameContent = frameObj.contentWindow.document.body.innerHTML;
 alert("frame content : "+frameContent);
 }

  • getElementById(frameId) – get the object reference of iframe
  • contentWindow – is a property which returns the window object of the iframe
  • contentWindow.document – returns the document object of iframe window.
  • contentWindow.document.body.innerHTML – returns the HTML content of iframe body.

You can also access any tag element’s inside the iframe. This can be done by processing with tag names/ids. Let’s imagine the use case: to retrieve the content of div element inside the iframe. Below statement will retrieve it.

frameObj.contentWindow.document.getElementById(“testFrameContent”).innerHTML

Blogs about dynamically change the iframe heights.

https://manikandanmv.wordpress.com/2009/05/25/version-2-dynamically-change-iframe-heights/
https://manikandanmv.wordpress.com/2009/04/25/dynamically-change-iframe-heights/

Version 2 : Dynamically change IFrame Heights

May 25, 2009

This is a continuation of my previous blog. Dynamically change IFrame Heights – here loaded a static HTML content on iframes.
In version 2, we have loaded dynamic files inside the iframes. At the same time we have to dynamically change the height of iframes based on their loaded file content.

Sample Code

Below code works well in both browsers Firefox & Internet Explorer.

<html>
<body>
<script>
function setIframeHeight()
{
    var elt = document.getElementById('testIframe');
    if(elt.contentWindow){
        document.getElementById('testIframe').height = elt.contentWindow.document.body.scrollHeight + 30;
    }
}
</script>


</body>
</html>

contentWindow

  • returns an window object of the iframe.

scrollHeight

  • is a property which returns the scrolling height of the object.
  • the value specifies only the visible height of the object.

elt.contentWindow – returns the object of IFrame window.
elt.contentWindow.document – returns the object of HTML document.
elt.contentWindow.document.body – returns the object of HTML body element.

You may also use contentDocument property for getting height of iframe. This will work only in Firefox. Since IE6.0 or 7.0 does not support this property. This has been supported from IE version 8.0

Sample code for doing the same in Firefox with contentDocument

if(elt.contentDocument){
elt.height = elt.contentDocument.body.offsetHeight+40;
}

contentDocument

  • returns an object of iframe document.

offsetHeight

  • is a property used to retrieves the height of the element/object in pixels.
  • this value includes the height of elements borders + padding.

How to open Ajax Page in Browser New Tab

May 18, 2009

It’s not easy task to support both “Load a web page using Ajax” and “Allow to open the same page in browser new tab”. Because we have to manually handle the second option. Let’s see how to solve this task.
Before proceeding, first you have to know why ajax web pages are not able to support the second option.
Reason : when you click a web page link, it will just invoke a javascript method specified in onclick event which loads the page through ajax requests. So here “href” attribute of anchor tag is either empty or “javascript:void(0);”. Due to this we are not able to open the page in new tab.

Sample code for achieving both the actions

  • ajax page load
  • the same page should be able to open in Browser New Tab by using “Open Link in New Tab” option.

Two operations handled in the web page links(anchor tags),

  • invoke the method showPage when u click the link. which means simply onclick event gets fired.
  • if u open the same link in new tab, the below sequence of actions will execute.
    • # part of href(say, #/blogs/JSON/json-basics.html) has appended to the browser url
    • showtab method has invoked beco’z the main page gets loaded. rest will take care of the method showtab

main page should be like this.

<html>
<body>
<a href="#/blogs/JSON/json-basics.html" onclick="showPage('/<span style="color:#000000;">blogs</span><span style="color:#000000;">/JSON/json-basics.html');">JSON Basics</a>
<a href="#/</span><span style="color:#000000;">blogs</span><span style="color:#000000;">/ajax/ajax-basics.html" onclick="showPage('/</span><span style="color:#000000;">blogs</span><span style="color:#000000;">/ajax/ajax-basics.html');">Ajax Basics</a>
<a href="#/</span><span style="color:#000000;">blogs</span><span style="color:#000000;">/html/html-basics.html" onclick="showPage('/</span><span style="color:#000000;">blogs</span><span style="color:#000000;">/html/html-basics.html');">HTML Basics</a></span>

<span style="color:#000000;">
<div id="showhelp"></div>
<!-- This div is the Common Dynamic Area, this area gets changed based on clicking the above link --></span>

<script>
showtab();
/* this method gets executed everytime when a page loads.
what this method does,
just get the full url from the browser address bar.
parse the url and get the exact "new page url" which is available after the symbol "#"
and send the "new page url" via ajax request.
*/

function showtab()
{
var url = document.location.href;
var index = url.indexOf("#");
var taburl = "";
if(index>0){
var taburl = url.substring(index+1);
}
sendAjaxRequest(taburl, "showhelp");
}

function showPage(url)
{
sendAjaxRequest(url,"showhelp");
}

function sendAjaxRequest(url, divid)
{
var req = <a href="https://manikandanmv.wordpress.com/2008/09/29/ajax-example">getXMLHttpRequest</a>();
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) {
document.getElementById(divid).innerHTML=req.responseText;
}
}
}

</script>
</body>
</html>

Are you new to Ajax..? Read the below posts for learning basics.

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/

Dynamically change IFrame Heights

April 25, 2009

With script you can able to change/set the iframe attribute values dynamically. Sometimes we don’t know the actual height of the web page because page gets loaded dynamically and the height may varies. So here i have to calculate the page content height dynamically and set the same value in iframe height property. Mainly this is required when a page loads dynamically inside the iframe and its height can adjust automatically based on the content.(which means to show iframe without vertical scroll bar).

Sample Code


<html>
<body>
<div id=”showid”>
<table>
<tr><td>
Enter your name <input type=”text” name=”yourname”/>
Enter your age <input type=”text” name=”yourage”/>
<input type=”submit” name=”Submit”/>
</td></tr>
</table>
</div>

<script>
function setIframeHeight()
{
document.getElementById(‘testIframe’).height = document.getElementById(‘showid’).offsetHeight;
}
</script>

<iframe src=”” name=”testIframe” id=”testIframe” onload=”setIframeHeight();” />
</body>
</html>

offsetHeight

  • is a property used to retrieves the height of the element/object in pixels.
  • this value includes the height of elements borders + padding.

How it works.?

Browser rendering a page by reading each HTML tags, scripts are loaded first. When the control comes to iframe tag, we have specified an event called onload and the value setIframeHeight() method gets invoked. In this method we get the height of the page which is rendered inside the div element and set the same in iframe height.

Like this you can set the value of any iframe attributes.

document.getElementById(‘testIframe’).width = 100;
document.getElementById(‘testIframe’).scrolling = “yes”
document.getElementById(‘testIframe’).class= “css_classname”;

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/

How to Show or Hide the HTML elements

November 6, 2008

In a web page you can able to show or hide the HTML elements using javascipt. Very simple, see below example of how to do it.

sample.html

<html>
<body>
<p><a href=”#” onclick=”showDetails(‘showid’)”>Show Details</a></p>
<p><a href=”#” onclick=”hideDetails(‘showid’)”>Hide Details</a></p>
<!–  set attribute id for div elements, because using this we will show or hide the below table –>
<div id=”showid”>
<table>
<tr><td> <!— am writing sample code here  –>
Enter your name <input type=”text” name=”yourname”/>
Enter your age <input type=”text” name=”yourage”/>
<input type=”submit” name=”Submit”/>
</td></tr>
</table>
</div>
</body>
</html>

javascript method
<script>
function showDetails(divid)
{
document.getElementById(‘showid’).style.display=”;
}
function hideDetails(divid)
{
document.getElementById(‘showid’).style.display=’none’;
}
</script>
style – is an attribute of div element tag. Eg: <div style=”display:none;color:blue”/>

using this attribute we will show or hide the HTML elements.

document.getElementById(divid).style.display

document.getElementById(divid) – will return the div element as object. with that object you can access the attribute style and property display. Property display has several values like block, none, inline with these values you can do the necessary actions.  Do you want more details about display property values read here http://www.w3schools.com/htmldom/prop_style_display.asp