How to use Ajax In struts

I want to use Ajax in my struts framework.Can anyone please suggest me how
to do this
Thanks

http://www.google.com/search?hl=en&q=ajax+struts&btnG=Google+Search

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"));
    }

  • How to Use Ajax Framework with Netbean6.0

    Hello Friends....
    I am using netbeans IDE to develop Java enabled web application
    now i want to use ajax technology in my webapp.
    So how can i use ajax with netbeans.
    I add Jmaki plugins in netbeans and i got various jmaki component but i dont know how to use them.....!
    Please somebody help me.........

    vasim_saiyad2000 wrote:
    Yes My Friend in the past i made a web application and all html, jsp and java code was written in notepad.
    I want that how to use ajax with java. IDE does not matter i wrote about netbeans because now i am very good aware of netbeans and i am using netbeans ide to develop my app.
    You just tell me how to use ajax with java like .net has some ajax toolkit in its palette..
    How can we use same thing in java /netbeans.Uh, look for a plugin which does that? Or, better, just write code yourself inside Netbeans.
    Can u tell one most import thing .......Suppose when user log in i have created session.
    Suppose user does not logout manually by clicking LOGOUT link its close directly browser so can be I sure that session may have been expired......!
    Please solve my this doubt.....!Implement HttpSessionListener and do the desired task in sessionDestroyed() method.

  • How to use internationalization in struts

    how to use the internationalization in struts with clear example

    http://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

  • How to use Ajax Get Multiple Values in Tabular form?

    Hi All-
    I am trying to use AJAX to get multiple values in tabular form by using Denes Kubicek's example in the following link -
    http://apex.oracle.com/pls/otn/f?p=31517:239:9172467565606::NO:::
    Basically, I want to use the drop down list to populate rest of the values on the form.
    I have created the example(Ajax Get Multiple Values, application 54522) on Oracle site -
    http://apex.oracle.com/pls/apex/f?p=4550:1:0:::::
    Workspace: iConnect
    login: demo
    password: demo
    I was able to duplicate his example on page 1 (home page).
    However, I want to use system generate tabular form to finish this example, and was not able to populate the data correctly.
    Page 2 (method 2) is the one that I am having trouble to populate the column values. When I checked application item values in Session, and the values seems to be populated correctly.
    This is what I have done on this page:
    1. Create an Application Process On Demand - Set_Multi_Items_Tabular2:
    DECLARE
      v_subject my_book_store.subject%TYPE;
      v_price my_book_store.price%TYPE;
      v_author my_book_store.author%TYPE;
      v_qty NUMBER;
      CURSOR cur_c
      IS
      SELECT subject, price, author, 1 qty
      FROM my_book_store
      WHERE book_id = :temporary_application_item2;
    BEGIN
      FOR c IN cur_c
      LOOP
      v_subject := c.subject;
      v_price := c.price;
      v_author := c.author;
      v_qty := c.qty;
      END LOOP;
      OWA_UTIL.mime_header ('text/xml', FALSE);
      HTP.p ('Cache-Control: no-cache');
      HTP.p ('Pragma: no-cache');
      OWA_UTIL.http_header_close;
      HTP.prn ('<body>');
      HTP.prn ('<desc>this xml genericly sets multiple items</desc>');
      HTP.prn ('<item id="f04_' || :t_rownum || '">' || v_subject || '</item>');
      HTP.prn ('<item id="f05_' || :t_rownum || '">' || v_price || '</item>');
      HTP.prn ('<item id="f06_' || :t_rownum || '">' || v_author || '</item>');
      HTP.prn ('<item id="f07_' || :t_rownum || '">' || v_qty || '</item>');
      HTP.prn ('</body>');
    END;
    2. Create two application items - TEMPORARY_APPLICATION_ITEM2, T_ROWNUM2
    3. Put the following in the Page Header:
    <script language="JavaScript" type="text/javascript">
    function f_set_multi_items_tabular2(pValue, pRow){
        var get = new htmldb_Get(null,html_GetElement('pFlowId').value,
    'APPLICATION_PROCESS=Set_Multi_Items_Tabular2',0);
    if(pValue){
    get.add('TEMPORARY_APPLICATION_ITEM2',pValue)
    get.add('T_ROWNUM2',pRow)
    }else{
    get.add('TEMPORARY_APPLICATION_ITEM2','null')
        gReturn = get.get('XML');
        if(gReturn){
            var l_Count = gReturn.getElementsByTagName("item").length;
            for(var i = 0;i<l_Count;i++){
                var l_Opt_Xml = gReturn.getElementsByTagName("item")[i];
                var l_ID = l_Opt_Xml.getAttribute('id');
                var l_El = html_GetElement(l_ID);   
                if(l_Opt_Xml.firstChild){
                    var l_Value = l_Opt_Xml.firstChild.nodeValue;
                }else{
                    var l_Value = '';
                if(l_El){
                    if(l_El.tagName == 'INPUT'){
                        l_El.value = l_Value;
                    }else if(l_El.tagName == 'SPAN' && l_El.className == 'grabber'){
                        l_El.parentNode.innerHTML = l_Value;
                        l_El.parentNode.id = l_ID;
                    }else{
                        l_El.innerHTML = l_Value;
        get = null;
    </script>
    Add the follwing to the end of the above JavaScript:
    <script language="JavaScript" type="text/javascript">
    function setLOV(filter, list2)
    var s = filter.id;
    var item = s.substring(3,8);
    var field2 = list2 + item;
    f_set_multi_items_tabular2(filter, field2);
    4. Tabular form query:
    select
    "BOOK_ID",
    "BOOK",
    "SUBJECT",
    "PRICE",
    "AUTHOR",
    "QTY",
    "BOOK_ID" BOOK_ID_DISPLAY
    from "#OWNER#"."MY_BOOK_STORE"
    5. In Book_ID_DISPLAY column attribute:
    Add the following code to element attributes: onchange="javascript:f_set_multi_items_tabular2(this.value,'#ROWNUM#');"
    Changed to -> onchange="javascript:setLOV(this,'f03');"
    Now,  T_ROWNUM2 returns value as f03_0001. But, TEMPORARY_APPLICATION_ITEM2 returns as [object HTMLSelectElement]...
    Please help me to see how I can populate the data with this tabular form format. Thanks a lot in advanced!!!
    Ling
    Updated code in Red..

    Ling
    Lets start with looking at what the javascript code is doing.
    function f_set_multi_items_tabular(pValue, pRow){
      /*This will initiate the url for the demand process to run*/
      var get = new htmldb_Get(null,html_GetElement('pFlowId').value,
                              'APPLICATION_PROCESS=Set_Multi_Items_Tabular',0);
      if(pValue){
        /*If there is an value than submit item name with value*/
        get.add('TEMPORARY_APPLICATION_ITEM',pValue)
        get.add('T_ROWNUM',pRow)
      }else{
        /*Else set the item TEMPORARY_APPLICATION_ITEM to null*/
        get.add('TEMPORARY_APPLICATION_ITEM','null')
      /*Submit the url and te returned document is of type XML*/
      gReturn = get.get('XML');
      if(gReturn){
        /*There is something returned*/
        var l_Count = gReturn.getElementsByTagName("item").length;
        /*For all elements of the tag item*/
        for(var i = 0;i<l_Count;i++){
          /*Get the item out of the XML*/
          var l_Opt_Xml = gReturn.getElementsByTagName("item")[i];
          /*Get the id of the item*/
          var l_ID = l_Opt_Xml.getAttribute('id');
          /*Get the element in the original page with the same id as
          **the item we have in the XML produced by the ondemand process
          var l_El = html_GetElement(l_ID);
          /*Now get the value of the item form the XML*/
          if(l_Opt_Xml.firstChild){
            var l_Value = l_Opt_Xml.firstChild.nodeValue;
          }else{
            /*There is no value*/
            var l_Value = '';
          if(l_El){
            /*There is an element with the same id as the item we are processing*/
            if(l_El.tagName == 'INPUT'){
              /*The element is an input item just set the value*/
              l_El.value = l_Value;
            }else if(l_El.tagName == 'SPAN' && l_El.className == 'grabber'){
              /*If it is a span elment and has the class grabber
              **Then set the innerHTML of the parent to the value
              **and the id of the parent to the id
              l_El.parentNode.innerHTML = l_Value;
              l_El.parentNode.id = l_ID;
            }else{
              /*Else set the value as innerHTML*/
              l_El.innerHTML = l_Value;
      get = null;
    Now where it went wrong in your initial post
    The XML that was returned by your XML process would be something like
    <body>
      <desc>this xml genericly sets multiple items</desc>
      <item id="f02_1">CSS Mastery</item>
      <item id="f03_1">22</item>
      <item id="f04_1">Andy Budd</item>
      <item id="f05_1">1</item>
    </body>
    When you don't use apex_item to create your tabular form a item in the table will look like
    <input id="f02_0001" type="text" value="CSS Mastery" maxlength="2000" size="16" name="f05" autocomplete="off">
    Notice the id's f02_1 and f02_0001 don't match.
    So to make it work the XML would have to look like
    <body>
      <desc>this xml genericly sets multiple items</desc>
      <item id="f02_0001">CSS Mastery</item>
      <item id="f03_0001">22</item>
      <item id="f04_0001">Andy Budd</item>
      <item id="f05_0001">1</item>
    </body>
    To do that simply use lpad in the ondemand process like
    HTP.prn ('<item id="f02_' || lpad(:t_rownum,4,'0') || '">' || v_subject || '</item>');
    HTP.prn ('<item id="f03_' || lpad(:t_rownum,4,'0') || '">' || v_price || '</item>');
    HTP.prn ('<item id="f04_' || lpad(:t_rownum,4,'0') || '">' || v_author || '</item>');
    HTP.prn ('<item id="f05_' || lpad(:t_rownum,4,'0') || '">' || v_qty || '</item>');
    Keep in mind that the above is based on your original post and #ROWNUM# not being lpadded with zero's.
    Nicolette

  • 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

  • How to use displaytags with struts

    How to use display tags with struts to generate report from database

    I think it would only consist in including the tag library of displaytags in the header and use the prefix of desplay tags.
    Exporting the report from a database would only need to retrieve this information from the database as a List, Map or Collection of objects (beans) and display tem with the corresponding tag (table)
    You have some more information here:
    http://displaytag.sourceforge.net/11/tut_basic.html
    Regards and good luck,
    Fran Serrano.

  • How to use Ajax Web method in v4.master page to pass value to server side from JavaScript?

    Hi,
    I am customizing my v4.master page. Just adding jquery "Multiselect" dropdown .
    I want to pass selected value to code behind to perform some database activities.
    Here no code behind for me. Just i have added "Server side script" as a code behind.
    How to pass the value?
    Anyone give me the idea on it.
    Thanks & Regards
    Poomani Sankaran

    try using asp.net variables as per below links:
    http://sharepoint.stackexchange.com/questions/88777/how-to-use-a-variable-in-the-masterpage
    http://sharepoint.stackexchange.com/questions/80074/how-can-i-use-the-current-language-as-a-variable-in-my-masterpage
    https://msdn.microsoft.com/en-us/library/ms476046%28v=office.12%29.aspx
    http://www.dotnetfunda.com/articles/show/1507/how-to-access-master-page-variableproperty-from-the-content-page
    Please mark answer as correct if it is correct else vote for it if you find it useful Happy SharePointing

  • How to use coolies in struts

    hai
    i got answer for this in O'Reilly Jakarta Struts Cook Book....
    thanks...

    I don't think you should use coolies in struts at all. Or for anything at all. I abhor slavery of any kind

  • How to use cookies in struts

    hai
    iI am new to struts. I want to get value in text field from one form to another using cookis in struts, can any one help me?, please...

    To write a cookie in Struts, you create one and add it to the response object. (response.addCookie(cookie)).
    To read it, you use the bean:cookie tag.
    As to use cookies to get a given value from one form to another, there might be better ways, like using request attributes.
    You might be better off keeping those cookies in the jar, after all.

  • 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

  • How to use jdbc in struts ?

    i want to connect to database and fire insert, select etc queries but my code should be in struts framework

    Struts is only a view-controller framework. MVC implemented properly places the database operations in the model tier. So, I would advise against doing something that seems quick and simple initially (such as firing off JDBC from a JSP).
    Rather, use Struts to simply be your VC. Within your model tier, create data access objects. These can use an ORM such as JPA (Hibernate, Toplink, etc.) or vanilla JDBC. My assumption since you are using Struts is that you at least have a Servlet container, likely Tomcat or Jetty. If so, there is documentation for each of those containers on how to set-up a JDBC data source. You can use JNDI within your model tier to access the DataSource (if you are using plain JDBC) or to supply the connection information for your EntityManagerFactory (if using JPA).
    If you are not sure how to even perform database access, I would recommend taking a JDBC tutorial. Do so standalone and not bothering with Struts or even Servlets. Once you have JDBC down, you can proceed to JPA and/or then integrate with Struts.
    - Saish

  • How to use frame in struts

    Hi all,
    I am using Struts framework.
    I have two part in a jsp page, in which i am getting data from previous page by using request.getParameterValues("date");
    i.e i am getting multiple date.
    Now in first part of jsp page i have checkbox tree ,where user can select checkbox, then click on submit .Now on click submit data will pass second part of jsp page.where with checked data
    and date i have to do some process.
    it is like frame type structure, where data from one frame will pass in second frame in jsp page.
    I request to all JGuru to guide me how to do it.
    Deepak

    Just let it access the request parameters the same way? Using HttpServletRequest#getParameter() and so on.

  • How to use session in Struts

    Hello, there:
    It's a simple question.
    I have a web app which has a login page, in its action class I create an object, user, and save it into session by using request.getSession(true).setAttribute("user", user).
    In another action class, I want to use the info of user then I use request.getSession(true).getAttribute("user"); however, the returned object is NULL. Did I use session in a wrong way?
    Thanks,
    Sway

    Did I use session in a wrong way?No, you are using the session correctly. The code looks fine.
    Check
    - your spelling of the attribute names - obviously they must match
    - the ids of the sessions you get both times: session.getId(). If they have different ids, then most probably the session is being lost somewhere.
    There are a number of reasons to lose a session. If you close the browser, invalidate the session in code, or lose the cookie recording the id. This happens when you change from https to http, so a session can be lost that way.
    The session is normally maintained by session cookies. If you close your browser you lose the cookie. If you have disabled cookies on your machine then it also might not work.
    In cases such as that you should be using the method response.encodeURL() to maintain the session for you in any hyperlinks you produce. Struts normally handles that for you though if necessary.
    Hope this helps,
    evnafets

Maybe you are looking for