What I'm trying to do today is to directly call a Javascript function from a JSP Servlet response. What does that mean? Here's the code:
Servlet, This is contained in myServlet.java
// Takes an XML already previously parsed as a string as input
CharSequence confirm= "something";
if (xml.contains(confirm)) {
// Carry on
// If it is contained we needn't go further
} else {
// "couldn't find confirms content
errorMessage = "Does not contain confirm";
// "If ^ quit this servlet"
request.setAttribute("rol", this.rol);
request.setAttribute("user", this.user);
request.setAttribute("errorMessage", errorMessage);
forwardToJSP(request, response, "/myJSP.jsp");
}
Now In Javascript I already have defined a function I want to be called. It is something along these lines:
Javascript, This is contained in myJSP.jsp
<script language="JavaScript" type="text/JavaScript">
// Assume all document.getElementById calls are properly implemented,
// they call real variables that exist elsewhere, but not shown
// here due to irrelevance.
window.errorExists = function() {
var errorExists = document.getElementById("terror");
errorExists.setAtribute("terror", "Does not contain confirm");
if (errorExists.attributes == "Does not contain confirm"){
if(confirm("Cannot find content, do you wish to add it?")){
anotherFunctionCall();
} else {
// Don't do anything
}
}
}
</script>
Now, in simple terms what I want to do is to call my Javascript function from the aforementioned JSP. I think cannot do so with work arounds such as:
PrintWriter out = response.getWriter();
out.println("<tr><td><input type='button' name='Button' value='Search' onclick=\"searchRecord('"+ argument + "');\"></td></tr>");
Because the other function wouldn't be called, also there's an update to Javascript variables.
How would one go around this?
Any and all help is greatly appreciated.
You can call that method in onload parameter of body of JSP page.
As you are already calling a JSP page using Forward method, your JSP page is getting loaded when you call it. You can call your method in body tag of JSP page as follows:
<body onload="YourMehodName()">
alternatively, you can put this script at the bottom of your JSP which will get called on loading of your page.
Related
Here's my problem:
When I write this in javascript it works
// OK:
alert('<s:property value="#my.package.utils.Util#getSomeInformation(1000)" />');
But when I try to set that value dynamically in the property tag, nothing is being executed.
// NOT OK:
var value = 1000;
alert('<s:property value="#my.package.utils.Util#getSomeInformation(' + value + ')" />');
Can someone please help me in this?
Struts Tags, like JSTL, EL, etc... are executed server side. After all of them are executed, the final page with HTML only is rendered to the client. Only then, javascript can run on the page.
You can't mix javascript and Struts tags.
Also, consider not using static method calls, you can probably do this with a call to an action method, performing the same checks that Util.getSomeInformation method does.
I get the JSONOject from my bean in my helper class.
Inside helper
public JSONObject init() throws Exception{
// initializations codes are here
JSONObject json = JSONObject.fromObject(bean);
return json;
}
Then I need to access above JSONObject inside a jsp calling through ajax request when loading the jsp(to assign javascript variable like bellow)
inside jsp
$(document).ready(function(){
var VAR_JSON = // need to get the JSON through AJAX
});
previously I had a code like this.
<script type="text/javascript">
var VAR_JSON = <%=helper.init()%>
</script>
how can I achive this by AJAX ?
thanks in advance..!!
First of all, stop thinking JSP. The JSP is (part of) what executes on your server when a request is being handled. That in turn returns a response to the browser (usually a webpage); your JavaScript (and therefore your AJAX request) run in the user's browser on that webpage, not in your JSP.
jQuery provides a function specifically designed for getting JSON through an AJAX request; it's called jQuery.getJSON(). You'd use it something like this:
<script type="text/javascript">
$(document).ready(function() {
var VAR_JSON;
function yourFunction() {
// do something with VAR_JSON here
}
$.getJSON('yoururl.do', function(response) {
VAR_JSON = response;
yourFunction();
});
});
</script>
It's important to note that you can't do var VAR_JSON = $.getJSON() because the function is asynchronous, and therefore doesn't return the JSON (it returns something else - see the documentation linked above). You instead need to provide a callback function that will execute when the asynchronous request returns a successful response, which will then set your variable and call another function that uses it.
Also note that you won't need to call something like JSON.parse() because jQuery does that for you; you've told it you're expecting JSON back so it parses that string to get the resulting object or array, which is then in turn passed as an argument to the callback function.
I want to redirect the user into last accessed page after session expire and i prompt user to login again. In that i passed last page url into one parameter and invoke a seesioerror action for validate the user.
I have this code snippet :
<script type="text/javascript">
var currentURL = window.location.href;
</script>
<%
String url= "<script>document.writeln(currentURL);</script>";
Object obj = session.getAttribute("user");
if (obj == null) {
response.sendRedirect(request.getContextPath() + "/SessionError?backurl=" + url);
}
%>
Now my problem is whenever I print the Java String varaible url using <% out.print("URL" + url);%> it correctly print the page URL.
But If pass it on this line response.sendRedirect(request.getContextPath() + "/SessionError?backurl=" + url); inside the snippet. It only pass <script>document.writeln(currentURL);</script> not the current page url like http://www.mysite.com/home. Please help me to get rid of this problem.
JSP is server side language, it will be executed before http response gets back to client. By saying that, you can use JSP variables in javascript but not the other way around.
You can use javascript : document.referrer to get previous url
You should be using
request.getAttribute("javax.servlet.forward.request_uri")
See this question
And please don't mix sciplets and Javascript code. Its a mess.
I have custom tag which contains form with text input and submit. I want to validate this text input using JS, so my custom tag output should look like:
<script type="text/javascript">
function validate(form) {
var text = form.textInput;
// validation code
}
</script>
<form onsubmit='return validate(this);'>
<input type='text' name='textInput'/>
<input type='submit'/>
</form>
(Note, this code simplified!)
My problem appears when I want to use this tag twice or more times at page - I want to print form at page again, but not JS validation code! Validation code must be unique at the page. How can I archive that? My custom tag extends javax.servlet.jsp.tagext.TagSupport
I found the most suitable solution for me.
Class javax.servlet.jsp.tagext.TagSupport contains protected field pageContext which presents... page context! I can easily access context attributes of javax.servlet.jsp.PageContext. So, I put next code in my custom tag:
public int doStartTag() throws JspException {
if (pageContext.getAttribute("validated") == null) {
// validation code writing
pageContext.setAttribute("validated", true);
}
...
}
If condition would be reachable only once per page rendering.
Hope it would be useful for someone.
I suggest you to try to embed that JavaScript function in some .js file an import that file. If you don't want to do that, for some reason you should try to define that function dynamically, if it is not defined:
if (typeof window.validateMyForm === 'undefined') {
window.validateMyForm = function(form) {
var text = form.textInput;
// validation code
}
}
As you guess this should define function only if it is not already defined.
First answer is correct, but that means that programer must know where in code are already inserted custom tags and according to that this whether to set that parameter to true or false. And what about code changes, you will have to always go thought whole page and revise all used tags on a page.
Make the custom tag to accept a parameter that toggles the validation on or off, and of course have it generate different code depending on the value of the parameter.
function add(){
<%if(empRecNum != null && !(empRecNum.equals("")))
{
empSelected=true;
}
boolean canModify = UTIL.hasSecurity("PFTMODFY") && empSelected;
%>
df('ADD');
}
When i click on add, i need to check whether the empSelected is true or not and pass this canModify value. Will this be called?
Is this right way i am checking a Scriptlet inside a JavaScript
A more elagant way to do this
var canModify = Boolean(${canModify});
Use jstl el, it turns more clear what do you intend to do.
The call to boolean will convert the given value in javascript boolean.
Remember:
Boolean(true); // returns true
Boolean(false); // return false
Boolean(); // returns false
You need to get the following concept right: Java/JSP runs at webserver and produces HTML/CSS/JS output. Webserver sends HTML/CSS/JS output to webbrowser. Webbrowser retrieves HTML/CSS/JS output and displays HTML, applies CSS and executes JS. If Java/JSP has done its job right, you should not see any line of Java/JSP code in webbrowser. Rightclick page in webbrowser and choose View Source. Do you see it, right?
The webbrowser has totally no notion about the Java/JSP code on the server side. All it knows about and can see is the HTML/CSS/JS code it has retrieved. The only communication way between webbrowser and webserver is using HTTP requests. In the webbrowser, a HTTP request can be fired by entering URL in address bar, clicking a (bookmark) link, pressing a submit button or executing XMLHttpRequest using JavaScript. In the webserver, the Java/JSP (and Servlet) code can be configured so that it executes on certain URL's only. E.g. a JSP page on a certain location, a Servlet which is mapped on a certain url-pattern, etcetera.
In a nutshell, to have JavaScript to access Java/JSP variables, all you need is to let Java/JSP print them as if it is a JavaScript variable. To have JavaScript to execute Java/JSP methods, all you need is to let JavaScript fire a HTTP request.
See also: Communication between Java/JSP/JSF and JavaScript
The canModify value defined in JSP is never passed to JavaScript. You need to redefine the variable in JavaScript, for example:
<%
if (canModify) { // This is the JSP variable
%>
var canModify = true; // This is the JavaScript variable
<%
} else {
%>
var canModify = false;
<%
}
%>
On a different note, you should abandon JSP scriptlets and switch to JSTL.