getting error while passing value from javascript to scriplet in jsp - javascript

I have a requirement where i need to pass a value from Javascript to a Scriplet in a JSP. i am aware that javascript is executed on client side and jsp on the server side.i have searched online and googled a lot but till now i am not able to find a solution that i am looking for. The JSP code is as below. both javascript and scriplet are in same jsp.
<script type="text/javascript">
var strUrl = window.location.href;
var aps = strUrl.toLowerCase().indexOf("values");
var modifiedString = strUrl.substring(aps+8);
var v = strUrl.indexOf(modifiedString);
document.write(v);
</script>
<%
String st="<script>document.writeln(v)</script>";
out.println("-----"+st);
int pareseValue = Integer.parseInt(st);
if(st.equals("0")){
out.println("test");
%>
<h1><div class="xyz">
<fmt:message>header.txt</fmt:message>
</div></h1>
<%
}else{
%>
<div class="pqr">
<fmt:message>header1.txt</fmt:message>
</div>
<%
}
%>
In the above code i am trying to pass a value from Javascript to a scriplet.
But i am getting a NumberFormatException when i try to parse that string and convert to int. looks like the variable st is not of a string type.
String st="<script>document.writeln(v)</script>";
out.println("-----"+st);
int pareseValue = Integer.parseInt(st)
Can you please let me know what is the problem with the above code and how can i resolve the problem that i am facing now.
Thanks
Vikeng

The reason why you can't parse "<script>document.writeln(v)</script>" as an int is because it contains characters other than digits.
Even though it looks like it contains <script> tags - it's still not code that will execute or evaluate to a number. Because it's in quotes it's just a string. So "<script>document.writeln(v)</script>" looks the same to the parser as would "tic/v)neiwtm>oprs<citdun.rtl(<rp>".
This is somewhat of a moot point however, because unfortunately, you can't pass values to scriptlets. It's completely one-directional.
In order to get your page communicating with your java, you'll need to pass your params while requesting some handler.
For example, you could do some asynchronous JavaScript:
var asyncHR = new XMLHttpRequest();
var URL = "https://www.yourserver.com/intparser?st=v";
asyncHR.open("GET", URL, true);
asyncHR.send();
Then your request handler could take that parameter st, parse it or whatever you need to do, modify the model - adding this new value as an attribute, and then from JavaScript, reload the page.

Related

JSP - how to pass a javascript var in session.setAttribute? [duplicate]

This question already has answers here:
Pass Javascript Value to Java in JSP
(2 answers)
Closed 7 years ago.
New to learning JSP, and trying out passing data between two pages.
I'm wondering if it is possible to pass a javascript variable to session.setAttribute()
At the moment, I can pass a string of text through 2 jsp files like so:
JSP1:
<% String text = "hello";
session.setAttribute("test", text);%>
JSP2:
var someText = "<%=session.getAttribute("test")%>"
which works fine.
However, is it possible to pass through a var into session.setAttribute instead? I store some data in a javascript variable and would like to send it across to the second JSP file.
So for example:
var number = 7;
<%session.setAttribute("test", number);%>
I've tried this out and I get the error "number cannot be resolved to a variable"
Thanks!
You cannot do that since javascript executes on client & JSP executes on server side.
If you want to set javascript variable to JSP session, then you pass this variable through the URL like this
var number = 7;
window.location="http://example.com/index.jsp?param="+number;
Now receive this var in your JSP page like this
String var = request.getParameter("param");
Now set it in session
session.setAttribute("test", var);
EDIT :
var number = 7;
<%session.setAttribute("test", number);%>
In the above code, server will only execute the code inside <% %>. It does not know anything outside of the JSP tags. So, it will also dont know about your javascript variable number.
Server executes the code & the result will be sent to the browser, then your browser will execute that javascript code var number=7;.
Hope, now it is clear for you.

Pass variable from JSP to Javascript

Inside a JSP, I am fetching data from a Servlet by this code
<%
String name=(String)request.getAttribute("filepath");
%>
I want to access this inside script tags, how should i go about it?
I tried this var n = "${name}" and var n = "<%=name%>" and it did not work.
Make sure the assignment in scriptlet is working. Try System.out.println(name); to see if the value is set correctly.
I often use the latter
var n = "<%=name%>";
Both options should work fine (do not forget the ;).
Just remember that the scriptlet/ EL are executed when the page is returned from the server and the JavaScript when the browser parse the HTML.
To debug this issue I would use scriptlet first and look if I have a value using browser "view source".
If you do not see any value i.e.
var n = "";
You did not set the attribute correctly in java.
As for EL usage. Make sure you have the correct setting, in older version EL was disabled by default see
http://www.mkyong.com/spring-mvc/modelandviews-model-value-is-not-displayed-in-jsp-via-el/

sending parameters from ASP.NET to javascript

I want to call a javascript function from my ASP.NET (C#) code, I want to pass a variable (string) with another string like below:
tag_label.Attributes.Add("onmouseover", "tooltip.show('my text'+'"+myString+"'<br/>'another text);");
how should I pass these values? also I want to have new line in my tooltip (<br/>), what should I do? I've tried several ways (using ', + and other methods) to send all these values but I get javascript error, is there any sample? please help me
thanks
In that function, you could use the server side code tag.
var string = "<% = myString%>"
You are very close, keep in mind that when controls are generated on the server they are 'unrolled' into HTML on the client -- in other words the '+' sign is unnecessary as the client will only ever see the string (it has no notion of which part of the attribute value was generated in code vs. which part is hard coded on the server).
var toolTip = string.Format("This is text was added on {0}:{1}<br />this text is hard-coded", DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString()
var attributeValue = string.Format("tooltip.show('{0}')");
tag.Attributes.Add("onmouseover", attributeValue);
Try this:
tag_label.Attributes.Add("onmouseover", "tooltip.show('my text','"+myString+"<br/>another text');");
Two ways:
Method 1 (Jon Martin's way): Have a javascript variable populated by server information
Create a javascript variable on the aspx page: var myString = '<%= _mytring %>';
Populate _mystring on the code behind: public String _mystring = "your value";
Method 2: Just dump the variable out from the server side
Page.ClientScript.RegisterStartupScript(getType(Page), "var myString = '" + "your value" + "';", true);

How to get the value of an ASP.net variable into a javascript textbox

I'm writing some Javascript code for an ASP.net page.
I have the string "foo" assigned to a string variable myString.
I would like to assign the value of myString to a JavaScript variable, so I write in my ASP.net code:
<script type='txt/javascript' language='javascript'>
var stringFromDotNet = '<%=myString%>';
</script>
This works fine as long as myString does not contain quotation marks or line-breaks, but as as soon as I try to assign something with quotation marks or line-breaks, all hell breaks loose and my code doesn't work. As a matter of fact, I can see that this code is vulnerable to all sort of injection attacks.
So... What can I do get the value of myString assigned to a variable in JavaScript?
Update: I've tried creating a page with just an ASP:Hidden field. It looks like the values inside are html encoded.
You could use JavaScriptSerializer and that's guaranteed to be safe against XSS:
<script type="text/javascript">
var stringFromDotNet = <%= new JavaScriptSerializer().Serialize(myString) %>;
</script>
This approach also allows you to pass complex objects and not just plain strings:
<script type="text/javascript">
var complexObjectFromDotNet = <%= new JavaScriptSerializer().Serialize(new { id = 123, name = "foo\"' <bar>" }) %>;
alert(complexObjectFromDotNet.name);
</script>
I think this may be the answer are looking for: http://www.velocityreviews.com/forums/t70655-escape-function-in-asp-net.html#edit352659. Basically, encode the value on the server side and unencode it with JavaScript:
var stringFromDotNet = decodeURI(<%=Server.URLEncode(myString)%>);
This will ensure that quotes and other dangerous characters won't break your script, or open up attack vectors.
You could either assign the js variable using double quotes like so
var stringFromDotNet = "<%=myString%>";
Or you could escape the single quotes and replace line breaks with literal "\r\n" in your string in the server side.

JavaScript literal insert vaule? (Too many characters in character literal)

Ok so in my mvc View my "Model" is a list of objects and in this case i want to get a specific Id of one of the objects.
var counter = 0; //for example
var id = '<%=Model[' + counter + '].Id %>';
This is what i get :
Compiler Error Message: CS1012: Too many characters in character literal
Thanks!
Yes, the counter variable can't be used as the index for Model[], because it only exists on the client (assuming this snippet was inside of a script html element). When you are creating a view, it might be useful to think of it as a long 'string' that you are constructing (the html returned to the browser). In this case 'counter' is just some characters in your script block that will eventually be interpreted by the browser, so it's not a variable that can be used while building the view. The <%= %> block just returns a string to append (that's what the = sign does).
Perhaps you intended to have the counter variable in it's own C# code block like so:
<% var counter = 0; %>
<script language=javascript>
var id = '<%=Model[counter].Id %>';
</script>
That doesn't really make any sense. You're trying to put together an ASP expression with client-side Javascript in the middle of it. It's nonsensical because the ASP stuff all runs on your server, while the Javascript runs in the client.
Without knowing the rest of what you want to do, it's hard to say how you should proceed.

Categories