简体   繁体   中英

Passing value from a servlet to jsp using javascript

I am new to web programming and I am trying to build a struts application. I want to print values from file or database according to the option selected from the dropbox in the same page. In order to do that, I have to fetch the data from the servlet and display it in the jsp using javascript. But I have no idea how to display the values using javascript.

handler.java(servlet)

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import net.sf.json.JSONObject;
import net.sf.json.JSONArray;

public class handler extends org.apache.struts.actions.DispatchAction{

    private static final String SUCCESS = "success";

    public ActionForward Add(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {

        actionFileAndDB obj=new actionFileAndDB();
        JSONArray list=obj.view();
        request.setAttribute("jsonArray",list);

        System.out.println("this is being called");
        String s1=request.getParameter("dropdown");
        System.out.println("add="+s1);

        String s="Karthikeyan";
        request.setAttribute("myname",s);       

        return mapping.findForward(SUCCESS);
    }
}

view.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="net.sf.json.JSONObject"%>
<%@page import="net.sf.json.JSONArray"%>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>View</title>
    </head>
    <body>
        <form action="operations.do">
            <table>
                <tr>
                    <td>
                        <select value="s"  name="dropdown">
                            <option>VIEW</option>
                            <option>Database</option>
                            <option>File</option>
                            <option>Both</option>
                        </select>
                    </td>
                    <td>
                        <input type="hidden" id="f4" value=<%= request.getAttribute("s") %>  />
                        <input type="button" value="Add" name="actionMethod" onclick="viewData();" />
                    </td>
                    <td>
                        <input type="submit" value="Edit" name="actionMethod"/>
                    </td>
                    <td>
                        <input type="submit" value="Delete" name="actionMethod"/>
                    </td>
                </tr>
            </table>
        </form>


        <div id="p1">

            asdfasdf


        </div>




        <script type="text/javascript">
            function viewData()
            {
                document.getElementById("p1").innerHTML=document.getElementById("f4").value;
                event.preventDefault();
            }
        </script>


    </body>
</html>

I have tried displaying values from javascript to the jsp, as is evident from the code, but unable to do so.Is it necessary to have a knowledge of JQuery and Ajax to do so? Please help me out.

I think we find a way to achieve what you intend to do. So first of all I understood that the usecase is a user getting an option selctor ('#dropdown') and they choose some entries and after that the view looks up the data store (DB or file hidden on the server) and displays some information. These interactively shown information is totally dependend on the option selected. Did I got that right?

Iff this is what you indended to do we need three files: your original StrutsAction (1), your original View (JSP) (2), and another StrutsAction for our requests to deliver information from the server. Whereas (1) and (2) are still there in your question and they have to be functioning currently. (I would prefer naming classes in Java in capital case, eg 'Handler' and 'ActionFileAndDB'.)

To get the interactivity in your classes first create your new StrutsAction with a mapping in your struts' config.xml files. These have to deliver your data in say JSON notation. I would use Jackson JSON, JAXB, or some lib to do this. Of course you can deliver (localized) strings as well. I suggest using your 'operations.do' for that.

Then in the view we have two options:

  1. using a form or
  2. using AJAX instead

    1. A form is easier to do but we have to submit this form (eg with a submit button) for the changes to take effect. And we have to redirect to our original view (reflection) and therefore will never leave this site. So the processing is worse for the user.

    2. Using AJAX has the benefit of being interactive (information appears right after the choice has been made) and we can submit the form to somewhere else. In this case you may load the data first from the server using jQuery.get('operations.do').done(...) with a callback function in 'done' and 'fail'. This callback function will either display retrieved 'data' (in case 'done(data)') or some error message using the jQuery('p1').html(data) or jQuery('p1').html('An error occured!') on your 'p1' label. You may use jQuery.post(...) as well. For more information on the usage I found this helpful: https://api.jquery.com/jQuery.get/

I would make the travel of information very clear before beginning implementing any solution: as the data needed and passed is in complex apps hard to change. The implementation heavily depends on your choice of form (1) or AJAX (2).

Here is the solution that I found out for my problem :

I added the following code to the 'View' method in action class ie, handler.java-

response.setContentType("text/JSON");
        try
        {
            PrintWriter out = response.getWriter();
            out.println(o);
            out.flush();
        }
        catch(Exception e)
        {
            System.out.println(e);
        }   



        return null;    

where 'o' is a JSON object containing JSON array of JSON objects.

I wrote a script for executing the action class-

   var url="http://localhost:8080/MyProjDBandFilesv2/operations.do?dropdown="+dropval+"&actionMethod=View"; 

where View is the method to be called in the 'handler' class and the 'url' is to passed as argument to JQuery post method.

The path for 'operations.do' is defined in struts-config.xml is as follows-

<action path="/operations" type="handler" parameter="actionMethod">
            <forward name="success" path="/view.jsp"/>
            <forward name="add" path="/AddOrEdit.jsp"/>
</action>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM