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.
Related
Hi i am trying to include a new jsp page on my jsp page in every 10 sec how can i achieve this
i am able to include page but not including according to time
Here is my code
<%# page language="java" contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html>
<head>
<title>Untitled Document</title>
section
{height:70%; background-color:blue; display:block; overflow:auto;}
section .push {height:500px;}
</style>
</head>
<body>
<form action="F1.jsp" method="post">
<%# include file="F2.jsp" %>
<footer>footer</footer>
</form>
</body>
</html>
How can i achieve this
Thanks in advance
If you want to include more content or refresh a section of the page you need to use browser side JavaScript to pull new content from the server.
Once you display something using JSP, that is final. It cannot change unless you provide the mechanisms to change. You can set a refresh rate of your JSP to auto refresh and display each time a new content.
Or you can use AJAX.
How to do it using ajax (I prefer the JQuery version) can be found here at the answer with 5 upvotes
You can set interval in Javascript.
syntax:
setInterval(function(){
// code //
},10000);
In the code you can use Ajax calls which pool the content of JSP from the server.
I am trying to redirect the user from one jsp page to another jsp page after making him wait for 10 seconds or 10000 milliseconds. But there is a redirect as soon as the page is opened in the browser. Why is this is so ? Is there anything wrong in the following code ? I am calling the redirectFunction which does the redirect.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP - 1</title>
<script>
function redirectFunction() {
<% response.sendRedirect("jsp-2.jsp"); %>
}
</script>
</head>
<body>
<h1>
Wait while you are redirected...
</h1>
<script type="text/javascript">
setTimeout(redirectFunc,10000); // wait for 10 seconds,then call redirectFunc
</script>
</body>
You sends redirect exactly from server that`s why it fired immediatelly.
If you want to fire redirect after 10 seconds than you need to change your code:
function redirectFunction() {
window.location.href = "jsp-2.jsp"
}
and setTimeout(redirectFunction,10000);
Actually when you call <% response.sendRedirect("jsp-2.jsp"); %> Java server sets http code 302 to your http response, and header Location: jsp-2.jsp
And browser redirects to page specified in Location header immediately.
Hope it helps.
the code in scriptlet is executed on the server, it is not javascript. use this
function redirectFunction() {
window.location.href = "jsp-2.jsp";
}
Assuming you're using HttpServletResponse, what's happening is that you're sending the HTTP location header with a status code 302. This happens when the page is requested, not during client-side execution of the JavaScript.
If you want it to be during JavaScript execution you need to assign the URL you want to window.location.
window.location = "http://google.com";
for example
This is because
<script>
function redirectFunction() {
<% response.sendRedirect("jsp-2.jsp"); %>
}
</script>
is translated and executed as
out.print(" <script> function redirectFunction() {");
response.sendRedirect("jsp-2.jsp");
out.print("</script>");
The call sendRedirect is executed on the server side, while preparing your page, and it's performing the redirect. You can do the sleep and the redirect in javascript only, using window.location.
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.
Good day!
I encountered the following error upon running my JSP program.
java.lang.IllegalStateException: PWC3991: getOutputStream() has already been called for this response
It seems like the html file inside my JSP doesn't work.
My code is as follows:
<%#page import = "java.util.*"%>
<%#page import = "javax.servlet.*"%>
<%#page import = "javax.servlet.http.*"%>
<%#page import= "session.*" %>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
Item item = (Item) request.getAttribute("invenItem");
if (item != null) {
out.println("<html><title>Inventory Item</title>");
out.println("<body><h1>Inventory Item Details:</h1>");
out.println("Stock ID : " + item.getStockID() + "<br/>");
out.println("Name : " + item.getItemName() + "<br/>");
out.println("Unit Price: " + item.getUnitPrice() + "<br/>");
out.println("On Stock : " + item.getOnStock() + "<br/>");
out.println("</body>");
out.println("</html>");
} else {
RequestDispatcher rd = request.getRequestDispatcher("DataForm.html"); //NOT WORKING
rd.include(request, response);
out.println("<br>Item not found...<br>");
rd = request.getRequestDispatcher("ItemEntry.html"); //NOT WORKING
rd.include(request, response);
}
%>
</body>
</html>
My html Files are located inside the folder WEB-INF. How can I make it work? DO i need to import it also? Thank you.
Don't use scriptlets (those <% %> things). JSP is a template technology for HTML. You don't need all those nasty out.println() things for HTML. Just write HTML plain in JSP.
So, instead of
<%
out.println("<html><title>Inventory Item</title>");
%>
just do
<html><title>Inventory Item</title>
(note that this results in invalid HTML, there should be only one <html> tag in a HTML page and only one <title> in the <head>, but that's a different problem, the w3 HTML validator should give a lot of hints and answers, also get yourself through some HTML tutorials)
JSP offers EL (Expression Language, those ${ } things) to access backend data, i.e. the data which is present as attribute in page, request, session and application scopes. It can be accessed using the attribute name.
So, instead of
<%
Item item = (Item) request.getAttribute("invenItem");
%>
use
${invenItem}
and instead of
<%
out.println("Stock ID : " + item.getStockID() + "<br/>");
%>
use
Stock ID: ${invenItem.stockID}<br/>
JSP also offers taglibs like JSTL to control the page flow and output.
So, instead of
<%
if (item != null) {
} else {
}
%>
use
<c:choose>
<c:when test="${invenItem != null}">
</c:when>
<c:otherwise>
</c:otherwise>
</c:choose>
JSP also offers <jsp:include> tag to include page fragments.
So, instead of
<%
RequestDispatcher rd = request.getRequestDispatcher("DataForm.html"); //NOT WORKING
rd.include(request, response);
%>
use
<jsp:include page="/WEB-INF/DataForm.jsp" />
(and rename it to .jsp)
And the exception will disappear.
See also:
JSP tag info page
How to avoid Java code in JSP files?
Java web development, what skills do I need?
Unrelated to the concrete problem, almost all of the links in this answer was already (in)directly given to you in your previous questions. Take them serious. To become a great programmer (as you ever stated in a question/comment), take some time to get yourself through those links (and the links in the links).
Firstly, try to avoid putting code onto your JSP page - it violates the MVC/separation of concerns paradigm that is a central part of JSP.
Second, plain old JSP's getting a bit old - using JSF/facelets/etc is recommended these days.
As for your actual problem, I'm not totally familiar with the technique you're employing, but the exception basically means that you've tried to send content after the latest point at which your able to (generally, after sending headers). In this case, I think what's happening is that you've already started sending the current page when you ask it to send a different page.
Simplest fix I can think of: rather than trying a conditional include based on results, just redirect to a different page.
The error indicates that the error lines of code cannot be called once something has been printed out to the output stream in jsp (including even the doctype declaration)
So you can try to put those pieces of code at the top of your page.
You can not use
out.print() and Requestdispatcher simultaneously....
It means after execution of out.print() there should not be any execution of statement with requestdispatcher.forward()....
So remove out.println() form else block.
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.