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.
LVL 12
jazzIIIloveAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
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
0
RobOwner (Aidellio)Commented:
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
0
jazzIIIloveAuthor Commented:
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.
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

RobOwner (Aidellio)Commented:
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
0
RobOwner (Aidellio)Commented:
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

0
jazzIIIloveAuthor Commented:
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.
0
RobOwner (Aidellio)Commented:
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
0
jazzIIIloveAuthor Commented:
Thanks tagit but the link is plain html and servlet. Where is JSON in this?

Regards.
0
leakim971PluritechnicianCommented:
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
0
RobOwner (Aidellio)Commented:
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
0
RobOwner (Aidellio)Commented:
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.
0
RobOwner (Aidellio)Commented:
In your html / javascript:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
	$("#myformid").on('submit', function() {
		$.ajax({
			dataType: "json",
			url: "/servlets/hall.JSONExample",
			data: $("#myformid").serialize(),
			success: function() {
				// do something when the action is complete
				// redirect to another page etc
			}
		});
		return false; // don't reload the page
	});
});
</script>
<meta charset=utf-8 />
<title></title>
</head>
<body>
  <form id='myformid' method='post' action=''>
   <input name="myfield1" value="123" />
   <input name="myfield2" value="456" />
   <input type="submit" value="SUBMIT" />
</form>
</body>
</html>

Open in new window



and your servlet:

package hall;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

public class JSONExample extends HttpServlet {
	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
		    // now do something with the key and value
		    ...
		}


	}
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
leakim971PluritechnicianCommented:
query string parameters
request.getParameter("mydata") ?
0
RobOwner (Aidellio)Commented:
0
leakim971PluritechnicianCommented:
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 :
JSON string
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)
0
RobOwner (Aidellio)Commented:
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.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.