0

I've the following Javascript function to add invisible data into my form,

function addHidden(theForm, key, value) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = key;'name-as-seen-at-the-server';
input.value = value;
theForm.appendChild(input);
}

and I have two forms as follows

form1

<form method="get" id="execform" name="toexecute" enctype="multipart/form-data">
    <div id="to execute">
        <ul id=ul>
            <li><button type= "button" id="execute1" onclick="saveTextAsFile()">Click to execute</button></li><li><br></li>
        </ul>
    </div>  
</form>

saveTextAsFile()

var script = ace.edit("editor");
var myDivText = script.getValue();
var theForm = document.forms['toexecute'];
addHidden(theForm, 'mytxt', myDivText);
document.toexecute.submit();

form2

<form method="post" id="theform" name="myform" action="upload" enctype="multipart/form-data">
    <div id="elements">
    <ul id="ul">
        <li>Left File : <input type="file" name="dataFile1" id="fileChooser1" /></li><li><br></li>
        <li>Right File : <input type="file" name="dataFile2" id="fileChooser2" /></li><li><br></li>
        <li>Runner.xlsx : <input type="file" name="dataFile3" id="fileChooser3" /></li><li><br></li>
        <li><button type="button" id="execute" onclick="ValidateFile()">Click to Upload files</button></li>
    </ul>
    </div>
</form>

ValidateFile()

var myDivText1 = ace.edit("editor").getValue();
var theForm1 = document.forms['myform'];
addHidden(theForm1, 'mytxt1', myDivText1);
alert(myDivText1);
document.myform.submit();   

The hidden data of form 1 is being successfully added, passed and I am able to access that in my servlet, while I've used the same method in form 2 my servlet is throwing a nullpointerexception. What is my mistake?

When form2 is being submitted in my servlet,

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{//activated by the form named myform of line 93 in geco.jsp
    PrintWriter out = response.getWriter();

    Cookie[] cookies = request.getCookies();
    String fpath= null;
    if (cookies != null) {//Get cookie initilised when user uploads geco script
     for (Cookie cookie : cookies) {
       if (cookie.getName().equals("thecookie")) { 
           fpath = cookie.getValue();
        }
      }
    }

    response.setContentType("text/html");  

        FileItemFactory factory = new DiskFileItemFactory();  
        ServletFileUpload upload = new ServletFileUpload(factory);
        try 
        {  
            List items = upload.parseRequest(request);  
            Iterator iterator = items.iterator();
            while (iterator.hasNext())
            {  
                FileItem item = (FileItem) iterator.next();  
                if (!item.isFormField())  
                {
                    String fileName = item.getName();      

                         String itemField = item.getFieldName();

                         if (itemField.equals("dataFile1")) 
                         {  //get the text of the editor here and save it

                            String TEXT = request.getAttribute("mytxt1").toString();//This is where it is displaying null


                            File uploadedFile = new File(fpath, fileName);
                            item.write(uploadedFile);
                            String f1 = "<span class='blue'>" + "Uploaded <b>left file</b> " +fileName+ "<br>" + "</span>";
                            request.setAttribute("f1stat", f1);
                         }
                         if (itemField.equals("dataFile2"))
                         {    
                            File uploadedFile = new File(fpath, fileName);
                            item.write(uploadedFile);
                            String f2 = "<span class='blue'>" +"Uploaded <b>right file</b> " +fileName+ "<br>" + "</span>";

                            request.setAttribute("f2stat", f2);
                         }
                         if (itemField.equals("dataFile3"))
                         {
                             File uploadedFile = new File(fpath, fileName);
                             item.write(uploadedFile);
                             File uploadedFile1 = new File(fpath, "Runner.xlsx");
                             item.write(uploadedFile1);
                             String f3 = "<span class='blue'>" +"Uploaded <b>Config file</b> " +fileName+ "<br>" + "</span>";
                             request.setAttribute("f3stat", f3);

                             String content="";
                             if(new File(fpath).exists())
                                {
                                    String my = fpath + "/gecofile.geco";

                                    BufferedReader reader = new BufferedReader(new FileReader(my));
                                        String line1;
                                        while ((line1 = reader.readLine()) != null) 
                                            {
                                                content= content + line1 +"\n";
                                            }
                                }
                             request.setAttribute("File_Text", content);
                             RequestDispatcher rd = request.getRequestDispatcher("geco");
                             rd.forward(request, response); 
                         }

PS: The cookie is set when form1 is submitted to doGet() and here in doPost() I am accessing the same cookie value.

PS: I've tried changing getAttribute to getParameter still the value remains null.

  • Are you absolutely sure that `document.forms['myform']` is holding a reference to your form? – aaron-bond Apr 09 '14 at 08:38
  • @Askanison4 there's no doubt. see form's name. – Bhojendra Rauniyar Apr 09 '14 at 08:40
  • Yep and thats the only form with that name I have –  Apr 09 '14 at 08:40
  • @DholakiyaAnkit Actually these are parts of my program, and so adding a fiddle would be of no use without the servlet side code –  Apr 09 '14 at 08:43
  • have you checked that your hidden field value is passed from client to servlet ? – Yagnesh Agola Apr 09 '14 at 08:47
  • Why don't you try adding a breakpoint before you submit and check the DOM for the form and the fields there. See if it has been added? – aaron-bond Apr 09 '14 at 08:54
  • Yep, on the client side the alert displays the correct value but on the server side it is being showed as a null value –  Apr 09 '14 at 08:55
  • @Zedai I don't mean the alert... you know the value being passed into your `addHidden` function is correct. I mean that you should inspect the actual HTML generated and be sure that the hidden input is being added to your form. – aaron-bond Apr 09 '14 at 09:04
  • Make the added input not hidden, so you can actually see what is happening. And if it works correct, make it hidden again. – Michel Apr 09 '14 at 09:06
  • added servlet code, pl check everyone. –  Apr 10 '14 at 11:14
  • possible duplicate of [Convenient way to parse incoming multipart/form-data parameters in a Servlet](http://stackoverflow.com/questions/3337056/convenient-way-to-parse-incoming-multipart-form-data-parameters-in-a-servlet) – Sebastian Piskorski Apr 11 '14 at 09:51

2 Answers2

0

The input field adds properly. Check request with FireBug if the data from hidden input is there, it should be. It is rather your servlet issue. Maybe because you use different names for the forms. Maybe because you give different values for input.name . Code above works fine. The reason might be also in that your first form toexecute does have no action field.

You give us to little data about server side code to solve this problem.

EDIT:

I don't have experience in Java Servlets so I'm just shooting. At first time you send GET and request.getAttribute() works. Second time you send POST, and there is issue with that. Since you send images, that is encoded data, you can't read it normally. I think you will find your answer here:

HttpServletRequest get JSON POST data

EDIT2:

Try this method. It should do the job:

request.getServletContext().getAttribute("attr_name");

EDIT3:

Because you're using Tomcat 6, you have issue with hadling multipart/form-data. Here is similiar problem and solution:

Convenient way to parse incoming multipart/form-data parameters in a Servlet

You should move to Tomcat 7.

Community
  • 1
  • 1
Sebastian Piskorski
  • 4,026
  • 3
  • 23
  • 29
0

Inside your servlet you need to be getting the request parameter called mytxt1 not an attribute set in the request with that name (unless there's some code you haven't shown us). Change this line:

String TEXT = request.getAttribute("mytxt1").toString();//This is where it is displaying null

to

String TEXT = request.getParameter("mytxt1");
Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
  • Tried both, still the value is null –  Apr 10 '14 at 14:02
  • @Zedai And you're sure the hidden input is being added correctly by the JavaScript? Try taking out the line that submits the form and checking that. – Anthony Grist Apr 10 '14 at 14:09
  • @Zedai As I said before, you cannot use standard functions to read data when you send encoded data. Normal post is send like string or array. Images require to send encoded objects and you cannot read them as usual. Object that usually stores data is empty. – Sebastian Piskorski Apr 10 '14 at 19:32
  • @AnthonyGrist I think they are not being added properly as I see no chamge in the URL during my second form submit –  Apr 11 '14 at 05:11