Can anyone tell me how to pass JavaScript values to Scriptlet in JSP?
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);
%>
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.
simple, you can't!
JSP is server side, javascript is client side meaning at the time the javascript is evaluated there is no more 'jsp code'.
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>
You cannot do that but you can do the opposite:
In your jsp you can:
String name = "John Allepe";
request.setAttribute("CustomerName", name);
Access the variable in the js:
var name = "<%= request.getAttribute("CustomerName") %>";
alert(name);
If you are saying you wanna pass javascript value from one jsp to another in javascript then use URLRewriting technique to pass javascript variable to next jsp file and access that in next jsp in request object.
Other wise you can't do it.
Its not possible as you are expecting. But you can do something like this. Pass the your java script value to the servlet/controller, do your processing and then pass this value to the jsp page by putting it into some object's as your requirement. Then you can use this value as you want.
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).
I Used a combination of the scriptlet, declaration, and expression tags...
<%!
public String st;
%>
<%
st= "<html> <script> document.writeln('abc') </script> </html>";
%>
<%=
" a " + st + " <br> "
%>
The above code is working completely fine in my case.
Related
I am attempting to call a java class function inside javascript that is inside a jsp page.
I've imported it...
<%# page language="java" import="myPackage.*"%>
I've constructed the class
<%
myClass myJavaInstance =new myClass();
System.out.println("this worked!");
%>
I have a bit of javaScript with an alert message in it
<script>
alert("hello ");
</script>
But when I add this line...
var thisHere = <%= myJavaInstance.getName() %>
before the alert it doesn't show up
<script>
var thisHere = <%= myJavaInstance.getName() %>
alert("hello ");
</script>
If I put it after the alert it shows up
<script>
alert("hello ");
var thisHere = <%= myJavaInstance.getName() %>
</script>
I know the method gets called because I put a println in it.
What am I missing here? It should work right?
The result of myJavaInstance.getName() is probably a string like "Nikos". The rendered output in JS will be:
var thisHere = Nikos
Which is not valid JS (Nikos is undefined). So surround it with quotes:
var thisHere = "<%= myJavaInstance.getName() %>";
Additionally you should escape the string for any quotes found inside it.
Use the console. Looks like you have a syntax error, you need to put quotes around strings in javascript. When the script errors out it stops executing the rest of the script. That's why when you put it before the alert and it errors out it wont execute the alert, but if you put it after it does the alert and then errors out.
<script>
var thisHere = "<%= myJavaInstance.getName() %>"
alert("hello " + thisHere);
</script>
I want To create Portlet For Monitoring Something, so it need like automatically refresh portlet page every interval of time, how i can achieve this? I've been trying with normal method like using Javascript but its didn't work... Thanks, please give me example :(
any help would be really appreciate
i'm trying using normal code for jsp but it's cant run
<%# page import="java.io.*,java.util.*" %>
<html>
<head>
<title>Auto Refresh Header Example</title>
</head>
<body>
<center>
<h2>Auto Refresh Header Example</h2>
<%
// Set refresh, autoload time as 5 seconds
response.setIntHeader("Refresh", 5);
// Get current time
Calendar calendar = new GregorianCalendar();
String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
String CT = hour+":"+ minute +":"+ second +" "+ am_pm;
out.println("Crrent Time: " + CT + "\n");
%>
</center>
</body>
</html>
Regards
Danial
I'm Managed to solve this problem using this code
<%#page import="com.liferay.portal.kernel.portlet.LiferayWindowState"%>
<%#page import="java.util.Date"%>
<%# taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
$.post('<portlet:renderURL windowState="<%= LiferayWindowState.EXCLUSIVE.toString() %>"></portlet:renderURL>', function(data){
$("#myportlet").html(data);
})
}
timedRefresh(5000);
// -->
</script>
<div id="myportlet"><%= new Date() %></div>
Thanks to #boky who give me the main idea how to solve this problem :)
Regards
Danial
If you want update your portlet at regular interval, you can make use of serveResource method.
Make an ajax call to serveResource method and you can set setTimeout on this ajax call. Following is the sample code snippet -
function <portlet:namespace />get_updated_data() {
var f = jQuery.ajax({
type: "POST",
url: '<<resourceUrl>>',
data: {"name" : "val"},
dataType: 'json',
async: false,
}).success(function(data){
// success code here
}).complete(function(){
setTimeout(function(){<portlet:namespace />get_updated_data();}, 5000);
});
}
Setting the Refresh header will in -- best case scenario -- refresh the whole page (that's what it's meant to do) and not just your portlet.
How you set up this refresh depends on your underlying technology for writing the portlet. Basically you want to do an AJAX request to your page to fetch the new data and redisplay it, as #harishkrsingla suggested.
If your code is pure JSP, you would set up two pages:
- one for displaying the portlet
- the other that's rendering the content
Your portlet page would then look something like this (really writting this off the top of my head, check documentation online):
<div id="portlet">
<jsp:include file="data.jsp" />
</div>
<script type="text/javascript">
// assuming jquery
var load;
load = function() {
$('#portlet').load('<portlet:namespace />/data.jsp', function() {
window.setTimeout(load, 1000);
});
}
load();
</script>
Also check out the working demo on JSFiddle: http://jsfiddle.net/z9az9/1/
Of course, this is just the basic idea. You should really include some error handling etc.
I am trying to find a way to invoke a piece of java code within the JSP using HTML form
<form method="get" action="invokeMe()">
<input type="submit" value="click to submit" />
</form>
<%
private void invokeMe(){
out.println("He invoked me. I am happy!");
}
%>
the above code is within the JSP. I want this run the scriptlet upon submit
I know the code looks very bad, but I just want to grasp the concept... and how to go about it.
thanks
You can use Ajax to submit form to servlet and evaluate java code, but stay on the same window.
<form method="get" action="invokeMe()" id="submit">
<input type="submit" value="click to submit" />
</form>
<script>
$(document).ready(function() {
$("#submit").submit(function(event) {
$.ajax({
type : "POST",
url : "your servlet here(for example: DeleteUser)",
data : "id=" + id,
success : function() {
alert("message");
}
});
$('#submit').submit(); // if you want to submit form
});
});
</script>
Sorry,not possible.
Jsp lies on server side and html plays on client side unless without making a request you cannot do this :)
you cannot write a java method in scriptlet. Because at compilation time code in scriptlet becomes part of service method. Hence method within a method is wrong.
How ever you can write java methods within init tag and can call from scriptlet like below code.
<form method="get" action="">
<input type="submit" value="click to submit" />
</form>
<%
invokeMe();
%>
<%!
private void invokeMe(){
out.println("He invoked me. I am happy!");
}
%>
Not possible.
When the form is submitted, it sends a request to the server. You have 2 options:
Have the server perform the desired action when the it receives the request sent by the form
or
Use Javascript to perform the desired action on the client:
<form name="frm1" action="submit" onsubmit="invokeMe()"
...
</form>
<script>
function invokeMe()
{
alert("He invoked me. I am happy!")
}
</script>
You can't do this since JSP rendering happens on server-side and client would never receive the Java code (ie. the invokeMe() function) in the returned HTML. It wouldn't know what to do with Java code at runtime, anyway!
What's more, <form> tag doesn't invoke functions, it sends an HTTP form to the URL specified in action attribute.
**<%# page import="com.ampliflex.commons.Ampliflex" %>**
<html>
<head>
<title>Search Result </title>
<style>
img{ height: 150px; float: left; border: 3;}
div{font-size:10pt; margin-right:150px;
margin-left:150px; }
</style>
<script type="text/javascript" src="jquery-1.6.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
**Ampliflex ms = Ampliflex.getInstance();
String mailHost = ms.getMailServer();**
// This function get the search results from Solr server
$("#submit").click(function(){
var query=getquerystring() ; //get the query string entered by user
Here in this, I imported a java class and instantiate its object. but object is not visible and script is generating an error "missing ; before statement
Ampliflex ms = Ampliflex.getInstance(); "...i am not getting why so.
EDIT:
The problem is i need to access this mailHost with in javascript. if i instantiate object with in <%.. %> then mailHost is local variable and am not able to access in javascript tag. is there any solution for it.
You are trying to instantiate java object but, without a scriptlet
it should be some thing like
<%
Ampliflex ms = Ampliflex.getInstance();
String mailHost = ms.getMailServer();
%>
$(document).ready(function(){
//Mail host
var mailHost='<%= mailHost %>';
// This function get the search results from Solr server
$("#submit").click(function(){
var query=getquerystring() ;
And, if you want to invoke method after page is loaded, try using ajax.
Problem here is this line:
Ampliflex ms = Ampliflex.getInstance();
String mailHost = ms.getMailServer();
This is actually Java code. This cannot execute on client side. Use scriptlet tags.
How can I read/access a JSP variable from JavaScript?
alert("${variable}");
or
alert("<%=var%>");
or full example
<html>
<head>
<script language="javascript">
function access(){
<% String str="Hello World"; %>
var s="<%=str%>";
alert(s);
}
</script>
</head>
<body onload="access()">
</body>
</html>
Note: sanitize the input before rendering it, it may open whole lot of XSS possibilities
The cleanest way, as far as I know:
add your JSP variable to an HTML element's data-* attribute
then read this value via Javascript when required
My opinion regarding the current solutions on this SO page: reading "directly" JSP values using java scriplet inside actual javascript code is probably the most disgusting thing you could do. Makes me wanna puke. haha. Seriously, try to not do it.
The HTML part without JSP:
<body data-customvalueone="1st Interpreted Jsp Value" data-customvaluetwo="another Interpreted Jsp Value">
Here is your regular page main content
</body>
The HTML part when using JSP:
<body data-customvalueone="${beanName.attrName}" data-customvaluetwo="${beanName.scndAttrName}">
Here is your regular page main content
</body>
The javascript part (using jQuery for simplicity):
<script type="text/JavaScript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript">
jQuery(function(){
var valuePassedFromJSP = $("body").attr("data-customvalueone");
var anotherValuePassedFromJSP = $("body").attr("data-customvaluetwo");
alert(valuePassedFromJSP + " and " + anotherValuePassedFromJSP + " are the values passed from your JSP page");
});
</script>
And here is the jsFiddle to see this in action http://jsfiddle.net/6wEYw/2/
Resources:
HTML 5 data-* attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Include javascript into html file Include JavaScript file in HTML won't work as <script .... />
CSS selectors (also usable when selecting via jQuery) https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Getting_started/Selectors
Get an HTML element attribute via jQuery http://api.jquery.com/attr/
Assuming you are talking about JavaScript in an HTML document.
You can't do this directly since, as far as the JSP is concerned, it is outputting text, and as far as the page is concerned, it is just getting an HTML document.
You have to generate JavaScript code to instantiate the variable, taking care to escape any characters with special meaning in JS. If you just dump the data (as proposed by some other answers) you will find it falling over when the data contains new lines, quote characters and so on.
The simplest way to do this is to use a JSON library (there are a bunch listed at the bottom of http://json.org/ ) and then have the JSP output:
<script type="text/javascript">
var myObject = <%= the string output by the JSON library %>;
</script>
This will give you an object that you can access like:
myObject.someProperty
in the JS.
<% String s="Hi"; %>
var v ="<%=s%>";
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
<title>JSP Page</title>
<script>
$(document).ready(function(){
<% String name = "phuongmychi.github.io" ;%> // jsp vari
var name = "<%=name %>" // call var to js
$("#id").html(name); //output to html
});
</script>
</head>
<body>
<h1 id='id'>!</h1>
</body>
I know this is an older post, but I have a cleaner solution that I think will solve the XSS issues and keep it simple:
<script>
let myJSVariable = <%= "`" + myJavaVariable.replace("`", "\\`") + "`" %>;
</script>
This makes use of the JS template string's escape functionality and prevents the string from being executed by escaping any backticks contained within the value in Java.
You could easily abstract this out to a utility method for re-use:
public static String escapeStringToJS(String value) {
if (value == null) return "``";
return "`" + value.replace("`", "\\`") + "`";
}
and then in the JSP JS block:
<script>
let myJSVariable = <%= Util.escapeStringToJS(myJavaVariable) %>;
</script>
The result:
<script>
let myJSVariable = `~\`!##$%^&*()-_=+'"|]{[?/>.,<:;`;
</script>
Note: This doesn't take separation of concerns into consideration, but if you're just looking for a simple and quick solution, this may work.
Also, if you can think of any risks to this approach, please let me know.