Ajax in struts
Hi,
i need your help on ajax with struts.
what i did is i have a 3 text box with two button what i want to do is, in page load i want disable 2 textbox and one button. i enter a value in the 1st textbox then after press the button that button become disable and the value shuld be inserted in the data base and also enable the remaining text box and button .
I suggest the DWR (direct web remote) ajax library. It's struts-compatible and turns any java to javascript easily.
Similar Messages
-
Using ajax with struts 1.2.9
Hello Experts ,
First of all I am sorry if I have posted question in a wrong forum but I have tried posting my problem in struts forum also but didn't get reply & I am pretty new to struts.
I am trying to use ajax in struts 1.2.9.I have used 1 dependent combo.When I am changing value in 1 combo it will call an action class which will fetch data for 2nd combo .My problem is ,action class "success" has to be forwarded to some particular jsp.But I want to refresh only a part of page not the whole page.How to refresh just a part of page?? Any idea or any link which can help me.Any help in this will be highly appreciated.Many many Thanx in advance.Hello Shasi,
Lets take the sample code for one combo box (College) , one change of which I want to display the information of that college in the textboxes below it.So on change of college combo I am calling the action class which is retrieving info of college.My problem is now how to send this data to jsp & what should be the success & failure forward for my action class.
In my JSP I have written something like this....
createXMLHttpRequest();
queryString2 ="retrieve_college_info.do?";
queryString2 = queryString2 + "selcollege="+document.forms[0].college_name.options[document.forms[0].college_name.selectedIndex].value;
xmlHttp.open("GET", queryString2, true);
xmlHttp.onreadystatechange = handleCollegeRetrieve;
xmlHttp.send(null);My action class code goes like this
package ibm.tgmc_nextyear.actionclass;
import ibm.tgmc_nextyear.businesslogic.*;
import ibm.tgmc_nextyear.formbean.*;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import java.sql.*;
import java.util.ArrayList;
import org.apache.struts.util.LabelValueBean;
public class CollegeRetrieveInfoAjaxAction extends org.apache.struts.action.Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String optionSelected = request.getParameter("selcollege");
String responseText="";
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
TeamDetailsForm team_frm = null;
try {
conn = getDataSource(request).getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery("select name , address , city , pincode , ph_no , hod_name , principal_name , alt_no , website from user.college_table where college_id=" + optionSelected);
*//what after this ???*
} finally {
if (rs != null) {
rs.close();
if (stmt != null) {
stmt.close();
if (conn != null) {
conn.close();
*//what should be the value os success forward*
return(mapping.findForward("success"));
} -
Uploading a file to server using ajax and struts
My problem is i wrote a program to upload a file to the server using Ajax.
Here iam used Struts and Ajax.
The problem is when iam uploaded a file from my PC the file is uploading to the server in the upload folder located in the server my system.
Iam using Tomcat server 5.0
But when iam trying to access it through other system it is not doing so
Giving an internal server error i,e 500.
Iam putting the necessary documents for ur reference.
Plz help me soon .
My exact requirement is i have to upload a file to the upload folder located in the server.
And i have to get the path of that file and display the file path exactly below the browse button from where iam uploaded a file.
That should be done without page refresh and submit thats y iam used Ajax
Any help would greatly appreciated
Thanks and Regards
Meerasaaheb.
The action class is FilePathAction
package actions;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class FilePathAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
String contextPath1 = "";
String uploadDirName="";
String filepath="";
System.out.println(contextPath1 );
String inputfile = request.getParameter("filepath");
uploadDirName = getServlet().getServletContext().getRealPath("/upload");
File f=new File(inputfile);
FileInputStream fis=null;
FileOutputStream fo=null;
File f1=new File(uploadDirName+"/"+f.getName());
fis=new FileInputStream(f);
fo=new FileOutputStream(f1);
try
byte buf[] = new byte[1024*8]; /* declare a 8kB buffer */
int len = -1;
while((len = fis.read(buf)) != -1)
fo.write(buf, 0, len);
catch(Exception e)
e.printStackTrace();
filepath=f1.getAbsolutePath();
request.setAttribute("filepath", filepath);
return mapping.findForward("filepath");
the input jsp is
filename.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
<script type="text/javascript">
alertflag = false;
var xmlHttp;
function startRequest()
if(alertflag)
alert("meera");
xmlHttp=createXmlHttpRequest();
var inputfile=document.getElementById("filepath").value;
xmlHttp.open("POST","FilePathAction.do",true);
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.send("filepath="+inputfile);
function createXmlHttpRequest()
//For IE
if(window.ActiveXObject)
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
//otherthan IE
else if(window.XMLHttpRequest)
xmlHttp=new XMLHttpRequest();
return xmlHttp;
//Next is the function that sets up the communication with the server.
//This function also registers the callback handler, which is handleStateChange. Next is the code for the handler.
function handleStateChange()
var message=" ";
if(xmlHttp.readyState==4)
if(alertflag)
alert(xmlHttp.status);
if(xmlHttp.status==200)
if(alertflag)
alert("here");
document.getElementById("div1").style.visibility = "visible";
var results=xmlHttp.responseText;
document.getElementById('div1').innerHTML = results;
else
alert("Error loading page"+xmlHttp.status+":"+xmlHttp.statusText);
</script></head><body><form name="thumbs" enctype="multipart/form-data" method="post" action="">
<input type="file" name="filepath" id="filepath" onchange="startRequest();"/>
</form>
<div id="div1" style="visibility:hidden;">
</div></body></html>
The ajax response is catching in a dummy.jsp
<%=(String)request.getAttribute("filepath")%>
corresponding action mapping
<action path="/FilePathAction" type="actions.FilePathAction">
<forward name="filepath" path="/dummy.jsp"/>
</action>
So plz help me to upload a file to the server from any PC.
Iam searched alot but didnt get any solution.Plz help me soon if it possible so
Iam in great need.
I have worked alot but not worked out.
Any help greatly appreciated -
I want to use Ajax in my struts framework.Can anyone please suggest me how
to do this
Thankshttp://www.google.com/search?hl=en&q=ajax+struts&btnG=Google+Search
-
Problem if i use ajax in struts
hi,
i am working on struts, now i got one problem if i use ajax in jsp.
In my jsp page i have two dropdown lists, according to the first dropdown value second dropdown result will getting from the database by calling an action class.
but my requirement is for getting the second dropdown result page should not be refresh for this i am using ajax.
in ajax how can we call one action class what should we return in actionmapping.
If any one already written some code for this please send it to me.
please can anyone help on this its very urgent for me.Hi
First of all you have to write on fnRetrieveURL which will be responsible for getting the connection and XML communication.
function fnRetrieveURL(strURL, strFnProcessStateChange)
if(window.XMLHttpRequest)
varXMLrequest = new XMLHttpRequest();
varXMLrequest.onreadystatechange = eval(strFnProcessStateChange);
try
varXMLrequest.open("POST",strURL,true);
catch(Exception)
alert("Problem in Getting data ");
varXMLrequest.send(null);
else if(window.ActiveXObject)
varXMLrequest = new ActiveXObject("Microsoft.XMLHTTP");
if(varXMLrequest)
varXMLrequest.onreadystatechange =eval(strFnProcessStateChange);
varXMLrequest.open("POST",strURL,true);
varXMLrequest.send();
}This method will be called in user written method in which request will be submitted to action class.
function fnGetAreaForRegion()
var iRegion = document.getElementById("region").value;
var strURL = "../getAreaForRegion.do"
strURL = strURL+"?methodName="+"getAreaForRegion";
strURL = strURL+"&controlName="+"area";
strURL = strURL+"&iRegion="+iRegion ;
fnRetrieveURL(strURL,"fnOnReturnFromRegion");
}Then there will be one on Return method i.e the method which will be called when the response will come back to JSP from fnGetAreaforRegion.
function fnOnReturnFromRegion()
if (varXMLrequest.readyState == 4)
if(varXMLrequest.status == 200)
var strSubClassValue = varXMLrequest.responseText;
if(strSubClassValue != '')
var strArray = strSubClassValue.split(",");
var iLength = strArray.length;
var strName = new Array();
var strID = new Array();
var j=0;
for(var i =0 ; i< iLength;i=i+2)
strName[j] = strArray;
j++;
var k=0;
for(var i =1 ; i< iLength;i=i+2)
strID[k] = strArray[i];
k++;
var iNewLength = strID.length;
var optnSelect = document.createElement("OPTION");
optnSelect.text = 'Select';
optnSelect.value = '';
document.getElementById("area").options.add(optnSelect);
for(var i =0 ; i< iNewLength;i++)
var optn = document.createElement("OPTION");
optn.text = strName[i];
optn.value = parseInt(strID[i]);
document.getElementById("area").options.add(optn);
Rest modification in struts-config, you can do by urself. and also you have to write one action class which will take care of parameters and all business logic.
Above code you can reuse by bit modification. Action class you have to write by your own.
let me know if you still face any issues -
Architecture question: Integrating AJAX and STRUTS
I'm slowly growing in familiarity with STRUTS and I have the basics of AJAX down, certainly as far as the request-response-parse-do something useful with the data paradigm goes.
My question is more about best practices in using an AJAX enable front-end with a STRUTS-based back-end.
In a nutshell, each user action is handled by a STRUTS action subclass. Requests are picked up by the STRUTS front controller and passed on to the handler for processing. The handler is then able to tell the controller which jsp/resource to send back to the user.
With AJAX, we are (generally) making specific data requests. We are essentially asking for data based on a set of parameters passed through on the request.
In the case of a dynamic search table (containing no business logic), the AJAX request is simply asking for a set of results that match some parameters supplied in the criteria form.
What should handle that data request?
I was thinking about a specific "data-server" set of classes which STRUTS can pass AJAX requests to.
NOTE: I'm thinking about this from the perspective of a new development, not tacking on to an existing application.
Thoughts, anyone?So let me broaden the question slightly? What are the
best practices for implementing an AJAX solution with
STRUTS? I have looked around on the net but not found
anything that constructive yet.
Suggestions and/or pointers welcome.I have played around with AJAX just to understand how the technology works and how ajax can be integrated into a j2ee (or any other for that matter) web application. I havent worked on a project which has analyzed the best practises/pitfalls of ajax and implemented a solution.
Having said that, here's my take -
Ajax, as far as I know and have seen is a 'view' thinggy - enhanced user experience, lesser clicks, blah blah. The underlying XMLHttpRequest technology is just another way to hit the server with a request. And as I said before, once the server receieves a request, it really doesnt/shouldnt matter where and how the request originated from - it could a tunelled http request (as from an applet/swing app), a normal http request from a browser or a XMLHttpRequest (read ajax). The server validates incoming params if any and performs business logic.
And here's when the similarity ends. The response (or the view) is entirely dependent on the 'requestor'. For browsers, the server would emit html, wap for cellphones, objects to a swing/applet program (possibly).
The point I am trying to make is that this (the view part) is where you'll have to concentrate on tweaking (using the so called best practises) for ajax requests. For instance, there are a set of ajax tags already that you could reuse in your jsps which help developers build cool ajax enabled apps.
(See http://ajaxtags.sourceforge.net/)
There however are a few standard best practises for using ajax itself (and this is at a general ajax as a technology level) - see for example
http://www-128.ibm.com/developerworks/library/j-ajax1/?ca=dgr-lnxw01Ajax
ram. -
How to upload a file to the server using ajax and struts
With the following code iam able to upload a file ato the server.
But my problem is It is working fine if iam doing in my system nd when iam trying to
access theis application from someother system in our office which are connected through lan
iam getting an error called 500 i,e internal server error.
Why it is so???????
Plz help me????????
It is required in my project.
I want the code to access from every system.
My exact requirement is i have to upload a file to the server and retrive its path and show it in the same page from which we
have uploaded a file.
Here the file has to be uploaded to the upload folder which is present in the server.Iam using Tomcat server.
Any help highly appreciated.
Thanks in Advance
This is my input jsp
filename.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
<script type="text/javascript">
alertflag = true;
var xmlHttp;
function startRequest(file1)
if(alertflag)
alert("file1");
alert(file1);
xmlHttp=createXmlHttpRequest();
var video=document.getElementById("filepath").value;
xmlHttp.open("POST","FilePathAction.do",true);
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.setRequestHeader('Content-Type', application/x-www-form-urlencoded');
xmlHttp.send("filepath="+file1);
function createXmlHttpRequest()
//For IE
if(window.ActiveXObject)
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
//otherthan IE
else if(window.XMLHttpRequest)
xmlHttp=new XMLHttpRequest();
return xmlHttp;
//Next is the function that sets up the communication with the server.
//This function also registers the callback handler, which is handleStateChange. Next is the code for the handler.
function handleStateChange()
var message=" ";
if(xmlHttp.readyState==4)
if(alertflag)
alert(xmlHttp.status);
if(xmlHttp.status==200)
if(alertflag)
alert("here");
document.getElementById("div1").style.visibility = "visible";
var results=xmlHttp.responseText;
document.getElementById('div1').innerHTML = results;
else
alert("Error loading page"+xmlHttp.status+":"+xmlHttp.statusText);
</script></head><body><form >
<input type="file" name="filepath" id="filepath" onchange="startRequest(this.value);"/>
</form>
<div id="div1" style="visibility:hidden;">
</div></body></html>
The corresponding action class is FIlePathAction
package actions;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class FilePathAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
String contextPath1 = "";
String uploadDirName="";
String filepath="";
System.out.println(contextPath1 );
String inputfile = request.getParameter("filepath");
uploadDirName = getServlet().getServletContext().getRealPath("/upload");
File f=new File(inputfile);
FileInputStream fis=null;
FileOutputStream fo=null;
File f1=new File(uploadDirName+"/"+f.getName());
fis=new FileInputStream(f);
fo=new FileOutputStream(f1);
try
byte buf[] = new byte[1024*8]; /* declare a 8kB buffer */
int len = -1;
while((len = fis.read(buf)) != -1)
fo.write(buf, 0, len);
catch(Exception e)
e.printStackTrace();
filepath=f1.getAbsolutePath();
request.setAttribute("filepath", filepath);
return mapping.findForward("filepath");
Action-mappings in struts-config.xml
<action path="/FilePathAction"
type="actions.FilePathAction">
<forward name="filepath" path="/dummy.jsp"></forward>
</action>
and the dummy.jsp code is
<%=request.getAttribute("filepath")%>MESSAGE FROM THE FORUMS ADMINISTRATORS and COMMUNITY
This thread will be deleted within 24 business hours. You have posted an off-topic question in an area clearly designated for discussions
about Distributed Real-time Java. Community members looking to help you with your question won't be able to find it in this category.
Please use the "Search Forums" element on the left panel to locate a forum based on your topic. A more appropriate forum for this post
could be one of:
Enterprise Technologies http://forums.sun.com/category.jspa?categoryID=19
David Holmes -
Is there good links , resources other than sun.java.com/ajax? i need to develop Ajax based report/grid control to my project.? please give resources
thanks in advanceTry to google for "ajax". What are you interested on more specifically?
-
Need help implementing AJAX in an existing Struts Application
Hi!
I am trying to implement AJAX in my existing Struts Application. I need a good approach to go ahead and implement Ajax. I was thinking.. may be i will have to club all the code in the forms n actions (in the current Struts application) to one form and action, So I can easily include the dynamic content in the page.
Please let me know if you have any ideas of how to implement AJAX in a fully developed Struts application.
Thanks,
Swapna.Hello Friends,
Check out whether the link below could be of somehelp for you folks...
http://www.it-eye.nl/weblog/2005/12/13/ajax-in-struts-implementing-dependend-select-boxes/
http://today.java.net/pub/a/today/2005/10/27/sprinkle-ajax-magic-into-struts-webapp.html
http://www.theserverside.com/news/thread.tss?thread_id=37355
http://getahead.ltd.uk/dwr/examples/lists
http://www.componentsource.com/products/backbase-ajax-struts/summary.html
http://www.jibbering.com/2002/4/httprequest.html
added to it there are few implementation frameworks which are addressing this issue you may further search on it and update abt the info which could be very much useful for all of the ppl out here.
and there is a current thread running on the same topic it'd really appriciated if u can accomadate ur posts there.
http://forum.java.sun.com/thread.jspa?threadID=784924&tstart=0
REGARDS,
RAHUL -
How Ajax works with Struts framework
How Ajax works with Struts framework .
Thanks
RamkiSo we must write file name(like abc.do), If am using struts <html:link > tag like <html:like action="abc" >Click</html:link>, so with ajax we must call like <a href ="abc.do">Click</a> .
But there is a problem, if am using ,
<servlet-mapping>
<servlet-name>MainServlet</servlet-name>
<url-pattern>/r/*</url-pattern>
</servlet-mapping>
or
<servlet-mapping>
<servlet-name>MainServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
here i am changing web.xml file based on client interest. At those situation we must change all jsp pages for <a href ="/r/abc">Click</a> .like,.
It's very difficult.
Is any other way to use ajax with Struts (Only struts tags)
Thanks
Ramki -
Hi,
Do u have any idea about Datagrid in Ajax with Struts Framework.?Hi,
For creating Java web applications with rich Datagrid, you can use any Javascript+XML component (it does not have to belong to Struts framework) . You can use one like http://www.treegrid.com -
Call struts action from javascript?
Hi all
I'm having problem already discussed here quite a lot, but I have idea to solve it different way. And need to know is it possible or I'm doing mission impossible here :(
I have JSP with 2 drop down lilsts, where the second is populated according to selected value from first - that's basically my problem.
Is it possible to somehow only call my struts action which will return all needed values using javascript and onchange event handler?
I dont have any experience with javascript, and I'm trying to avoid it as much as possible at the moment.
Thanks in advancewell as far your requirement is concern if at all you are planning to implement AJAX try to use the below link which might be of some help...
http://www.it-eye.nl/weblog/2005/12/13/ajax-in-struts-implementing-dependend-select-boxes/
However,I somehow feel there are few loopholes in the author's approach...
i advice to use XmlHttpRequest.reponseXML property there.
However, i've mentioned a sample code snippet for you reference.
XML Response Pattern :
======================
<? xml version="1.1" ?>
<dropdown>
<option>
<val>CUSTOMIZED_VALUE</val>
<text>CUSTOMIZED_VALUE</text>
</option>
</dropdown>Sample.jsp:
===========
<%@page language="java" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Automatic Drop-Down Updation</title>
<script language="javascript">
// Global Variable for XmlHttp Request Object
var xmlhttp
// Timer Variables
var c = 0
var t
/* A function which calls a servlet named AjaxServlet to get XmlData using XmlHttpObject */
function refreshCombo(txt){
xmlhttp = null
// code for initializing XmlHttpRequest Object On Browsers like Mozilla, etc.
if (window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest()
// code for initializing XmlHttpRequest Object On Browsers like IE
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
if (xmlhttp != null){
// Setting the Action url to get XmlData
url = "dropdown.do?count="+txt;
// Course of Action That Should be Made if their is a change in XmlHttpRequest Object ReadyState NOTE : it is 4 when it has got request from CGI
xmlhttp.onreadystatechange = getResponseAction;
// Open the Request by passing Type of Request & CGI URL
xmlhttp.open("GET",url,true);
// Sending URL Encoded Data
xmlhttp.send(null);
else{
// Only Broswers like IE 5.0,Mozilla & all other browser which support XML data Supports AJAX Technology
// In the Below case it looks as if the browser is not compatiable
alert("Your browser does not support XMLHTTP.")
/* Used for verifing right ReadyState & Status of XmlHttpRequest Object returns true if it is verified */
function verifyReadyState(obj){
// As Said above if XmlHttp.ReadyState == 4 then the Page Has got Response from WebServer
if(obj.readyState == 4){
// Similarly if XmlHttp.status == 200 it means that we have got a Valid response from the WebServer
if(obj.status == 200){
return true
else{
alert("Problem retrieving XML data")
/* Action that has to take place after getting reponse */
function getResponseAction(){
// Verifying State & Status
if(verifyReadyState(xmlhttp) == true){
// Building a DOM parser from Response Object
var response = xmlhttp.responseXML.documentElement
// Deleting all the Present Elements in the Drop-Down Box
drRemove()
// Checking for the Root Node Tag
var x = response.getElementsByTagName("option")
var val
var tex
var optn
for(var i = 0;i < x.length; i++){
optn = document.createElement("OPTION")
var er
// Checking for the tag which holds the value of the Drop-Down combo element
val = x.getElementsByTagName("val")
try{
// Assigning the value to a Drop-Down Set Element
optn.value = val[0].firstChild.data
} catch(er){
// Checking for the tag which holds the Text of the Drop-Down combo element
tex = x[i].getElementsByTagName("text")
try{
// Assigning the Text to a Drop-Down Set Element
optn.text = tex[0].firstChild.data
} catch(er){
// Adding the Set Element to the Drop-Down
document.SampleForm.SampleCombo.options.add(optn)
/* Function removes all the elements in the Drop-Down */
function drRemove(){
var x = document.SampleForm.SampleCombo
for(var i = document.SampleForm.SampleCombo.length - 1 ; i >= 0 ; i--){
x.remove(i)
</script>
</head>
<body onload="syncCount()">
<pre> <h1>Refresh Drop-Down <div id='txt'> </div> </h1></pre>
<form name="SampleForm">
<!-- Drop Down which has country list -->
<select name="x" onchange="refreshCombo(this.value)">
<option value="1">United States</option>
<option value="2">United Kingdom</option>
<option value="3">United Arab Emriates</option>
</select>
<!-- Drop Down which is dependent on Country Drop down get list of states -->
<select name="SampleCombo">
<option value="-1">Pick One</option>
</select>
</form>
</body>
</html>
struts-config.xml:
==================
<action-mappings>
<action path="/dropdown" type="com.controlleraction.AjaxActionClass">
<forward name="error" path="/error.jsp"/>
</action>
</action-mappings>AjaxActionClass.java:
=====================
package com.controlleraction;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class AjaxActionClass extends DispatchAction {
public ActionForward execute( ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response) throws Exception {
String req = new String("");
try{
req = request.getParameter("count");
} catch(Exception exp){
if(!req.equals("")){
response.setContentType("text/xml");
response.setHeader("Pragma","no-cache");
response.setHeader("Cache-Control","no-cache,post-check=0,pre-check=0");
PrintWriter out = response.getWriter();
/*a sample bean where we trying to call a service from Model*/
com.Biz.XmlBean xml = new XmlBean();
String buffer = xml.getXmlData(req);
if(xml.close() == true && buffer.equals("") == false)
out.write(buffer);
return(null);
} else {
return new ActionForward("error");
}XmlBean.java:
=============
* XmlBean.java
import java.sql.*;
import java.util.*;
import java.io.*;
* @author RaHuL
public class XmlBean {
private Connection con = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
// Setting CLASSURL path to TYPE I Driver
private String CLASSURL = "sun.jdbc.odbc.JdbcOdbcDriver";
/* Specifing CONNECTION PATH to a DSN named TestDsn
* Please Make Sure you create a DSN Named TestDsn to your database which holds EMP table
private String CONNECTIONURL = "jdbc:odbc:TestDsn";
boolean IS_ESTABLISHED = false;
/** Creates a new instance of XmlBean and also establishes DB Connections */
public XmlBean() {
try{
Class.forName(CLASSURL);
con = DriverManager.getConnection(CONNECTIONURL,"admin","");
IS_ESTABLISHED = true;
} catch(SQLException sqe){
sqe.printStackTrace();
} catch(Exception exp){
exp.printStackTrace();
/* Generates XmlData For the Business Logic Specified */
public String getXmlData(String req){
String XmlBuffer = new String("");
if(IS_ESTABLISHED == true){
try{
pstmt = con.prepareStatement("SELECT stateid,statename FROM STATE_TABLE where countryid = ?");
pstmt.setString(1,req);
rs = pstmt.executeQuery();
if(rs != null){
XmlBuffer = XmlBuffer + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>";
XmlBuffer = XmlBuffer + "<!-- Edited by Rahul Sharma -->";
// Root Node
XmlBuffer = XmlBuffer + "<dropdown>";
while(rs.next()){
String value = rs.getString(1);
String text = rs.getString(2);
// Sub-root Node
XmlBuffer = XmlBuffer + "<option>";
// node which holds value of drop-down combo
XmlBuffer = XmlBuffer + "<val>"+value+"</val>";
// node which holds text for drop-down combo
XmlBuffer = XmlBuffer + "<text>"+text+"</text>";
XmlBuffer = XmlBuffer + "</option>";
XmlBuffer = XmlBuffer + "</dropdown>";
}catch(SQLException sqe){
sqe.printStackTrace();
} catch(Exception exp){
exp.printStackTrace();
return(XmlBuffer);
/* Closes the DB Connection Conmpletely */
public boolean close(){
if(IS_ESTABLISHED == true){
try{
pstmt.close();
con.close();
return(true);
} catch(SQLException sqe){
sqe.printStackTrace();
} catch(Exception exp){
exp.printStackTrace();
return(false);
NOTE: I understand i'm not completely coded things as per proper coding standards.please execuse me for that as this example was just given to enable user to learn how XmlHttpRquest,reponseXML
can be used for better purposes instead of devising manual parsing.
where i've used XmlHttpResponse pattern to be in XML. you may make use of other practices like JSON & so on depending on your requirement..
and and if you are more instrested in integrating Struts with AJAX using few frameworks & customized tag based support please go though the below link.
http://struts.sourceforge.net/ajaxtags/index.html
Hope that might help :)
REGARDS,
RaHuL -
Tranforming xml in struts giving exception
Hi,
I am using ajax with struts. I have to transform xml into html using xsl stylesheet at server side and send the response to the client.
I am using Transformer for the xml transformation. The whole transformation works fine in a simple java application but when i use it in strut framework it throw exception "could not compile style sheet". Following is the code written in the action class of the struts.
/************ code ***************/
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try
StreamSource source = new StreamSource("data.xml");
StreamSource style = new StreamSource("page.xsl");
StreamResult result = new StreamResult(out);
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer(style);
return null;
catch (Exception e)
e.printStackTrace(out);
/************ stack trace **************/
javax.xml.transform.TransformerConfigurationException: Could not compile stylesheet at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTemplates(TransformerFactoryImpl.java:824) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTransformer(TransformerFactoryImpl.java:619) at RSSFeed.Transformxml.execute(Transformxml.java:80) at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:419) at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:224) at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1194) at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414) at javax.servlet.http.HttpServlet.service(HttpServlet.java:689) at javax.servlet.http.HttpServlet.service(HttpServlet.java:802) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173) at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:362) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:856) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:744) at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527) at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80) at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684) at java.lang.Thread.run(Thread.java:595)
I am very much new to java and just can't figure out whats wrong. Can anyone tell me the mistake or suggest any other alternative. I need help fast. I shall really appreciate it.
ThanxI stuck with this same issue today and managed to resolve:
I removed all the Temp files in the server work directory (I use JBoss 4.0) and when restarted it works -
Hi..
I have to develop a web application in my last semester of Bachelor of Engineering using technologies like Servlets, JSP, AJAX, JavaScript, struts, portlets ..
Please give me some ideas on which domain I can develop a good project. The project should also have a business perspective..
Waiting for some good project definitions..
Thanking in advance..http://search.sun.com/search/onesearch/index.jsp?qt=project+suggestion&rfsubcat=siteforumid%3Ajava54%2Csiteforumid%3Ajava31%2Csiteforumid%3Ajava553&col=developer-forums
-
I have developed a Portlet using JPDK that access a database. It does a select and displays the result. Everything works like a charm.
I want to enable a scheduled refresh. That is to say, that I want my Portlet to be regularly re-executed, for example each 5 minutes.
To do this I thought about two ways:
- IFRAME
I had inserted an iframe in my Portlet and I set the source of it to be a detail page. The problem was that the detail page does not have the same style that the one of the Portlet. I did not find any way to set it to be the same. Moreover I have seen some links in the forum to some iframe examples but they are dead
- AJAX
I have read the excellent white paper of Oracle on this subject but my problem with it is that I do not want to implement a specific web service that returns the select result. I find it too a complicated solution for this simple problem…
So could anyone help me on this simple point how to regularly reload a Portlet ?Hello,
To me, there are 2 ways to di so :
Simple way :
Add a javascript timer on your page. Each top of teh timer will refesh your page.
-> drawback : it reposts your request
Nice way :
Following the AJAX wokaround, you can use JAVASCRIPT to make an astnchronous request to a PL-SQL procedure that can send you your results in a XML fargment. If you modify your JAVA portlet to take this XML in input, you will ne able to refresh your datas.
AJAX in portal could be made very simply, just take a look at this link : http://julien.carnelos.free.fr/blog/index.php?2006/01/06/26-ajax-et-struts-par-l-exemple
(french tutorial for ajax and struts)
Put the javascript methods in a HTML portlet on your page and it works perfeclty.
Hop That Helps
Maybe you are looking for
-
I have a side-by-side bar chart with three series. Two of the series are represented by risers and the third series is a line showing the percent difference between the first two series. There are two y axes. The 2nd's y axis shows the third serie
-
Dreamweaver support not available
I have Dreamweaver suite CS3 and after a computer crash I cannot get it activated. Adobe does not offer phone support and I've been on their site for hours and cannot find a solution
-
Hi experts Am trying to apply SPS to our EP 7.0 portal. So I downloaded the files from SMP and dumped them into /usr/sap/trans/EPS/in directory including the SAPCAR file. I renamed the SAPCAR_XXX(some file name ) to SAPCAR. I am getting errors while
-
is there any practical way of entering numeric values with suffixes in Labwindows CVI in order to prevent user from struggling with '0' es.
-
HT204053 Can't access old Apple ID
Can't access old Apple ID, any suggestions? Tried to change password and says my date of birth is wrong. Says cant find Apple ID if I "find ID"