I have a jsp page where i have several varibles, all of the variables will have different values in every seconds because some codes in the backend will change them. When the user load the following page will see these numbers az zero but as the time passes these values should be updated and displayed at this page, so basically it should look like a time counter.
Here is my jsp page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Process</title>
</head>
<body style="background-color:aquamarine;">
<h2>${info}</h2>
<h2>Number of Xs:</h2>
<h2>${numberOfX}</h2>
<h2>Completed Xs:</h2>
<h2>${completedInfo}</h2>
<h2>Elapsed time:</h2>
<h2>${elapsedTime}</h2>
<form action="/" method="get">
<table>
<tr>
<td><input type="submit" name="button1" value="BACK" /></td>
</tr>
</table>
</form>
</body>
</html>
Unfortunately jsps are populated once with the model data.
You can use server side events though:
https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events
https://www.baeldung.com/spring-mvc-sse-streams
Related
I am stuck in a situation where I have a Struts2 form with a select tag which when changed should trigger an event and I can't figure out why the onchange function is not triggering but the peculiar thing is that the onchange trigger event works in an other example. I am confused here.
NOT Working:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!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=ISO-8859-1">
<title>New Order</title>
<script src="js/jquery-1.11.1.min.js"></script>
<script type='text/javascript'>
$(function(){
$('#company').change(function() {
var selected = $('#company').val();
alert(selected);
});
});
</script>
</head>
<body>
<s:form action="NewOrder">
<s:select headerKey="-1" headerValue="Select Company" name="company"
label="Select Company" list="{'companies','industries'}" />
Select Item:
<select id="item"></select>
<s:select id="ordertype" name="purchaseorder.orderType"
list="{'Consumables','Tools','Raw Materials'}" label="Order Type" />
<s:textfield name="purchaseorder.orderDate" label="Order Date" />
<s:textfield name="purchaseorder.deliveryDate" label="Delivery Date" />
<s:textfield name="purchaseorder.exciseDuty" label="Excise Duty" />
<s:textfield name="purchaseorder.salesTax" label="Sales Tax" />
<s:textfield name="purchaseorder.remarks" label="Remarks" />
<s:textfield name="purchaseorder.deliverySchedule"
label="Delivery Schedule" />
<s:submit />
</s:form>
</body>
</html>
Working:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<script src="js/jquery-1.11.1.min.js"></script>
<script>
$(function(){
$('#state').change(function(){
var sel = $('#state').val();
alert(sel);
});
});
</script>
</head>
<body>
<h3>Struts 2 Dynamic Drop down List</h3>
<s:select label="What's your State" headerKey="-1"
headerValue="Select State" list="states" name="state"
value="defaultState" />
District :
<select id="district"></select>
</body>
</html>
The #something selector (both in jQuery and CSS) is the ID selector. It means:
select the object with the id attribute equals to something.
Since both your <s:select/> have no id attribute set, it should not work in none of the above case.
However, the explanation to why it works there and not here is simple:
Struts2 generates the id for you, when it is not specified. The id is usually autogenerated in the form of formName_elementName (or formId_elementName, I'm not sure).
First example:
since you have a form, the id of your select will be something like id="form1_company" (or id="formNewAction1_company", I don't remember the way Struts2 generates the id/name for the forms, since also your <form> is missing them !..).
Second example:
the <s:select> is not enclosed in a form, so since its name is "state", the autogenerated id will be id="state" , and will be matched by the $('#state') selector.
Moral of the story:
always give your objects an id, at least to the one you need to work with JavaScript.
$(function(){
$('#ordertype').change(function() { //id shoud be orderType not company
var selected = $('#ordertype').val();
alert(selected);
});
});
Firstly I do not see any element that matches #company in the first HTML, BUT I also don't see one that matches #state in the supposedly working example.... so that's confusing. You have a "select[name=company]" but no select box has an id attribute with value 'company'.
If anything is being dynamically changed on your page, like something loading through ajax (like that id attr being added in) you may need to use this: .on()
I would like to start off saying that I'm very new to programming. I am developing a site (www.example.com) that has multiple hyperlinks.
When a user visits my site I want all the links to be defaulted to the back office of another site (www.tvcmatrix.com/mhammonds) I use. How do I set the links to redirect to the query string value based on inputted text from a form that is on my site (www.example.com)?
In other words, if the url reads www.example.com/?user=abelliard, how do I make all the links on the site change to "www.tvcmatrix.com/abelliard"? If no query string is present, then I would like for the links to be www.tvcmatrix.com/mhammonds.
Here is a file on my site for the form called "form.asp"
<!DOCTYPE html>
<html>
<body>
<form action="viral.asp" method="get" name="input" target="_self">
Your TVC Matrix Associate ID: <input type="text" name="user" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Here is the "viral.asp" file in the "form.asp" file.
<%# language="javascript"%>
<!DOCTYPE html>
<html>
<body>
<%
var id = Request.QueryString("user");
Response.Write("Your URL is: www.mca.com/?user=" + id)
%>
</body>
</html>
Here is the last file and front end of the site called "front.asp"
I have 'viral' and 'form' down packed. The main thing I needed help with was the front end of the site that deals with the links.
I have no clue if I am even a tad bit close or way off track, but what I have isn't working at all so I know it's wrong.
<!DOCTYPE html>
<html>
<head>
<title>Main Site</title>
</head>
<body>
Click Here!
<iframe width="450" height="40" src="form.asp">
</iframe>
</body>
<script lang="javascript" type="text/javascript">
function tvcid() {
var username = document.getElementById('username');
if (username.value != "") {
tvcid = "username";
}
else {
tvcid = "mhammonds";
}
}
</script>
</html>
How do I pass a variable through a hyperlink?
For staters, you're not using a hyperlink, you're submitting a form.
Request.QueryString("user"); is looking for something on the querystring. You're using POST, which has form fields.
Use Request("user");, which will grab the value regardless of whether it's on the querystring or a POST field. If you want to force recognition of form fields only, use Request.Form("user");
Classic ASP code is executed server side when the page loads. You are submitting a form inside an iframe, and the result page is also displayed inside the iframe. This result can't change anything on the parent page because it has already been loaded. The easiest way around this would be to have all your code on the same page. I'll show you how to do this with VBS as the scripting language, it's what I'm used to, but it should be easy enough to use server side JS instead
<%# language="VBScript"%>
<%
Dim id
If Request("user") <> "" then
id = Request("user")
else
id = "mhammonds"
End if
%>
<!DOCTYPE html>
<html>
<head>
<title>Main Site</title>
</head>
<body>
Click Here!<br />
<% If Request("Submit") <> "Submit" then %>
<form method="get">
Your TVC Matrix Associate ID: <input type="text" name="user" />
<input type="submit" name="submit" value="Submit" />
</form>
<% else
Response.Write("Your URL is: www.mca.com/?user=" & id)
End If %>
</body>
</html>
If you really don't want to have to reload front.asp then you need to look at ajax, and add the relevant tag to your question
I've been working with Struts2 and it's JQuery plugin for around a week and I'm a little bit lost.
Last thing I tried to do was to implement searches by date in a jqGrid I'm displaying on a page. For this, I followed this tutorial here.
The thing is it's not working because when I click on the searchfield which is supposed to pop out the datepicker, it won't pop out anything.
I've debugged the javascript code and found that when it tries to call the datepicker() function, an error comes up saying "Uncaught TypeError: Undefined is not a function" .
I'm not sure why this happens as I'm using Struts2-jquery-plugin 3.7.1. I'm posting my JSP code below (I've omitted all the grid rows that don't relate to the question):
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sj" uri="/struts-jquery-tags"%>
<%# taglib prefix="sjg" uri="/struts-jquery-grid-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<sj:head jqueryui="true" jquerytheme="south-street" locale="es" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
datePick = function(elem) {
$(elem).datepicker({
firstDay : 1
});
$('#ui-datepicker-div').css("z-index", 2000);
}
</script>
<title>Testing</title>
</head>
<body>
<s:url var="remoteurl" action="reservationList"/>
<div id="grid">
<sjg:grid
id="reservationsGrid"
caption="%{getText('reservationTable.title')}"
dataType="json"
href="%{remoteurl}"
pager="true"
gridModel="gridModel"
rowList="10,15,30"
rowNum="15"
navigator="true"
navigatorSearch="true"
autowidth="true"
navigatorSearchOptions="{multipleSearch:true, closeAfterSearch:true}">
...
<sjg:gridColumn name="date" index="date" title="Date" search="true" formatter="date" sortable="true" formatoptions="{newformat : 'd/m/Y H:i', srcformat : 'Y-m-d H:i'}" searchoptions="{sopt:['eq','lt','le','gt','ge'], dataInit:datePick}"/>
...
</sjg:grid>
</div>
</body>
</html>
Am I missing any import/reference or such a thing?
UPDATE
Recently I've found a hack, and it's telling me that the issue relates to the datepicker's import/reference:
All I did was adding a new tag inside my JSP:
<sj:datepicker style="display:none" disabled="true"></sj:datepicker>
By doing this, I guess I'm forcing the framework to automatically import and initialize a datepicker, and so it works, but it's not the solution I'm searching for.
So my question then is:
How can I import/reference and initialize the datepicker?
By default <sj:head> will NOT load all jQuery ui resources rather they are loaded on demand. When you've added a <sj:datepicker> tag it also loaded needed resources and your script was able to run.
In order to load all resources at once set loadAtOnce attribute of <sj:head> tag to true.
<sj:head jqueryui="true" loadAtOnce="true"
jquerytheme="south-street" locale="es" />
Ok its a continuation of my crap attempts of using client side scripts along with server side elements.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form name="test" action="test.jsp" method="post" enctype="multipart/form-data">
<select name="harish" onchange=callme();>
<option value="1">1</option>
<option value="2">2</option>
</select>
<script>
var jsvar="Hello";
function callme()
{
alert(jsvar);
jsvar=document.getElementById("harish").value;
alert(jsvar);
}
</script>
<%
String s=(String)("<script>document.writeln(jsvar)</script>").toString();
out.println(s.equals("Hello"));
if(!(s.equals("Hello")))
{
String jspvar="<script>document.writeln(jsvar)</script>";
out.println("jspvar"+jspvar);
session.setAttribute("test",jspvar);
}
%>
</form>
</body>
</html>
Now what I am trying is to set the selected value as a session variable.But my bad the value from javascript is not sitting properly on the jsp/java variable and therby my condition if(!(s.equals("Hello"))) fails.Can anyone help me here...
Update:
Can the below be the solution for this question
Have a HTML page with two frames. Let the first page contain all the javascript values you wish to populate. The second page(hidden) of the frame actually does the trick. That is actually a JSP. On click of a button (on any action on the first page) in the first page, point your location to the hidden frame (2nd page), perform checks / conversions and populate the variable of the first page using cross frame JAVASCRIPT.
my condition if(!(s.equals("Hello"))) fails
That is because this:
String s=(String)("<script>document.writeln(jsvar)</script>").toString();
out.println(s.equals("Hello"));
...is pretty much the same as writing:
out.println("this".equals("that"));
It will always be false.
Now what I am trying is to set the selected value as a session variable.
To set a variable in the session, you need to POST the form to the server (ignoring AJAX techniques, etc.). As I mentioned here, using multipart/form-data requires a MIME parser - the form below uses the default enctype.
This form will, when you select an option from the drop-down, post the form to the server. Every time the JSP is run, it uses a scriptlet <% ... %> tests to see if a "harish" parameter has been posted. If it has, it places it in the session. An expression <%= ... %> is used to display the current session value.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- header removed for clarity -->
<body>
<form id="test" name="test" action="test.jsp" method="post"><select
name="harish" onchange="document.getElementById('test').submit();">
<option value="select">select an option</option>
<option value="1">1</option>
<option value="2">2</option>
</select></form>
<%
//see if a parameter was sent from page; "harish"==name attr on select
String value = request.getParameter("harish");
if (value != null) {
//store it in session
session.setAttribute("test", value);
}
%>
<%="harish=" + session.getAttribute("test")%>
</body>
</html>
This assumes that the above page is test.jsp - that the page posts back to itself. If not, you'll need to move the scriptlet and the expression to test.jsp.
Java is evaluated on the server side, so in variable s you will always find
<script>document.writeln(jsvar)</script>
Javascript is evaluated on the opposide side, that is on the client's browser, so this is why your method does not work (I've fallen many time into this also ^^)
You can POST the form on the same jsp where this code resides and take the result from the POSTed data, to do that you'll use a scriptlet. If I remember correctly you could use
request.getParameter("PARAMETER_NAME")
So just add the name of the jsp where this code is to the action of the form and the above code to retrieve the selected value.
I have a page where I am getting session values then calling form action through javaScript, please see the code below
<%# Page language="c#" AutoEventWireup="false" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>SessionRedirect</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name=vs_defaultClientScript content="JavaScript">
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5">
</head>
<body MS_POSITIONING="GridLayout">
<form method="post" name="frmRedirect" target="_blank">
<input type="hidden" name="email" value="<%=Session["Email"].ToString() %>" />
<input type="hidden" name="pass" value="<%= Session["PWD"].ToString() %>" />
<input type="hidden" name="User" value="<%= Session["User"].ToString() %>" />
</form>
<script type="text/javascript">
if(frmRedirect.User.value == "P")
{
frmRedirect.action = "http://cmsstag/partnerzone/index.aspx";
}
else
frmRedirect.action = "http://cmsstag/studentportal/index.aspx";
document.frmRedirect.submit();
location.replace("index.aspx");
</script>
<%
Session.Remove("registration");
Session.Remove("User");
Session.Remove("UserId");
Session.Remove("UserLoggedIn");
Session.Remove("AgentCode");
Session.Abandon();
%>
</body>
</html>
Now I want to open page in new window with size given by me when I use "frmRedirect.action" used in above code.
This is a rather complicated example.
What you could try is:
open a new window first with javascript window.open() and set its dimensions and name
submit the form to it setting the correct target name as you've set it in window.open()
I've tried it. It works.
Edit
This is the code for you. Maybe you will have to set some time between opening a new window and submitting a form to make sure the window is already created (use setTimeout).
// open a new window with proper size
window.open("", "MySubWindow", "height=480,width=640");
// do your action assignments
frmRedirect.target = "MySubWindow";
frmRedirect.submit();
location.replace("index.aspx");