Can anyone tell me how to pass JavaScript values to Scriptlet in JSP?
9 Answers
I can provide two ways,
a.jsp,
<html>
<script language="javascript" type="text/javascript">
function call(){
var name = "xyz";
window.location.replace("a.jsp?name="+name);
}
</script>
<input type="button" value="Get" onclick='call()'>
<%
String name=request.getParameter("name");
if(name!=null){
out.println(name);
}
%>
</html>
b.jsp,
<script>
var v="xyz";
</script>
<%
String st="<script>document.writeln(v)</script>";
out.println("value="+st);
%>
2 Comments
<script>document.writeln(v)</script>Your javascript values are client-side, your scriptlet is running server-side. So if you want to use your javascript variables in a scriptlet, you will need to submit them.
To achieve this, either store them in input fields and submit a form, or perform an ajax request. I suggest you look into JQuery for this.
Comments
I've interpreted this question as:
"Can anyone tell me how to pass values for JavaScript for use in a JSP?"
If that's the case, this HTML file would pass a server-calculated variable to a JavaScript in a JSP.
<html>
<body>
<script type="text/javascript">
var serverInfo = "<%=getServletContext().getServerInfo()%>";
alert("Server information " + serverInfo);
</script>
</body>
</html>
1 Comment
This is for other people landing here. First of all you need a servlet. I used a @POST request. Now in your jsp file you have two ways to do this:
The complicated way with AJAX, in case you are new to jsp: You need to do a post with the javascript var that you want to use in you java class and use JSP to call your java function from inside your request:
$(document).ready(function() { var sendVar = "hello"; $('#domId').click(function (e) { $.ajax({ type: "post", url: "/", //or whatever your url is data: "var=" + sendVar , success: function(){ console.log("success: " + sendVar ); <% String received= request.getParameter("var"); if(received == null || received.isEmpty()){ received = "some default value"; } MyJavaClass.processJSvar(received); %>; } }); }); });The easy way just with JSP:
<form id="myform" method="post" action="http://localhost:port/index.jsp"> <input type="hidden" name="inputName" value=""/> <% String pg = request.getParameter("inputName"); if(pg == null || pg.isEmpty()){ pg = "some default value"; } DatasyncMain.changeToPage(pg); %>; </form>
Of course in this case you still have to load the input value from JS (so far I haven't figured out another way to load it).