Link to home
Start Free TrialLog in
Avatar of jazzIIIlove
jazzIIIloveFlag for Sweden

asked on

how to send html forms with JSON in Java

Hi;

I have html pages and servlets in which i form my html page in servlets but i want to do this via JSON.

How to do this?

Any tips and libraries?

Regards.
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Do you want to send your forms to the browser with JSON

Or

Do you want to post your forms back from the browser using JSON
As for posting to your servers it's really easy with jquery (javascript made easy)

$.ajax({
  dataType: "json",
  url: url,
  data: $("#myformid").serialize(),
  success: function() {
\\ do something when the action is complete
}
});

Open in new window


As for the servlet that's not my forte so ill leave that one to the other experts
Avatar of jazzIIIlove

ASKER

Hi Julian:
>>Do you want to send your forms to the browser with JSON
No.

>>Or

>>Do you want to post your forms back from the browser using JSON
Yes

Thanks tagit, but i need a complete example to understand the logic properly.

I can use Jackson or GSon for this need.

Regards.
No problem, this looks to be your answer though as it shows how to parse the json on the servlet
http://stackoverflow.com/questions/5338943/read-json-string-in-servlet
public doPost(HTTPServletRequest req, HTTPServletResponse res)
{
     JSONObject jObj = new JSONObject(request.getParameter("mydata")); // this parses the json
Iterator it = jObj.keys(); //gets all the keys

while(it.hasNext())
{
    String key = it.next(); // get key
    Object o = jObj.get(key); // get value
    session.putValue(key, o); // store in session
}
}

Open in new window

Is there more complete example for this?

Like a full but simple html page having form and processed in servlet via JSON?

I need to see the complete picture..

Regards.
Here is a link to a tutorial on using servers for receiving post and get data. http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Form-Data.html

I may not know servlets very well but the principles remain the same when compared with other server side scripts such as php and asp
Thanks tagit but the link is plain html and servlet. Where is JSON in this?

Regards.
you don't need to worry about the format
using @julianH code you send parameters to your server and read them as usual

<form>
   <input name="myfield1" value="123" />
   <input name="myfield2" value="456" />
   <input type="submit" value="SUBMIT" />
</form>

Open in new window


$.getJSON("/servlet/mypage", $("form:eq(0)").serialize(), function(message){}, "post");
or :
$.getJSON("/servlet/mypage", $("form:eq(0)").serializeArray(), function(message){}, "post");

in your servlet just use :
public doPost(HTTPServletRequest req, HTTPServletResponse res) {
     String field1 = req.getParameter("myfield1");
     String field2 = req.getParameter("myfield2");

Open in new window


var data = $("#myform").serializeArray(); // return a JSON object
var data = $("#myform").serialize(); // return a string

but here : $.getJSON(url, data, success, method);
or here : $.ajax({ dataType:"json", url:url, data: data, success: success });
that don't make any difference when reading on the server side
I know what you mean by a complete example though its late here and I'm trying to do this on the iPad. Hopefully another expert can give you this while I sleep otherwise ill post back in the morning.
In the meantime also post what code you do have and where and what you are stuck on
The second link I sent you was dealing with just the method for parsing POST data. The first link was parsing the JSON.  It was just a matter of integrating the two.  
I would strongly suggest working through a few tutorials on java and servlets as well as javascript to understand the basics before just accepting code given to you by us experts.  With all due respect, I thought you would make that connection between the links.
Again it would be really beneficial for all the experts to see what you've got already.  So many times we come up with solutions that don't work with the authors code right away because there's not much to go on initially and we guess what is needed.
ASKER CERTIFIED SOLUTION
Avatar of Rob
Rob
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
User generated image
request.getParameter("mydata") ?
no...
the problem is not how to read but how you send.
you need to send ONE parameter : mydata
for your example it should be :

            $.ajax({
                  dataType: "json",
                  url: "/servlets/hall.JSONExample",
                  data: { mydata : JSON.stringify( {myfield1:$("#myfield1").val(), myfield2:$("#myfield2").val() } ),

Yes you MUST stringify the JSON object.
You CAN'T use $.serialize or $.serializeArray because the JSON is different (you get name and value key for an input)

Now with that you send a JSON string like this one :
User generated image
And you are able to use :
JSONObject jObj = new JSONObject(request.getParameter("mydata"));

BUT there's no available reason to do all of this, I don't understand the question of using JSON for this purpose...

Anyway, congratulations for your points @tagit (I know you're not here for points)
The code I've posted is correct. There's no point going a JSON encode on the Ajax request because it just gets converted to a query string when sent. I know what you're saying re the "my data"but I wouldn't do it that way. I was constructing each example separately and want careful enough linking the two.
The get parameter map function looks for a query string and creates the map. The JSON object's constructor accepts a map for an argument.