This is what I thought a very simple issue. Basically I am trying to send a json string to a REST API service. Here is the JSON they supply
"vslText": "[field1] = '12345678'"
Now to send it to the REST as a string I've tried
String jsonRequest = "{ 'vslText' : '[field1] = " + ""
But I get lost in all the quotes.
I tried using
JSONObject jsonRequest = new JSONObject();
jsonRequest.put("vslText", "[field1] = '12345678'");
but I get this error
An error occurred at line: 18 in the jsp file: /jsp/javaServlet/IDsearch.jsp
JSONObject cannot be resolved to a type
Here is my import clause
<%# page import="java.util.*" %>
<%# page import= "java.io.*" %>
<%# page import= "java.net.*" %>
<%# page import= "org.json.JSONObject" %>
Please give me direction?
Using eclipse I was able to add the .jar to the list of libraries the web app could see. Basically right click on the project and select build path then configure build path. From there, you can go to the libraries tab and add JARS using the interface.
After re-exporting it as a war file this seemed to work.
Related
I'm building a practice Web API with Ruby + Sinatra and I want my responses to be displayed in a ERB template with formatted JSON (GeoJSON). So far I've been able to process the request and format the response correctly.
However, I can't find a way to display the contents in the endpoint as a JSON string, and it displays as a regular string (difficult to read for JSON). Is there any way to do that in Ruby + Sinatra without using JavaScript?
Here's what I've got so far in both files.
# app.rb
before do
json = File.open("data/cities.json").read
data = JSON.parse(json)
data.each do |item|
geoarray["features"].append(json_to_geojson(item))
end
#geojson = geoarray.to_json
end
...
get('/myendpoint') do
#activities = #geojson
erb :cities
end
<!--cities.erb-->
<%= #activities %>
try <%= #activities.to_json.html_safe %>
You can make JSON string look prettier by using JSON.pretty_generate() method.
# app.rb
before do
json = File.open("data/cities.json").read
data = JSON.parse(json)
data.each do |item|
geoarray["features"].append(json_to_geojson(item))
end
# use pretty_generate instead of to_json
#geojson = JSON.pretty_generate(geoarray)
end
And In your erb file. Instead of simple showing it, add <pre> tag to it.
<!--cities.erb-->
<pre><%= #activities %></pre>
reference
I have the following jsp
<%
JSONObject jsonResult = new JSONObject();
response.setContentType("application/json");
String parentNodePath = slingRequest.getRequestPathInfo().getResourcePath();
String url = getServerBaseUrl(sling) + parentNodePath.split("/jcr:content")[0] + ".html?cid=twitter";
UrlShortener urlShortener = sling.getService(UrlShortener.class);
String shortUrl = urlShortener.shorten(url);
String encShortUrl = URLEncoder.encode(shortUrl);
jsonResult.put("url", url);
jsonResult.put("shortUrl", shortUrl);
jsonResult.put("encShortUrl", encShortUrl);
%>
<%=jsonResult.toString()%>
It executed when I type in browser the following adress http://servername:port/path/to/page.urlshortener.html.jsp
As you see i have "application/json" contentType. Result must contain only json information, but there is html comment:
{
"url":"http://servername/content/app/test/test1/naps1.html?cid=twitter",
"shortUrl":"http://servername/1E4sZYJ",
"encShortUrl":"http%3A%2F%2Fservername%2F1E4sZYJ"
}
<!--
cq{
"decorated":false,
"type":"app/components/page/newsarticlepage",
"path":"/content/app/test/test1/naps1/jcr:content",
"selectors":"urlshortener",
"servlet": "Script/apps/app/components/page/contentpage/urlshortener.html.jsp","totalTime":276,"selfTime":276
}
-->
Also i saw, this comments inserted after every component, or executed jsp in any page.
How to turn off insertion of this comment?
The comments <!-- cq{ ... } --> are added for the authoring interface. They are not included on the publish instance where wcmmode is disabled. You can see this by adding wcmmode=disabled as a query param to the end of your url. Also you will have to remove the cf# or editor.html from the url.
I'm writing a simple jsp code for login which retrieves data from mysql. The code is showing error at response.sendRedirect("feedback.jsp");
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%
String user=request.getParameter("username");
String passwrd=request.getParameter("password");
try{
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/feedback", "root", "");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select username,password from users");
while(rs.next())
{
String username=rs.getString(1);
String password=rs.getString(2);
if(user.equals(username) && passwrd.equals(password))
{
response.sendRedirect("feedback.jsp");
}
else
{
out.println("Invalid Credentials");
}
}
}
catch(NumberFormatException e){
System.out.print(e);
e.printStackTrace();
}
%>
The connection to database is working as the else statement of "Invalid Credentials" is working if incorrect username and password combination is entered. The error i'm getting is "Cannot call sendRedirect() after the response has been committed"
Thanks.
if the URL is absolute http://www.google.com , it redirects to
http://www.google.com.
If the URL is not absolute , it redirects
relative to the current URL. If the URL starts with / it redirects
relative to the context root, Else it redirects to the current url
You should return after redirecting.
response.sendRedirect("http://www.google.com");
return;
It does not return automatically after calling sendRedirect().
First of all, Java code connecting to a database should be inside a servlet, and not inside a JSP. JSPs are view components. They should not use scriptlets AT ALL. Their only responsibility should be to generate HTML from attributes stored in the request by a controller, written in Java.
You get this exception because you try to redirect after sending data to the response already. Sending a redirect consists in setting a response header. And the headers are sent before the response body.
Also, your strategy for finding a user is extremely inefficient. You have the user name. So instead of getting all the users from the database and comparing them one by one with the username you have, you should add a where clause to your query:
select username, password from user where username = ?
Read the Java tutorial about prepared statements.
And finally, storing passwords in clear text in the database is a very bad practice. They should be hashed using a strong cryptographic hashing algorithm.
This is usually because you have sent response to the client, and you are changing or trying to send response after it is being sent to the user. Try removing any spaces or output before your redirect statement. In this case I would suggest remove all white-spaces before <% and then try executing your code.
I want an external webpage rates.appiclife.com to be rendered in the applications <%=yield%>.
I tried this:
I placed the following method in pages_controller.rb
def fetch_url(url)
r = Net::HTTP.get_response( URI.parse( url ) )
if r.is_a? Net::HTTPSuccess
r.body
else
nil
end
end
In the same file:
def showexternal
#snippet = fetch_url "http://rates.appiclife.com/"
end
And in the showexternal.html.erb view/pages:
<%= #snippet %>
I get the following error: incompatible character encodings: UTF-8 and ASCII-8BIT
Is it even possible to do this? The thing is that those prices are updated and received in an excel file, so a lot of work to adapt them if I just place them in a html-table.
You should be able to parse the request response with Nokogiri into a string and then do whatever you want to with it. You can find a quick tutorial here:
http://nokogiri.org/tutorials/parsing_an_html_xml_document.html
Is it possible in one JSP to make a jQuery ajax callback to another JSP and have data returned?
I am trying to make the ajax call to Page2.jsp in the $(document).ready call in Page1.jsp
I am attempting to get JSON returned by "Page2.jsp"
I am running Tomcat locally to test.
I am seeing the JSON printed to the console, but not returned to the original calling method in Page1.jsp
Any ideas?
Page1.jsp
$(document).ready(function(){
$.ajax({
url : 'Page2.jsp',
dataType: 'json',
success : function(json)
{
var obj = jQuery.parseJSON(json);
}
});
});
Page2.jsp
<%#page contentType="application/json; charset=UTF-8"%>
<%#page import="org.json.simple.JSONObject"%>
<%
JSONObject json = new JSONObject();
json.put("amount","55.00");
json.put("tax","1.00");
String jString = JSONObject.toJSONString(json);
PrintWriter out = response.getWriter();
out.println(jString);
out.close();
%>
I tried the code in your question and the jQuery.parseJSON() code throw the following error: "SyntaxError: JSON.parse: unexpected character". On debugging I saw that the servlet code generated by tomcat includes out.write("\r\n"); I suspect that these character are causing the syntax error.
Nevertheless in the javascript I tried accessing the returned object using the dot notation without parsing it and I was able to so as if it were a JSON object. It appears that it is not necessary to parse the returned object.
The only modification I made to the JSP code was to remove the lines PrintWriter out = response.getWriter(); and out.close();