So here is what I want to do. I want to have a static HTML and javascript file in Google App Engine (by the way, I can write it in either Java or Python). So I want the user to visit my index.html file and get information from the datastore, but how would I do this?
I understand you must access the datastore from Java or Python, but once I get the data using these languages, how do I make it appear on myindex.html page (preferably without refreshing). I have tried to find this information everywhere, but all I can find is how to access the datastore using the two languages, not how to take that data and put it into my HTML page.
Cheers
The Python or Java app runs on the server, while any Javascript functionality you have is run on the client (in the web browser). AJAX is generally the best way to communicate between the two.
I assume that you had access data from datastore and you would like to show it on index.jsp .
Suppose your data is greeting with property "user" and "content" . then you can write like this in your jsp file.
if (greetings.isEmpty()) {
%>
<p>Guestbook '<%= guestbookName %>' has no messages.</p>
<%
} else {
%>
<p>Messages in Guestbook '<%= guestbookName %>'.</p>
<%
for (Entity greeting : greetings) {
if (greeting.getProperty("user") == null) {
%>
<p>An anonymous person wrote:</p>
<%
} else {
%>
<p><b><%= ((User) greeting.getProperty("user")).getNickname()
%></b> wrote:</p>
<%
}
%>
<blockquote><%= greeting.getProperty("content") %></blockquote>
<%
}
}
%>
You can use GqlQuery to get the data as a python object. Use GqlEncoder to convert from GQL to JSON.
self.response.write() the data to a url.
Then, with javascript, you can make an XMLHttpRequest to get the data from that url, and include the javascript into the html.
A stackoverflow question/answer on the XHR doing a similar task.
Related
I have a form in JSP. I have to populate it based on the request object (from the servlet). How do I use Java Script for accessing request object attributes or if you can suggest me any other better way to populate form dynamically?
You need to realize that Java/JSP is merely a HTML/CSS/JS code producer. So all you need to do is to just let JSP print the Java variable as if it is a JavaScript variable and that the generated HTML/JS code output is syntactically valid.
Provided that the Java variable is available in the EL scope by ${foo}, here are several examples how to print it:
<script>var foo = '${foo}';</script>
<script>someFunction('${foo}');</script>
<div onclick="someFunction('${foo}')">...</div>
Imagine that the Java variable has the value "bar", then JSP will ultimately generate this HTML which you can verify by rightclick, View Source in the webbrowser:
<script>var foo = 'bar';</script>
<script>someFunction('bar');</script>
<div onclick="someFunction('bar')">...</div>
Do note that those singlequotes are thus mandatory in order to represent a string typed variable in JS. If you have used var foo = ${foo}; instead, then it would print var foo = bar;, which may end up in "bar is undefined" errors in when you attempt to access it further down in JS code (you can see JS errors in JS console of browser's web developer toolset which you can open by pressing F12 in Chrome/FireFox23+/IE9+). Also note that if the variable represents a number or a boolean, which doesn't need to be quoted, then it will just work fine.
If the variable happens to originate from user-controlled input, then keep in mind to take into account XSS attack holes and JS escaping. Near the bottom of our EL wiki page you can find an example how to create a custom EL function which escapes a Java variable for safe usage in JS.
If the variable is a bit more complex, e.g. a Java bean, or a list thereof, or a map, then you can use one of the many available JSON libraries to convert the Java object to a JSON string. Here's an example assuming Gson.
String someObjectAsJson = new Gson().toJson(someObject);
Note that this way you don't need to print it as a quoted string anymore.
<script>var foo = ${someObjectAsJson};</script>
See also:
Our JSP wiki page - see the chapter "JavaScript".
How to escape JavaScript in JSP?
Call Servlet and invoke Java code from JavaScript along with parameters
How to use Servlets and Ajax?
If you're pre-populating the form fields based on parameters in the HTTP request, then why not simply do this on the server side in your JSP... rather than on the client side with JavaScript? In the JSP it would look vaguely like this:
<input type="text" name="myFormField1" value="<%= request.getParameter("value1"); %>"/>
On the client side, JavaScript doesn't really have the concept of a "request object". You pretty much have to parse the query string yourself manually to get at the CGI parameters. I suspect that isn't what you're actually wanting to do.
Passing JSON from JSP to Javascript.
I came here looking for this, #BalusC's answer helped to an extent but didn't solve the problem to the core. After digging deep into <script> tag, I came across this solution.
<script id="jsonData" type="application/json">${jsonFromJava}</script>
and in the JS:
var fetchedJson = JSON.parse(document.getElementById('jsonData').textContent);
In JSP file:
<head>
...
<%# page import="com.common.Constants" %>
...
</head>
<script type="text/javascript">
var constant = "<%=Constants.CONSTANT%>"
</script>
This constant variable will be then available to .js files that are declared after the above code.
Constants.java is a java file containing a static constant named CONSTANT.
The scenario that I had was, I needed one constant from a property file, so instead of constructing a property file for javascript, I did this.
In JSP page :
<c:set var="list_size" value="${list1.size() }"></c:set>
Access this value in Javascipt page using :
var list_size = parseInt($('#list_size').val());
I added javascript page in my project externally.
<%!
public void runJavaMethod(int id)
{
%>
<%
try{
String icd = request.getParameter("icd");
String inm = request.getParameter("inm");
String istk = request.getParameter("istock");
String sstk = request.getParameter("sstock");
String upr = request.getParameter("uprice");
String spr = request.getParameter("sprice");
r = s.executeQuery("select * from itemsyncdata");
while(r.next())
{
s.executeUpdate("update itemsyncdata set itemcode='"+icd+"',itemname='"+inm+"',instock='"+istk+"',storestock='"+sstk+"',unitprice='"+upr+"',storeprice='"+spr+"' where id='"+a+"'");
}
}
catch(Exception e)
{
e.printStackTrace();
}
%>
<%!} %>
And I am Calling Function from html like
<input type="submit" id="btnSync" value="Sync" class="button" name="Sync" onclick="<%runJavaMethod(r.getInt(1));%>"/>
So We want runJavaMethod Parameter.
onclick="<%runJavaMethod(r.getInt(1));%>"/>
HTML/Javascript Plays on client side and JSP/Java plays on server side.
Simply you can't. You might misunderstand that JSP and HTML/JavaScript existed on same document. Yes but JSP part compiles on server side itself comes to client.
What you can do is you have to make a server request. Most probably look at Ajax requests.
You are trying to mix up two languages i.e., Java and Javascript/html together i.e., onclick is a Javascript event and you can't call runJavaMethod from Javascript.
In simple words, you can't directly call a Java method (present inside the scriptlet) using Javascript because all of your JSP code produces (becomes) html when it is loaded from the server.
So, if you have to fix the issue, upon onclick, you need to call an URL which hits a servlet/controller method on the server to do the job (i.e., executes the business logic).
One more important point is that Scriptlets are legacy code and I strongly suggest not use them to generate or manage the html content, rather use JSTL so that there will be a clear separation between the concerns (i.e., business logic and user interface requirements).
Also, I strongly suggest you read the JSP best practices from here and follow them.
You are mixing to two different things. JSP is server side code and it's rendered response is the HTML that is send back to the browser.Javascript is pure client side in your case.
If you really want invoke a server side processing than create a simple Java script function with Ajax call and get response back which u can use it.
I suggest send all the logic of JSP in backend class not a good practice to put in the jsp. JSP is ideally for UI design.
We know that we can redirect an website by putting this below the tag:
<head>
<meta content=0;url=http://www.google.com http-equiv='Refresh'/>
</head>
But what happen if the link I want to redirect is not google.com but it is stored in a string variable that I processed from my Java code? I know if it load from head down, then it will redirect immediately to that page without going through the following code right? So, how to combine the string that I extracted and let the website to load to that link?
From JSP (or servlet):
<%
response.sendRedirect(redirectURL);
%>
Where redirectURL is the variable containing the page you want to go to.
Ok, finally I figured it out:
First, need to construct the index.jsp and its java class in an web app:
https://netbeans.org/kb/docs/web/quickstart-webapps.html
then in the index.jsp, use this to get variable from that java class and redirect:
<%#page import = "org.mypackage.Webredirect.*" %>
<%Webredirect obj = new Webredirect();%>
<%response.sendRedirect( obj.getName());%>
thank you.
I am in a bit of a pickle :
I have a lot of values which i am setting in a bean in java and then i am getting them in javascript and jsp using scriplets like this :
In My Bean.java :
public void setListValue(String s) { listValue = s; }
public String getListValue() { return listValue; }
Now in my jsp(inside a javascript function) :
input = $input({type:'hidden',id:'ListVal',name:'ListVal',
value: '<%= results.getListValue() %>'});
Sometimes i am using the scriplet code to retrieve parametres in jsp as well.
Normally if a parameter is passed from java file to java file or from jsp file to jsp file , then i use native java encoder and decoder like this :
EncodedHere = URLEncoder.encode(encodedStr,"UTF-8");
DecodedHere = URLDecoder.decode(EncodedHere,"UTF-8");
This works flawlessly for those scenarios but if i have set my variables in java and then i try to retrieve them in javascript or jsp like the afore mentioned way , it fails. I have tried the JSTL way as well , but could not make it work, seems JSTL is not suitable to get values in javascript. Now this scriplet has been flagged as security concern by many. Since it's a huge code base it's very difficult to change that as well.
Does some one have any ideas as to avert this security flaw somehow. In other words, is there a way i can encode the variable in java and get the encoded string in jsp and javascript and then decode it ?
It sounds like your security guys are worried about XSS (cross site scripting) attacks, which means data entered by the user that is re-displayed on a page could have malicious code in it. If that is the case you actually don't want to URL encode the data, you want to XML escape it, i.e replace potentially dangerous characters like < with their corresponding character entity like <. To do this in JSP you can use the <c:out> tag or the fn:escapeXML EL function. This works perfectly fine in javascript code, even if it is a little ugly. In your case it would look something like this:
First escape the javascript before you put it on the request using an escaping library the ESAPI reference implementation:
String jsEscapedValue = ESAPI.encoder().encodeForJavaScript(results.getListValue());
request.setAttribute("listValue", jsEscapedValue);
Then on the page use the <c:out> tag to HTML/XML escape it:
var myJsValue = '<c:out value="${listValue}"/>';
Make sure jstl.jar is on the classpath and be sure to include the correct tag lib at the top of your page.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
I have to design several pages in jsp.
After clicking on the submit button on the first page, the page should be automatically redirected to the second page.
Can you help with a quick example or a link to a tutorial that demonstrates how to implement this?
<%
String redirectURL = "http://whatever.com/myJSPFile.jsp";
response.sendRedirect(redirectURL);
%>
This answer also contains a standard solution using only the jstl redirect tag:
<c:redirect url="/home.html"/>
Just define the target page in the action attribute of the <form> containing the submit button.
So, in page1.jsp:
<form action="page2.jsp">
<input type="submit">
</form>
Unrelated to the problem, a JSP is not the best place to do business stuff, if you need to do any. Consider learning servlets.
Hello there: If you need more control on where the link should redirect to, you could use this solution.
Ie. If the user is clicking in the CHECKOUT link, but you want to send him/her to checkout page if its registered(logged in) or registration page if he/she isn't.
You could use JSTL core LIKE:
<!--include the library-->
<%# taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>
<%--create a var to store link--%>
<core:set var="linkToRedirect">
<%--test the condition you need--%>
<core:choose>
<core:when test="${USER IS REGISTER}">
checkout.jsp
</core:when>
<core:otherwise>
registration.jsp
</core:otherwise>
</core:choose>
</core:set>
EXPLAINING: is the same as...
//pseudo code
if(condition == true)
set linkToRedirect = checkout.jsp
else
set linkToRedirect = registration.jsp
THEN: in simple HTML...
CHECKOUT
Extending #oopbase's answer with return; statement.
Let's consider a use case of traditional authentication system where we store login information into the session. On each page we check for active session like,
/* Some Import Statements here. */
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
}
// ....
session.getAttribute("user_id");
// ....
/* Some More JSP+Java+HTML code here */
It looks fine at first glance however; It has one issue. If your server has expired session due to time limit and user is trying to access the page he might get error if you have not written your code in try..catch block or handled if(null != session.getAttribute("attr_name")) everytime.
So by putting a return; statement I stopped further execution and forced to redirect page to certain location.
if(null == session || !session.getAttribute("is_login").equals("1")) {
response.sendRedirect("http://domain.com/login");
return;
}
Note that Use of redirection may vary based on the requirements. Nowadays people don't use such authentication system. (Modern approach - Token Based Authentication) It's just an simple example to understand where and how to place redirection(s).