I have a jsp page that looks like the following:
What the intent is, is to get the current environment via a system variable and then generate the correct url for that environment.
<%# taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<%# taglib prefix="logic" uri="http://struts.apache.org/tags-logic" %>
<%
String sysEnv = "";
if(System.getProperty("env.name").equals("test")) {
sysEnv = "test";
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html>
<head>
<%# include file="/includes/common.jsp" %>
<script type="text/javascript" src="<c:out value="${requestScope.scriptsLocation}"/>/scripts/general.js"></script>
<c:if test="${requestScope.isFeed == true}">
<jsp:include page="/includes/someInclude.jsp"/>
<script src="http://www.myothersite.com/feed/d/some.js" type="text/javascript"></script>
<script type="text/javascript">
var environ = <%=sysEnv%>;
if(environ == 'test'){
var theUrl = 'http://mywebsite.com?isFeed=true&env=TEST';
} else {
var theUrl = 'http://mywebsite.com?isFeed=true';
}
...
</script>
...
I think I'm supposed to have the tags-logic import to do the looping that I'm trying to achieve in Java, but this is not working.
Since you're already in a JSP why not just do (roughly) this:
<script>
var url = 'http://mywebsite.com?isFeed=true';
if ('<%= System.getProperty("env.name") %>' === 'test') {
url += '&env=TEST';
}
// etc.
Personally I'd move this logic out of the view and create a request-scoped attribute in a filter, as part of your Struts 1 request processor, etc. since scriptlets are almost always bad. It also gives you the opportunity to set it at runtime.
In addition, the URL generation should also likely be moved out of the view layer.
Related
I need a ASP.net application which is only kind of "pageDisplayer" from content which is coming from an API. So I choose ASP.net Webform and tried the following:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="PMLetterAcceptance.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:Literal runat="server" id="JavaScript"></asp:Literal>
</head>
<body>
<form id="letterform" runat="server">
<div>
<%= pageContent %>
</div>
</form>
</body>
public partial class WebForm1 : System.Web.UI.Page
{
protected string pageContent = "";
protected void Page_Load(object sender, EventArgs e)
{
...// here I fetch the html and javascript content from the API
dynamic json = Json.Decode(streamReader.ReadToEnd());
if (json.status != "OK")
pageContent = json.error;
else
pageContent = json.html;
JavaScript.Text = json.script;
}
}
The html content and the script are loaded correct but I cannot access DOM elements in the javascript. The javascript looks like that
(function()
{
function processForm(e)
{
... // Here I want to do some stuff before sending the form
}
let form = document.getElementById('letterform');
if (form.attachEvent)
form.attachEvent("submit", processForm);
else
form.addEventListener("submit", processForm);
})();
No I get the error "form is null". For me it looks like the javascript is executed before the DOM is ready. But how can I change this to make it work like expected?
Try putting the JS (literal) at the bottom of the page, before the closing body tag. That way, the HTML will be loaded before the JS tries to find elements.
I am working on jsp,
What I am trying to implement is quite simple.
do some time-consuming work with Java
while processing, show users the spinner
So I have implemented like below
<%# page contentType="text/html; charset=UTF-8" %>
<%# page isThreadSafe="true" %>
<%
boolean isFinish = false;
Thread executeThread = new Thread(new Runnable() {
#Override
public void run() {
for(int i = 0; i < 10; i++){
try{
System.out.println(i + " Thread ");
Thread.sleep(1000);
}catch(Exception ex){
System.err.println(ex);
}
}
}
});
executeThread.run();
%>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Loading</title>
</head>
<body>
<div class="popup" style="text-align: center;">
<div class="l_img">
<img src="resources/image/spinner/loading_gif.gif" alt="LOADING...">
</div>
<div class="b_txt">Processing</div>
<div class="s_txt">Please, wait..</div>
</div>
</body>
<%
if(isFinish){
%>
<script>
alert('done');
</script>
<%
}
%>
</html>
However, page shows up after Thread has terminated. Could I reverse the order?
What I wanted in order
show html page(spinner gif)
execute Java logics
catch the return of Java execution
if return is true, then alert with javascript
Is it possible?
Thanks for your answers
You can't do a server-side operation change dinamically the render the page.
the page will be rendered always where if(isFinish) has been executed.
the server will send the complete html page to the user only when all the java has been executed and in one block! you need to implement it on the front-end, for example you send a starting basic page of loading and you call the long term process with a ajax call or something similar.
<!DOCTYPE html>
<html>
<body onload="alert('done')">
Put your spinner here.
Some text here is necessary here for the browser to start displaying.
Otherwise it will wait until it receives enough of a response to begin displaying anything.
I am not sure how much is necessary. This works for me.
<%
out.print("<br/>Starting processing now. <br/>");
out.flush();
Thread.sleep(2000);
out.print("<br/>Processing..... <br/>");
out.flush();
for(int x = 1; x < 4; x++){
Thread.sleep(2000);
out.print("Result " + x + ".<br/>");
out.flush();
}
%>
</body>
</html>
<script language="javascript" >
function addSelection(){
var tst="hello";
sessionStorage.setItem("test", tst);
<%
String pastst=request.getParameter("tst");
session.setAttribute("tst1",pastst);
%>
addSelection1();
}
function addSelection1(){
var outtst = '<%= session.getAttribute("tst1") %>';
<%
out.print("session"+session.getAttribute("tst1"));
%>
var tstout= session.getAttribute("tstout");
alert(tstout);
}
</script>
alert(tstout); works properly, but the code inside jsp prints blank.
I don't know what is the purpose behind this. Anyway few issues found in your code.
First. You cannot get the javascript variable value like this,
var tst="hello"; //Setting the value in javascript
sessionStorage.setItem("test", tst);
<%
String pastst=request.getParameter("tst"); //Expecting the value will be returned by java request
session.setAttribute("tst1",pastst);
%>
Second. Following line will provide you JS error, You cannot assign like this var tstout= session.getAttribute("tstout");
You need to change into, var tstout= '<% session.getAttribute("tstout"); %>'
Its wrong assumption javascript will print the session value in the following line,
<%
out.print("session"+session.getAttribute("tst1"));
%>
Finally, you need to start learning JSTL and EL avoid using scriptlets.
This is the way some where it is working.
<script type="text/javascript" >
function addSelection(){
var tst="hello";
sessionStorage.setItem("test", tst);
<%
String pastst="hello";
session.setAttribute("tst1",pastst);
%>
addSelection1();
}
function addSelection1(){
var outtst = '<%= session.getAttribute("tst1") %>';
alert('<%
out.print("session : "+session.getAttribute("tst1"));
%>');
alert(outtst);
}
</script>
Hope it helps you.
I searched similar topic to add full screen option in my jsf application. I tried to add into "https://stackoverflow.com/a/11820717/1194553" and "https://stackoverflow.com/a/7525760/1194553"
solutions into my jsp file of jsf applicaton such as;
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%# taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!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>Making Full Screen</title>
<script type="text/javascript">
function cancelFullScreen(el) {
var requestMethod = el.cancelFullScreen||el.webkitCancelFullScreen||el.mozCancelFullScreen||el.exitFullscreen;
if (requestMethod) { // cancel full screen.
requestMethod.call(el);
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
}
function requestFullScreen(el) {
// Supports most browsers and their versions.
var requestMethod = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen;
if (requestMethod) { // Native full screen.
requestMethod.call(el);
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
return false;
}
</script>
</head>
<body>
<f:view>
<h:form id="mainForm">
<div>
<h:commandButton id="topBtn" styleClass="topMenuItem topMenuItem" image="images/common/fullScrUfa.png" onmouseover="this.src='images/common/fullScrFa.png'" onmouseout="this.src='images/common/fullScrUfa.png'" onclick="requestFullScreen(document.body);"></h:commandButton>
</div>
</h:form>
</f:view>
</body>
</html>
When I run the project and click the button of which id is "topBtn", I expect to make the browser-view showed in full screen. I tried on chrome vs.27.0.1453.116 and explorer 10.
However, when I push the button, the view is displayed in full screen mode and immediately returns back to normal mode without waiting any click or something. Although, this action is occured in less than one second, I can realized when I look carefully.
How can I solve this problem?
You need to add return false; like this :
onclick="requestFullScreen(document.body);return false;"
to stop propagation of the click, and so stop the form submit.
Not related :
You don't need a <h:commandButton /> if you are not using any JSF functionnality. A simple <input type="button" onclick="..." />. This is only a matter of slighly better performance. You can use plain HTML in JSF. This is about the same for <h:panelGroup />, I don't abuse them, when not necessary I'll use <span /> or <div />
i have populate some values using c:forEach tag. I want to get those values in my javascript.
If I click GetCtag value button, then i want to read from (c:forEach) values in javascript.
Is any other-way to retrieve the c:forEach tag value
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%# taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%# taglib uri="http://richfaces.org/a4j" prefix="a4j"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<f:view>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function getCTagValue(ctagObject)
{
alert("CFor Each Tag Object Value: " + ctagObject);
// Here i want write code for retrieve the c:forEach tag value
}
</script>
</head>
<body>
<h:form id="cTagForm" >
<c:forEach items="${cTagBean.tagList}" var="ctag">
<c:out value="${ctag.name} : "/>
<c:out value="${ctag.age}"/></br>
</c:forEach>
<a4j:commandButton id="GetCtagId" value="GetCtag" oncomplete="getCTagValue('#{cTagBean.tagList}')"/>
</h:form>
</body>
</html>
Help me.
Thanks in advance.
Just print it in JavaScript syntax instead of HTML syntax.
<script>
var data = {
<c:forEach items="${cTagBean.tagList}" var="ctag" varStatus="loop">
'${ctag.name}': ${ctag.age}${!loop.last ? ',' : ''}
</c:forEach>
};
</script>
So that it end up as valid JavaScript object (assuming that name returns String and age returns Number):
<script>
var data = {
'foo': 10,
'bar': 5,
'waa': 20
};
</script>
It is only possible for JavaScript to access the data in the HTML as it is SEEN BY THE BROWSER.
The method I would recommend is to generate JSON (however your Web-API allows that) and store it in JavaScript code -- perhaps a global. Of course, keeping this data "closer" to where it is used is advisable, but the same holds. Another approach is to use custom HTML attributes (hopefully starting with "data-" for HTML5-compliance).
I got the solution.
<a4j:commandButton id="GetCtagId"
value="GetCtag"
data="#{cTagBean.tagList}"
oncomplete="getCTagValue(data)"/>
Then,
function getCTagValue(data)
{
for(var i=0; i<data.length; i++)
{
alert("Month : " + data[i].name);
alert("Value : " + data[i].age);
}
}
<script>
var data = new Array();
<c:forEach items="${cTagBean.tagList}" var="ctag" varStatus="loop">
data.push(${ctag.name});
</c:forEach>
</script>