java, jquery and jsp messaging - java

I am using jquery get request to pass the array of strings to java class from jsp.
something like this :
$.ajax({url: '<%= My java class %>'+'?s1='+ $("#networkBox1").val()+'&box1=Box1&tick=add&val1='+ allvs+'&s2='+ $("#networkBox2").val()+'&box2=Box2&val2='+ allvs,
type: 'get',
dataType: 'text',
async: false,
success: function(data) {Processbox(newdata);}});
allvs --is array of strings.
I am converting these strings to list in My java class and than updating the java collections (hashMap) on the basis of parameters s1 and s2 and getting the response back by jquery and printing again by Processbox function shown above. The parametrs s1 and s2 can be same for different users. so my question is do i need to have my methods in java class as thread safe (synchronized) ? This is a web app which will be used by different users when they login into website.

Related

Error tolerance of URI-encoded string syntax

I have picked up a legacy project and I am in the process of debugging something.
I have come across a custom JavaScript function (encodeJsonIntoString) which encode URI components for JavaScript object before sending over via AJAX.
The AJAX is nothing fancy:
$.ajax({
url: URL,
method: 'POST',
datatype : 'json',
data : encodeJsonIntoString(myObj),
success: ...
});
There is no custom processData or contentType set in the ajax call. What really puzzle me is why the previous developers didn't let $.ajax's data attribute to convert the JavaScript object automatically into a URI-encoded string or didn't even try using JQuery.param() to do it but to write the whole function themselves.
For a test, I have made a simple object to test the function encodeJsonIntoString:
var testDataA = {
list: [
{
lastname:"Smith",
firstname:"John"
},
{
lastname:"Black",
firstname:"Jack"
},
{
lastname:null,
firstname:"Mary"
}
]
};
After decoding URI components, the result of the function is:
list[0][lastname=Smith&list[0][firstname=John&
list[1][lastname=Black&list[1][firstname=Jack&
list[2][lastname=null&list[2][firstname=Mary
Notice there are lack of closing square brackets(]) in some places and it uses "null" for null values.
If I run JQuery.param() and decode it, I get this:
list[0][lastname]=Smith&list[0][firstname]=John&
list[1][lastname]=Black&list[1][firstname]=Jack&
list[2][lastname]=&list[2][firstname]=Mary
See the difference? But somehow the result of the function is accepted by the server(Java/Spring - #ModelAttribute) and read into the correct list structure.
I don't have access to the server side here, but I wonder if that array syntax is correctly acceptable or is it just "tolerated" by the server? Will the server see both versions of object in the same structure format?
I am tempted to just replace it with JQuery.param() to handle more robust input data in the future which may also accept special characters.

How to pass an array from Java to Ajax

I am new to Ajax and would have thought there would be plenty of examples of passing an array from java to ajax; however, I have not been able to find them. I want to pass three strings to ajax and then display them in HTML. My java code is:
System.out.println("Authenticated");
String json = new Gson().toJson(questionList);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
The ajax is:
dataType: "json";
alert(responseJson);
var result = $.parseJSON(responseJson); <-- this line fails
$('#question1').val(result.question1);
$('#question2').val(result.question2);
$('#question3').val(result.question3);
The alert displays "Question 1 is a?,Question 2 is b?,Question 3 is c?".
How do I pass each of the strings to display in the HTML. I suspect I need to build the array in java differently as well as receive the result in ajax differently; however, I can not find an applicable example. I do not want to use unstring as the question could contain "," or other delimiter used.
The responseJosn you get from ajax is already been parsed. No need to parse it again. It's an Array. So the JS code would be like:
dataType: "json"; //this line should not be here
alert(responseJson);
//var result = $.parseJSON(responseJson); <-- this line fails
$('#question1').val(responseJson[0]);
$('#question2').val(responseJson[1]);
$('#question3').val(responseJson[2]);

Return 2 variables from the servlet after ajax query

I post to my servlet via AJAX this:
$.ajax({
url: 'myServlet?action=Doeth',
type: 'post',
data: {machine: i, name: txt, status:status}, // i have initilized the values before
success: function (data) {
$('#fep').val(data);
}
});
back in my servlet I have:
if(jspAction.equals("Doeth")){
int status = Integer.parseInt(request.getParameter("status"));
int name = Integer.parseInt(request.getParameter("name"));
String machine = request.getParameter("machine");
//do some stuff and assign in 2 variables
//fep = "a value" and var2="some more"
response.getWriter().write(String.valueOf(fep));
}
So in success the following input is filled with the value fep
<input id="fep" class="form-control" name="fep" required>
If I want to return not only one value but 2 from the servlet (lets say the variable var2, how I do this? I tried
response.getWriter().write(String.valueOf(fep));
response.getWriter().write(String.valueOf(var2));
but it didn't work
A Servlet can't return multiple results. It's function is to handle an HTTP request and produce a single corresponding HTTP response.
If you need to pass data in the response, you need to choose an appropriate format and serialise it. The most common thing you can use, is JSON.
JSON is a text - based data format, that can represent complex objects and data structures. There is also a wide variety of libraries for working with it.

Get data from Http request in servlet

I am sendin post request from jquery like this :
$.ajax({
type: "POST",
url: "Save",
data: { conr: conr ,expiry : expiry,settings : settings}
inside servlet , i am able to get parameters (conr , expiry , settings)
but the problem is that
the settings parameter contains serialized form data : like this :
high=true&ci=false&title=qTip+as+Button+Menu&private=true&email=abc#google.com
I know that i can use string tokenizer to get data but i want to make sure that- if their is any simple way or not?
You could use the HttpComponents and let URLEncodedUtils parse it for you.
So you could just invoke URLEncodedUtils.parse(yourString,Charset.forName("UTF-8")) and you receive as return a List<NameValuePair> containing name and value associated elements. In this case something like: hight = "true", title = "qTip as Button Menu" and so on. And this all with the right decoded.
You can also use split on the settings string with "&" as a regex.

how to pass java beans to jsp page for jqQrid to display using json?

we are trying to use jqGrid with our jsp front end and java back end.
this page is displaying a grid of contacts :
jQuery(document).ready(function(){
jQuery("#list").jqGrid({
datatype: 'json',
url:'gridContactDrv.jsp',
mtype: 'GET',
height:300,
width:600,
colNames:['First Name','Last Name', 'Company', 'Primary Phone','Email'],
colModel :[
{name:'firstname', index:'firstname', width:100},
{name:'lastname', index:'lastname', width:100 },
{name:'company', index:'company', width:100},
{name:'phone', index:'phone', width:100 },
{name:'email', index:'email', width:200}
],
pager: '#pager',
rowNum:10,
rowList:[10,20,30],
sortname: 'lastname',
sortorder: 'desc',
viewrecords: true
});
});
gridContactDrv.jsp calls a search function which return a Vector of ContactBeans. In our current (old) way, we loop through the vector, hook out the 5 fields in each bean and contruct a HTML table.
now we want to use json and i can't figure out how to contruct a valid json (obect? array?) to pass to the grid.
Enumeration e = resultVector.elements();
while (e.hasMoreElements())
{
ContactBean c = ContactBean((ContactBean)e.nextElement());
c.getCompany()
c.getFirstName() etc etc and what to do?
}
btw the ContactBean has many other data members but we are only displaying the 5 fields.
can someone give me some pointers to start? i have searched for a few days and feel like not getting anywhere.
Have you looked at the JSONWriter class from json.org?
Quoting from the API docs:
new JSONWriter(myWriter)
.object()
.key("JSON")
.value("Hello, World!")
.endObject();
which writes
{"JSON":"Hello, World!"}
You need to:
Configure your jqGrid instance to expect JSON data
Have something (servlet?) on back-end that would handle JSON request. You could, of course, output grid data as JSON in the same JSP that renders jqGrid but that would largely defeat the purpose (especially for large volumes of data if pagination is involved).
Use JSON library like json-lib to marshall your beans into JSON. I personally like XStream but there are many various implementations available.

Categories

Resources