So I'm working on an old application and I'm forced to use JSP at the moment, which I'm extremely unfamiliar with (and unfamiliar with most aspects of web development tbh).
I'm generating a JSON Array using JSONSimple in a Java class method, and then invoking that method from a JSP on a GET request to get the JSON. Sounds simple enough.
I was able to get my JSON when accessing the URL in my browser. Now I'm trying to access my JSP page from another application, and that's where I'm having difficulty. The content type of my "JSON" was text/html, and not JSON, so I tried setting the content type to JSON in my JSP, and now nothing is showing up in browser, and my Spring application is giving me this error when I try to get JSON from the URL: Could not read document: No content to map due to end-of-input at....
Here's my JSP:
<%# page import="com.company.Someclass" %>
<% if(request.getMethod().equals("GET")){
response.setContentType("application/json");
Someclass.getJSONArray();
}
else if(request.getMethod().equals("POST")){
//todo
}
%>
Any help would be greatly appreciated as I'm pretty lost at the moment. Thanks!
Fixed this myself. I'm able to get JSON in the browser, but having trouble reading it in my Spring application. but thats another battle. Here's my solution:
<%# page import="com.company.Someclass" %>
<% String ret = "";
if(request.getMethod().equals("GET")){
response.setContentType("application/json");
Someclass.getJSONArray().toJSONString();
}
else if(request.getMethod().equals("POST")){
//todo
}
%>
<%= ret %>
the toJSONString() is a method of json-simple's JSONArray class
Related
I wrote the below code to test the status of msgCode. If the msgCode is not Success it should redirect to error.jsp file. If it is a Success it should stay on the same page . When I ran the code the page always redirects to error.jsp although msgCode is Success. What mistake did I do in my code. Can you please help me if you can. Thank in advance.
<%# page import="com.siebel.SurveyWebService.SurveyTester" %>
<%
SurveyTester tc = new SurveyTester();
tc.getResult();
java.lang.String msgCode = tc.getResult2().getStatusCode();
%>
<%= msgCode%>
<%
if (msgCode.toString() != "Success")
{
response.sendRedirect("error.jsp");
}
%>
First of all, you should use equal method for string comparison. Secondly, even though it's not a problem at the moment but you are creating objects in your jsp and faking the response. tc.getResult2().getStatusCode() is not an actual HTTP response from server.
I have a jsp code, where I fetch some JSON data from JAVA Class file. [Basically openfire users]
Now I get the data successfully, but I want to show this data in HTML table format.
How do I Do this ?
My JSP Code :
<%# page language="java" import="prov.*, java.util.*, java.io.*,java.text.*" contentType="text/html"%>
<%# page errorPage="error.jsp" %>
<%
Openfire tc = new Openfire();
tc.getUsers("192.168.50.218","epvFjHq5RHA614C7");
out.println("Data Is As Below : " + tc.getUsers("192.168.50.218","epvFjHq5RHA614C7"));
%>
And I get Response from the JAVA Class method like this :
[{"username":"abcd","name":"","properties":null},{"username":"admin","email":"admin#example.com","name":"Administrator","properties":null},{"username":"bizdd456d454mnc","email":"bizMNC#bizrtc.com","name":"bidzMNC","properties":null},{"username":"bizddd454mnc","email":"bizMNC#bizrtc.com","name":"bidzMNC","properties":null},{"username":"bizmnc","email":"admin#example.com","name":"511515151515151","properties":{"property":[{"#key":"console.order","#value":"session-summary=1"},{"#key":"console.rows_per_page","#value":"user-summary=8"}]}},{"username":"dhaval","email":"dhaval#bizrtc.com","name":"dhaval","properties":null},{"username":"keyur","email":"keyur#bizrtc.com","name":"keyur","properties":null},{"username":"minz","email":"bizMNC#bizrtc.com","name":"bidzMNC","properties":null},{"username":"patel","email":"rau#example.com","name":"patelbhai","properties":{"property":[{"#key":"console.order","#value":"session-summary=1"},{"#key":"console.rows_per_page","#value":"user-summary=8"}]}},{"username":"rajan","email":"rajan#bizrtc.com","name":"rajan","properties":null},{"username":"+username+","email":"+email+","name":"+name+","properties":null}]
As I am very new to JAVA and JSP I don't know how to parse this data to HTML Table.
So Please help.
You can see here how to do it. You can populate it in Javasript or jQuery, but it is better to use JSTL and not just call java code inside JSPs.
I would suggest you use mustache als template engine.
It allows you to use a HTML fragment as template (store it as resource) where double curly brackets (hence the name Mustache) denote the insertion points.
The full documentation of the Mustache syntax is here and a Java example here. Let us know how it is going.
I want to display JSON & XML using a single jsp page.
at a time only one attribute will come from the java class.
My code something look like this.
<%
String json = (String) request.getAttribute("userRequestedJsonById");
if (!StringUtility.isNullOrEmpty(json)) {%>
<%=json%>
<% } else { %>
<%
String xml = (String) request.getAttribute("searcherRespondedXmlById");
if(!StringUtility.isNullOrEmpty(xml)) {%>
<%#page contentType="text/xml"%>
<%=xml%>
<%}%>
<%}%>
I am having a plugin called JSONVIEW to display the json properly.which doesn't work if it finds content type xml.
Content type is set only on the condition,jsp is including this content type even condition is not satisfied.
I don't know much how jsp set content type works,is there any other way to do this or to restrict to set content type xml on a particular condition.
Thanks.
Setting the content type needs to be done before printing anything out, so you need to get rid of the pointless opening and closing of tags that causes whitespace to be printed. Then you will use response.setContentType():
<%
String json = (String) request.getAttribute("userRequestedJsonById");
if (!StringUtility.isNullOrEmpty(json))
{
response.setContentType("application/json");
out.print(json);
}
else
{
String xml = (String) request.getAttribute("searcherRespondedXmlById");
if(!StringUtility.isNullOrEmpty(xml))
{
response.setContentType("text/xml");
out.print(xml);
}
}
%>
Its also just cleaner if you're going to use Scriptlets to just keep your code block open and use out.print() rather than opening, closing, and then <%=var%>, and opening again. That's just so unreadable.
How can pass json values from jsp to javascript as object via ajax?
I can not use global js variables in jsp because this will lead to json content to be visible in page's source
Here is the scenario that I want to achieve:
url of jsp is opened in browser.
Data is being created in scriptlet and coverted to JSON format
json is "sent" to javascript as object
From above scenario, i understand that javascript must initiate the ajax call to jsp.
The issue with this, that jsp's code will be invoked 2 times:
When page is opened in browser - data is prepared
on each ajax call same code will be called again
Constrains: No jquery, no other libs, no servlets, no additional jsps. :(
EDIT:
There is additional problem, I need to pass multiple json objects to javascript.
I wont be able to do it with response.getWriter().write();
I don't think concatenating all json objects and sending is the correct solution.
The parsing of the received object in javascript http.responseText will be overwhelming.
Why do you need ajax here? If you know that you need to populate some things from server onto jsp page you can do that through scriplets itself:
EX
<%# page import="com.mypackage.PersonDAO" %>
<html>
<body>
<table>
<th>Name</th><th>Email</th><th>Contact</th>
<%
List<Person> myList = PersonDAO.getAllPersons();
for(Person person:myList)
{
%>
<tr>
<td><%=person.getName()%></td>
<td><%=person.getEmail()%></td>
<td><%=person.getContact()%></td>
</tr>
<%}%>
</table>
</body>
</html>
This is a very simple example. You can do more complex things using JSTL.. :)
So there is no jquery, no Servlets, no ajax and no extra jsp's :)
UPDATE
Since you want data in your javascript before page loads you can use jQuery's holdReady() method.
$.holdReady( true );
$.get( url, function() {
// Perform something
$.holdReady( false );
});
See but all modern browsers have developer tools like firebug for mozilla, so any ajax call made will be trapped by them. The only way you can secure them is my encrypting them.. which will complicate things for you... IF you can explain the scenario you are trying to implement may be I can come up with it..
I'm trying to get value from Action using Ajax request, but I'm having problem in using struts tag in javascript to show the value.
Javascript code:
dojo.xhrPost({
url: "dashboard"
,content: myParameterscomp
, handle: function(response, ioargs) {
if (ioargs.xhr.status == 200)
{
var data = "<s:property value='#request.consumptionData'/>"
console.log(data);
}
}
,error: function (data) {
handleError(data.description);
}
});
Java code:
Map request = (Map)context.get("request");
request.put("consumptionData", 43);
I'm getting the value of data as <s:property value='#request.consumptionData'/> on console instead of 43. I'm using struts2. My javascript code is in JSP file. Could anyone please tell me how can I show the value?
You seems to be calling /dashboard page via Ajax from your homepage. And expecting it to send you request attribute consumptionData. This won't work as your JSP does not contain required data. You need to put data in JSP and then fetch the same in Ajax. Convert your response to JSON. The simplest way of doing this would be to put following like of code in your Ajax response JSP.
Dashboard.jsp
{"consumptionData": < "<s:property value='#request.consumptionData'/>"}
And in main page when you load this JSP via ajax, you can parse this JSON output and use data in Javascript.
var json = JSON.parse(response);
var data = eval(json.consumptionData);
Code in browser accepts JSON. You could serialize you request as JSON and embed in you JavaScript file. For example:
var data = <%= toJson(request.get("consumptionData")) %>
If the data is simplely Integer values, you can even directly put the value in the code:
var data = <%= request.get("consumptionData") %>
The syntax could be vary (I'm not familiar with struts tag), but the idea is the same.