aspose file tools*
The moose likes Struts and the fly likes Struts+Ajax+Database Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Frameworks » Struts
Bookmark "Struts+Ajax+Database" Watch "Struts+Ajax+Database" New topic
Author

Struts+Ajax+Database

khizar dheen
Greenhorn

Joined: May 30, 2007
Posts: 13
I am new to struts and ajax
i want to know how the select options is working in ajax and retrieve values from database.suppose i am selecting country (usa) under that what are the states in usa is displayed in another select box

anybody having sample code for that application

Kindly suggest me how to do it
i have done but it is wrong,i do no this is correct or not

myform bean class:
package jobportal.struts.actionform;

import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;

public class StateForm extends ActionForm{

private String state;
private String city;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}

public void reset(ActionMapping mapping,HttpServletRequest request){
state="";
city="";
}

}
My action class:
package jobportal.struts.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jobportal.actions.AjaxActions;

import jobportal.beans.*;
import jobportal.constants.JobPortalConstants;

import jobportal.struts.actionform.StateForm;

import org.apache.log4j.Logger;
import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class AjaxAction extends Action{

public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {

/* Declaring Action Messages class and object */

ActionMessages message = new ActionMessages();
String optionSelected = request.getParameter("optionSelected");

try {
StateForm stateForm=(StateForm)form;
String path = this.getServlet().getServletContext()
.getRealPath("/");


ArrayList state=new ArrayList();
ArrayList ajax1=new ArrayList();
ArrayList ajax2=new ArrayList();
AjaxActions ajaxactions=new AjaxActions(stateForm);
ajax1=ajaxactions.ShowStateDetails(request, path);
ajax2=ajaxactions.ShowCityDetails(request, path);
if (ajax1 != null) {
request.setAttribute("Ajax1", ajax1);
}

if (ajax2 != null) {
request.setAttribute("Ajax2", ajax2);
}


} catch (Exception e) {
System.out.println("AjaxActionPage" + e);
java.io.StringWriter sw = new java.io.StringWriter();
java.io.PrintWriter pw = new java.io.PrintWriter(sw);
e.printStackTrace(pw);

} finally {
}
return mapping.findForward("Ajax");
}

}

my Dao class:
package jobportal.actions;

import java.sql.ResultSet;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import com.pgcinfotech.db.SQLExecuter;
import jobportal.beans.State;
import jobportal.constants.JobPortalConstants;
import jobportal.struts.actionform.StateForm;

public class AjaxActions {

private String path;

private StateForm stateForm;

public AjaxActions() {
}

public AjaxActions(StateForm stateForm) throws Exception {

}
public ArrayList ShowStateDetails(HttpServletRequest request,String path)throws Exception
{

SQLExecuter sqlExe = new SQLExecuter(path,
JobPortalConstants.DATA_SOURCE_KEY);

ArrayList arraylist = null;
try{

ResultSet rs = sqlExe.executeSql2("ShowState", new String[0]);

arraylist = new ArrayList();
while (rs.next()) {

String State=rs.getString(1);
State state=new State();
state.setState(State);
arraylist.add(state);

}
sqlExe.closeConnection();
} catch (Exception e) {
System.out.println("AjaxStateActionsexception" + e);
sqlExe.closeConnection();
throw e;
}
return arraylist;

}
public ArrayList ShowCityDetails(HttpServletRequest request,String path)throws Exception
{

SQLExecuter sqlExe = new SQLExecuter(path,
JobPortalConstants.DATA_SOURCE_KEY);

ArrayList arraylist = null;
try{

ResultSet rs = sqlExe.executeSql2("ShowCity", new String[0]);
arraylist = new ArrayList();
while (rs.next()) {
State state=new State();
String City=rs.getString(1);
state.setCity(City);
arraylist.add(state);

}
sqlExe.closeConnection();
} catch (Exception e) {
System.out.println("AjaxCityActionsexception" + e);
sqlExe.closeConnection();
throw e;
}
return arraylist;

}
}

ajax.jsp:::::::


<script lang="javascript">
var req;
/*
* Get the second options by calling a Struts action
*/
function retrieveSecondOptions(){

firstBox = document.getElementById('firstBox');

//Nothing selected
if(firstBox.selectedIndex==0){
return;
}
selectedOption = firstBox.options[firstBox.selectedIndex].value;
//get the (form based) params to push up as part of the get request
url="AjaxAction.do";

//Do the Ajax call
if (window.XMLHttpRequest){ // Non-IE browsers
req = new XMLHttpRequest();
//A call-back function is define so the browser knows which function to call after the server gives a reponse back
req.onreadystatechange = populateSecondBox;
try {
req.open("GET", url, true); //was get
} catch (e) {
alert("Cannot connect to server);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = populateSecondBox;
req.open("GET", url, true);
req.send();
}
}
}

//Callback function
function populateSecondBox(){
document.getElementById('secondBox').options.length = 0;

if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
textToSplit = req.responseText
if(textToSplit == '803'){
alert("No select option available on the server")
}
//Split the document
returnElements=textToSplit.split("||")

//Process each of the elements
for ( var i=0; i<returnelements .length; i++ ){
valueLabelPair = returnElements[i].split("|")
document.getElementById('secondBox').options[i] = new Option(valueLabelPair[0], valueLabelPair[1]);
}
}
} else {
alert("Bad response by the server");
}
}
}
</script>

my jsp page::::

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>

<%@ taglib uri="/tags/struts-html" prefix="html"%>
<%@ taglib uri="/tags/struts-bean" prefix="bean"%>
<%@ taglib uri="/tags/struts-logic" prefix="logic"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Check</title>
</head>
<body>
<%@include file="/jsp/Ajax.jsp" %>
<html:form action="State" method="post">
<tr>
<td><label for="first"><bean:message key="ajax.state"/></label></td>
<td>
<!--On change the function retrieveSecondOptions() is called to populate the second box -->
<html:select property="state" onchange="retrieveSecondOptions()" styleId="firstBox" styleClass="mandatory">
<html ptions collection="Ajax1" property="state" labelProperty="state"/>
</html:select>
</td>
</tr>
<tr>
<td><label for="second"><bean:message key="ajax.city"/></label></td>
<td>
<html:select property="city" styleId="secondBox" styleClass="mandatory">
<html ption value="nothing">-First choose above-</html ption>
</html:select>
</td>
</tr>
</html:form>
</body>
</html>

kindly suggest me how to do further
any help advance thanks
khizar dheen
Greenhorn

Joined: May 30, 2007
Posts: 13
No one know ahax with struts help me

Advance Thanks
Kizar
Nick Williamson
Ranch Hand

Joined: Jan 06, 2007
Posts: 73
When I've used ajax with strus I used AjaxTags framework.

http://ajaxtags.sourceforge.net/

it's really nice and most work both in firefox and ie. You can download the war file and run it locally, all the docs and source is there with examples. It's got the two select like you said you were using.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Struts+Ajax+Database