Sunday, August 8, 2010

Simple AJAX Application with Select Box in JSP

Hi,

I will demonstrate how to develop a simple AJAX Application for beginners

In the context of fast rendering of the screen without refreshing, the AJAX comes into picture. In scenarios, like
on selecting one select box another select box has to populated by making a AJAX call to server, I will show you how to achieve it.

Step 1 : Servlet class
1) Prepare a Java servlet class Let's say GetDataServlet with necessary methods which we need to make a call
2) You need to use out.print() to construct the response
3) prepare the servlet-mapping and servlet in web.xml let's say as getData

Step 2 : JSP
1) Construct the jsp. Here I have 2 select boxes. one which is already populated using bean and second one to be done using AJAX
sample code for select box 1
<select name="loginNameSelect" id="loginSelect" onchange="change()">
<% ModelUtility modelUtil = new ModelUtility();
List<String> uList = modelUtil.getUserList();
Iterator itr = uList.iterator();
while(itr.hasNext()){
String val = (String)itr.next();
%>
<option value=<%=val%>><%=val%></option>
<% } %>
</select>
In my case I have ModelUtility bean, which returns me the list of users

sample code for select box 2

%<select name="ajaxPopulate" id="ajaxPopulate"%>%</select%>

Step 3 Javascript

If you see, I have attached a javascript function for onchange event on select box 1. Here is where we make a AJAX call to our servlet (GetDataServlet).
Once we make a call to server, the response will be returned in xmlhttp response either as simple text or XML which ever fromat we outputted in servlet
Here you can parse the response and construct the elements of select box 2
Sample code goes like this
function change()
{
var answer = document.getElementById('loginSelect').value;
var http = new XMLHttpRequest();
var url = "getData";
var params = "loginName="+answer;
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
var responseString = http.responseText;
var arrUsers = responseString.split(',');
var select = document.getElementById("ajaxPopulate");
select.options.length = 0;
for(var i=0;i var d = arrUsers[i];
select.options.add(new Option(d, i))
}
}
}
http.send(params);
}

With this the data gets populated by making a call to getDataServlet

I am available for any clarification

A Ram Prasad

Saturday, July 24, 2010

Java Threading Learnings

When creating threads, there are two reasons why implementing the Runnable interface may be preferable to extending the Thread class:

* Extending the Thread class means that the subclass cannot extend any other class, whereas a class implementing the Runnable interface
has this option.
* A class might only be interested in being runnable, and therefore, inheriting the full overhead of the Thread class would be excessive.

JSP Learnings

Hi,

JSP :

JSP is a way of developing the UI where we can embed Java Code in HTML and make use of beans

To write Java Code, We need to embed the code inside <% and %> which we call them as scriptlets

<%@ -- page directive
used to import files, include pages
e.g.,<%@page language="java" import="java.sql.*,mypackage.myclass" %> ,
<%@ include file="/header.jsp" %> ,
<%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>

<%! -- delcaration
used to declare some Java Methods at the start of jsp

To write HTML Code, We need to output using out.println("test") or we can use <%=<variablename< which internally converts that into out.println and prints output

If you want to use a Java Bean inside Jsp use jsp:useBean

<jsp:useBean id="user" class="user.UserData" scope="session"/>

setProperty sets all the properties value taken from the form directly into the bean id provided. Here it is "user" bean
The only condition for this to happen automatically is, the getters and setters defined in java bean file must be same as fieldName
For example: if there is field firstName then the bean should have setFirstName and getFirstName

<jsp:setProperty name="user" property="*"/>

summary of jsp tags :

jsp:include
The jsp:include action work as a subroutine, the Java servlet temporarily passes the request and response to the specified JSP/Servlet. Control is then returned back to the current JSP page.

jsp:param
The jsp:param action is used to add the specific parameter to current request. The jsp:param tag can be used inside a jsp:include, jsp:forward or jsp:params block.

jsp:forward
The jsp:forward tag is used to hand off the request and response to another JSP or servlet. In this case the request never return to the calling JSP page.

jsp:plugin
In older versions of Netscape Navigator and Internet Explorer; different tags is used to embed applet. The jsp:plugin tag actually generates the appropriate HTML code the embed the Applets correctly.

jsp:fallback
The jsp:fallback tag is used to specify the message to be shown on the browser if applets is not supported by browser.
Example:
<jsp:fallback>
<p>Unable to load applet</p>
</jsp:fallback>

jsp:getProperty
The jsp:getProperty is used to get specified property from the JavaBean object.

jsp:setProperty
The jsp:setProperty tag is used to set a property in the JavaBean object.

jsp:useBean
The jsp:useBean tag is used to instantiate an object of Java Bean or it can re-use existing java bean object.


A Ram Prasad

Saturday, July 17, 2010

Hibernate No CurrentSessionContext Exception

Hi

While starting hibernate you might get the following exception

org.hibernate.HibernateException: No CurrentSessionContext configured!

The reason for the above error is the property "current_session_context_class" is missing

The solution you need to follow is to add
<property name="current_session_context_class">thread</property>
in the hibernate.cfg.xml file

A Ram Prasad

Adding a custom jar to maven-repo effectively

Hi

Maven gives a wonderful way to add custom jars to maven-repo and make use of the jar in the project. Here is how it is :

If You have a jar not available in maven repository but it is needed for your project
thereby when maven build your project, you want maven to pick from the local repository instead of downloading it from the web or maven URL (http://repo1.maven.org/maven2/)

For Example :

I have a hibernate-jpa-custom jar which i want to use the jar available with me while doing maven build

Steps to follow that:

1) First install the jar into local maven-repository using

mvn install:install-file -DgroupId=org.hibernate -DartifactId=hibernate-jpa-custom -Dversion=2.0 -Dpackaging=jar -Dfile= -DgeneratePom=true


Going by the command :

groupId - denotes the group of the artifact
artifactId - name of the artifact
version - version of the artifact which you want to use in your project
file - the jar library
generatePom - to generate pom for the jar file automatically
this option is very important in order to avoid errors like

[INFO] Copying 0 resource
Downloading: http://repo1.maven.org/maven2/org/hibernate/hibernate-jpa/2.0/hibernate-jpa-2.0.pom
[INFO] Unable to find resource 'org.hibernate:hibernate-jpa:pom:2.0' in repository central (http://repo1.maven.org/maven2)

Since there is no pom available to look in the local repository, maven tool assumes that there is no jar in local repository and has to contact maven repo URL to download the jar thereby showing the error message "unable to download"

2) make a entry in the pom.xml of your project for the jar which you just added to local maven repo
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-jpa-custom</artifactId>
<version>2.0</version>
</dependency>

3) use mvn install to do a install of the project with newly added jars

Now your project will make use of the custom jar

let me know in case of any queries

Thank You
Ram Prasad

Sunday, June 20, 2010

JSF Deployment Error in Eclipse IDE

Hi

In JSF I got the error while deploying a JSF Application on tomcat server using eclipse's Run As -- > on a server

SEVERE: Exception sending context initialized event to listener instance of class com.sun.faces.config.ConfigureListener
java.lang.NoClassDefFoundError: javax/faces/component/html/HtmlColumn
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at com.sun.faces.config.ConfigureListener.configure(ConfigureListener.java:859)
at com.sun.faces.config.ConfigureListener.configure(ConfigureListener.java:910)
at com.sun.faces.config.ConfigureListener.configure(ConfigureListener.java:379)
at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:306)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3843)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4342)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)

Solution :

The solution for above kind of errors are tricky to find since we will be in a state that we provide jsf jars required to run but still the error props up.

The reason is, in eclise when we run as on a server, server while running the application makes use of the jars which we provide. There might be a case we are missing the libraries provided to the server run-time

please check that and it will be running normal

A Ram Prasad

Saturday, June 19, 2010

A Beginner's Help Point to JSF Application using Eclipse IDE

Hi All

I started making use of the JSF application components and libraries to develop a web 2.0 UI making use of the latest technologies like Hibernate, Spring

I would like to share my experiences while learning these technologies.

To Start with, We need the following environment and libraries to start a JSF project

Environment :
1) JDK 1.5 or higher is fine
2) Eclipse IDE Eclipse Galileo,better 3.3 or higher version
3) JSF jar files (jsf-api.jar,jsf-impl.jar)
4) Apache Tomcat 6.0.18
5) JSP (tm) Standard Tag Library 1.2 implementation (jstl.jar)

Steps

1) Make the Web Page Editor the default editor for JSP pages

The JSF Tools Project-contributed Web Page Editor (WPE) is NOT registered as the default editor for JSP files. You can make the WPE the default editor for JSP files by following these steps:
• Navigate to "Window" -> "Preferences..." -> "General" -> "Editors" -> "File Associations"
• In the "File types" section, select "*.jsp"
• In the "Associated editors" section, select "Web Page Editor"
• Select the "Default" button

2) Register JSF libraries (jsf-api.jar,jsf-impl.jar)

We will be creating a library containing the Sun JSF Libraries
Select Windows->Preferences->Web and XML->->JavaServer Faces Tools->Libraries. Click on the New.. button to add a new library. Create the JSF Libraries as shown in the following figures



3) In similar fashion register the jstl libraries (jstl.jar)

4) In Eclipse, Create a new dynamic web application and in the options that come on the screen you can select the configuration as JSF v1.2 project which creates some dafult files required for any JSF Application
The screenshot that shows while configuring a dynamic web application is given below:



In a step to select libraries, provide the jsf libraries which we already created in earlier steps. Click Finish

Now the JSF Project Template is ready and you can start writing JSF Applications

Let me know if anyone faces any problem while configuring

more updates to come

Thank You
A Ram Prasad

Saturday, June 12, 2010

vipassana meditation

Hi

I was not at all available last 2 weeks.

Decided to go and give a humble and honest effort towards meditation a technique which helps you to know yourself and relax yourself from all your material miseries

Gave myself a full 2 weeks course for a disciplined meditation. attended vipassana meditation , a wonderful technique to know thyself

It is completely a 10-day long residential course

It is a really a wonderful experience and recommend everyone to attend the course

The details are fully available at http://www.dhamma.org/en/schedules/schpaphulla.shtml

I will be updating more and more in coming days

A Ram Prasad

Friday, May 28, 2010

Samsung Corby pro review & some tips

Hi

I bought a samsung corby pro mobile recently and like to give my inputs of the same
Firstly, this mobile has nice features infact most features of high-end mobiles available in this phone. A good product from samsung family

corby is going to bring huge profits for samsung in Indian Market

Some Good Features :
1) A lot of widgets
2) Qwerty keypad
3) All available technologies like 3G,GPRS,Wi-Fi

Disadvantages
1) Touch screen not that comfortable.may be it will be same with all high-end phones
2) You get the applications from getjar only and not all the applications are immediately accepted by corby pro
3) Kies software which they provide with kit doesn't seem to work always

These are some tips to make the best use of corby pro
1) set-up wifi connection
Go to Menu-->wifi
tap on wi-fi to enable WIFI signal from your mobile
tap search which searches for wi-fi networks
shows the list of wi-fi connections available
Go to the Network Key and enter the password for wi-fi
select the protocol as HTTP
Save the Details and Connect to Internet adn start browsing

2)There is one uncomfortable feature in corby pro, where the profiles looks like, we can use only samsung provided like Normal,Silent...
In normal sound comes up which may distract you and others. To reduce the sound on the left hand side, the volume up/down can be used to mute the sounds

3)Many might be wondering how to insert the number while sending messages
Tap on messages-->create Message
Tap on the message section where message is typed
Now Tap on the more option --> Insert --> Name card
brings up the contact list to select and gets inserted in the message upon selection


Hope above information helps some of you. see more updates in the future

A Ram Prasad

Sunday, March 15, 2009

Welcome message

Hi Friends , I am happy to finally kick-start the blogging activity which i used to think every time when i access some public blogs which found to be very useful to me. I would also be a author of something and may be helpful to someone in some way. ok..Too much crap intro.. :) The day has arrived and decided to start..

I am not very good at english grammar..kindly ignore and suggest if you find any mistake

This will be a blog where you can find my personal experiences ranging from Location updates,travel,leisure,fun,SocialActivity and so on and also last but not the least some good technical stuff.

Keep watching this blog regularly for some exciting stuff.