JSP - How do get time to constantly update by ms - java

I am attempting to write an example JSP page for myself (very new to jsp), and have gone over an example to write one, but how do I get time to consistently update?
here is my snippet of code:
<body>
<%
java.text.DateFormat df = new java.text.SimpleDateFormat(
"HH:mm:ss:SS z MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
%>
<h1>
Current Date and Time:
<%=df.format(cal.getTime())%>
</h1>
</body>
By the way i'm using a tomcat server to deploy this

function updateYourTime() {
var now = new Date(),
months = ['January', 'February', '...'];
time = now.getHours() + ':' + now.getMinutes(),
date = [now.getDate(),
months[now.getMonth()],
now.getFullYear()].join(' ');
document.getElementById('currentTime').innerHTML = [date, time].join(' / ');
setTimeout(updateYourTime, 1000);//This method will call for every second
}
updateYourTime(); // initial call
see here for details
<div id="currentTime"></time>

do you mean to show clock in your pages?
you can use java script.
here is an example

to show server clock in clients jsp use this javascripcode with java
Add a label where ever you want to show the server Time
<strong>Server Time : </strong><label id="timelable"></label>
And then add the following java script code at the end of the jsp inside the body tag
<script type="text/javascript">
var myVar = setInterval(function(){ myTimer() }, 1000);
var jsVar= <%=java.util.Calendar.getInstance().getTimeInMillis()%>;
var timeZoneOffset=<%=java.util.TimeZone.getDefault().getOffset(System.currentTimeMillis())%>;
jsVar=jsVar+timeZoneOffset;
function myTimer() {
jsVar=jsVar+1000;
var d = new Date(jsVar);
var t=d.toUTCString();
document.getElementById("timelable").innerHTML = t;
}
</script>
Thats it now you will see the server time running in you jsp.

Related

Changing and loading an iframes src when the link within a file changes/updates

I'm building a page called live_link_frame.php and within it is loading an iframe via a url pulled from a local file: live_link.txt:
<?php
$filePath = 'live_link.txt';
$handle = #fopen($filePath, "r");
$text = fread($handle,filesize($filePath));
$lines = explode(PHP_EOL,$text);
$live_link = reset($lines);
?>
and
<iframe src="<?php echo "$live_link"; ?>"></iframe>
Is there a way to have the iframe src= update with the new value from $live_link when the url is changed in the local file? It doesn't have to be isolated to just php.
Everything I've tried so far ends up being some kind of looping method and causes the live_link_frame.php page to never fully load.
This can be achieved with Javascript:
In your index page, you have some javascript that periodically checks inside live_link.php. You change the value in the makeInterval function to how often you want the file to be checked, 10000 = 10 seconds.
<script>
function makeInterval()
{
getFileAndSetIframe();
let interval = setInterval(getFileAndSetIframe, 10000);
}
function getFileAndSetIframe()
{
let current_src = document.getElementById('changeme').getAttribute('src');
let link = fetch('live_link.php')
.then(response => response.text())
.then((response) => {
if (response !== current_src) {
document.getElementById('changeme').setAttribute('src', response);
}
});
}
window.addEventListener ? window.addEventListener("load",makeInterval,false) : window.attachEvent && window.attachEvent("onload",makeInterval);
</script>
<h1>This is my page</h1>
<iframe src="" id="changeme"></iframe>
Note that if the URLS are of external sites you will probably run into issues.

Writing Dynamic JSP Using Servlet

I store my HTML pages in the database, and I use PrintWriter out = response.getWriter (); to show them. I would like to do the same with my JSP pages it is possible to do this using JspWriter
Example: I have this page in my database, I load this page and would like the code to be processed dynamically (inside servlet).
<%# page import = "java.io.*,java.util.*" %>
<html>
<head>
</head>
<body>
<center>
<%
// 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("Current Time is: " + CT + "\n");
%>
</center>
</body>
</html>
No, it is not possible. The servlet writes HTML (in this case) to the response, and your standard client (web browsers) will understand that.
A JSP, however, is a dynamic page and contains code that the container has to compile and run in order to produce the output for the HTTP response. Writing the content of the JSP to the response would (roughly speaking) send Java code to the client.
If you need dynamic content at that level, perhaps you should look into a custom tag library. Documentation can be found here

play framework : Pass date to view

I need to pass the date parameter to view in play framework
My controller looks like
something.render(new Date());
And on my view what I've done is
#(myDate : Date)
<script lang="text/javascript">
var time = "#(myDate)";
</script>>
This time variable I further need to use in jQuery.
Thing is Play framework is converting the date to string object.
What I want is date object itself.
If I remove the quotes around "#(myDate)" Java script gives following output.
var backupTimeString = 2015-01-15 00:01:28.767;
Uncaught Syntax Error : expecte number
I really need the object to passed as Date object not as String represnetation of Date
1) If you work in local time, you could pass the time as a formatted string :
something.render( ... new java.text.SimpleDateFormat("yyyy/MM/dd hh:mm:ss").format(new java.util.Date()) ...)
and convert it to javascript date in the view :
<script>
var t = new Date("#mydate");
</script>
According to http://dygraphs.com/date-formats.html the format aaaa/mm/jj hh:mm:ss is the most robust.
2) In case you don't work in local time, recent browsers accept ISO-8601 date with offset from UTC, for example :
new Date('2015-01-22T12:00-0600')
3) As a last resort, you can pass a timestamp :
something.render(... new java.util.Date().getTime() ...)
<script>
var t = new Date(#mydate);
</script>

Calling a Javascript function without any event

This is a code written in a.jsp:
<script type="text/javascript" >
function chk(d,e)
{
var x = d.split('/')
var y = e.split('/')
var a = new Date(x[2],x[0],x[1])
var b = new Date(y[2],y[0],y[1])
var c = ( b - a )
var p= c / (1000 * 60 * 60 * 24);
}
</script>
<% String b="2013/07/12";
String c="2013/07/14";%>
<script>
var myVar=chk('$b','$c');
</script>
<body>
<% String st="<script>document.writeln(myVar)</script>";
out.println("value="+st); %>
</body>
I want to get the number of days(i.e. 'p') between these 2 dates(i.e. 'b' and 'c') as the output. But the output I am getting is "value=NaN". What is wrong with this code? Please help.
This question was tricky to answer. First, looks like you want to pass the variables declared in scriptlet to your JavaScript using EL. To accomplish this, you should:
Set the variable in scriptlet as pageContext attribute or request attribute as explained here: How to evaluate a scriptlet variable in EL?
Use JSTL <c:out> to send the variable from EL to your JavaScript function.
Following GauravSharma's answer suggestion, add a return p; at the end of your JavaScript function.
Your code should look like this (at least works for me using Tomcat 7 and prints 2 in the navigator):
<script type="text/javascript">
function chk(d, e) {
var x = d.split('/');
var y = e.split('/');
var a = new Date(x[0], x[1] - 1, x[2]);
var b = new Date(y[0], y[1] - 1, y[2]);
var c = (b - a);
var p = c / (1000 * 60 * 60 * 24);
return p;
}
</script>
<%
String b = "2013/07/12";
String c = "2013/07/14";
pageContext.setAttribute("b", b);
pageContext.setAttribute("c", c);
%>
<script>
var myVar = chk('<c:out value="${b}" />', '<c:out value="${c}" />');
</script>
<body>
<%
String st = "<script>document.writeln(myVar)</script>";
out.println("value=" + st);
%>
</body>
As said in my comment on your question, this looks like an exercise for practicing about scriptlets, EL, JSTL and JavaScript integration. This kind of code is not meant to be used in a live production system NEVER. Scriptlets usage is discouraged since long time. Refer to: How to avoid Java code in JSP files?. Also, show this to your teacher, professor or whoever is teaching you about Java web development.
At the end of the function, add return p;.
Your function didn't returned anything that's why undefined was written on screen.
function chk(d,e)
{
var x = d.split('/')
var y = e.split('/')
var a = new Date(x[2],x[0],x[1])
var b = new Date(y[2],y[0],y[1])
var c = ( b - a )
var p= c / (1000 * 60 * 60 * 24);
return p;
}
Simply call write this
var myVar=chk('$b','$c');
on document ready.
Because JSP just written the script to document.Not executed yet.

dd/MM/yyyy date format in jsp by scriptlet

I want to show the date coming from data base in the jsp page in dd/MM/yyyy format. Here is my code in javascript.
$(document).ready(function(){
<%
SDateDTO sDTO = (SDateDTO) request.getAttribute("sDTO");
if(null != scholAvailDTO){
System.out.println(scholAvailDTO.getEndDate());
%>
var end = <%=scholAvailDTO.getEndDate() %>;
$("#endDateId").val(end);
<%
}
%>
});
In console it is coming 27/04/2010 but in jsp it is getting populated like 0.0033582089552238806 which is actually division result of the date. Any help will be appreciated. Thanks, Amit
Well yes - your Javascript will presumably be rendered to the browser as:
var end = 27/04/2010;
If you want it to be in a string literal then you'll need to add the quotes yourself:
var end = "<%=scholAvailDTO.getEndDate() %>";
Note that you'll need to be confident that the value itself doesn't have quotes - or other values which aren't appropriate for JavaScript - in there. I suspect there may well be a better approach than the above.
If getEndDate() returns java.util.Date object then, use DateFormat for get the formatted string and then wrap the value in quotes as below:
<%DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");%>
var end = "<%=formatter.format(scholAvailDTO.getEndDate()) %>";
If getEndDate() returns java.lang.String then simply wrap the value in quotes as below:
var end = "<%=scholAvailDTO.getEndDate() %>";

Categories