How to get RequestDispatcher parameter in forward target html - javascript

guys, I want to pass values from one html page to another. In test1.html, submit the value to Serlvet. In servlet got the value, and dispatcher request to test2.html. like this:
request.setAttribute("url", url);
request.getRequestDispatcher("test2.html").forward(request,reponse);
So, how can i get the "url" value in test2.html?. need help, thx!

request.setAttribute("url", url);
request.getRequestDispatcher("test2.jsp").forward(request,reponse);
then test2.jsp
<%# page language="java" pageEncoding="UTF-8"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
${url}
</body>
</html>

As the forward is entirely server-side, the attribute should still be present in the request. So from test2.html (actually you should make this a JSP page, test2.jsp), you can do the following:
<%
String url = (String)request.getAttribute("url");
%>
And if you wish to display it:
<html> ...
The URL is: <%=url%>
</html>

Related

Adding ASP.Net tags from javascript, why does this work?

I got an ASPX page with the folowing code behind
public partial class test : Page
{
protected void test(object sender, EventArgs e)
{
throw new Exception("test");
}
}
And the following ASPX code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Thumbnail</title>
</head>
<body>
<form id="form1" runat="server">
<div id="buttonTarget">
</div>
</form>
</body>
</html>
If I run the following javascript a button is added to the page:
$('#buttonTarget').html('<asp:Button runat="server" ID="tst" CssClass="buttons" OnClick="Test" Text="Test"/>');
The buttons shows the same way as an asp tag shows in element inspector.
And when I click the button the server sided function is called and the site breaks with the "test" exception
I know this isn't good practice but I want to know why this works. Why does this button call the server sided function and why is it displayed as a normal button ?
--EDIT--
The aspx code was a simplified version. The actual code used a gridview control and used javascript to insert rows in the table. These rows hold the tags.
Expanding on what #Mamun was probably saying, when the page is executing on the server, it's seeing the asp tag in the JS string and translating it into the appropriate HTML. If you view source on your page in the browser, you'll probably see something like this instead of the ASP tag in your JS call:
$('#buttonTarget').html('<input type="submit" name="ctl00$MainContent$tst" value="Test" id="MainContent_tst" class="buttons" />');

org.apache.jasper.JasperException: Unable to compile class for JSP:

I am trying to call jsp code in javascript.
The error is as follow
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 16 in the jsp file: /testng_index.jsp
String cannot be resolved
13: var mai=document.getElementById("j");
14: //mai.value = mai.value.toUpperCase();
15: var m=mai.value;
16: <%=String value=document.writeln(m)%>
17: var mo= <%= new PlaneBo().getOwnerId(value)%>;
18: // document.writeln(mo);
19: if(mo==0)
here is the code
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="com.ams.services.*" %>
<!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>
<script type="text/javascript" language="javascript">
function emailCheck()
{
var mai=document.getElementById("j");
//mai.value = mai.value.toUpperCase();
var m=mai.value;
<%=String value=document.writeln(m)%>
var mo= <%= new PlaneBo().getOwnerId(value)%>;
// document.writeln(mo);
if(mo==0)
{
// document.writeln(m);
var tab = document.getElementById("t");
var row = tab.insertRow(3);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var inpt= document.createElement("input");
inpt.setAttribute("name","jho");
inpt.setAttribute("type","text");
cell1.innerHTML="Name";
Please provide me suitable solution of this problem.
It looks to me as if you have some confusion about when and where Java and JavaScript code executes.
The Java code and JSP runs on the server when the browser requests the page. The server knows nothing about HTML and JavaScript. As far as the server is concerned, this is your JSP page:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="com.ams.services.*" %>
TEXT
<%=String value=document.writeln(m)%>
TEXT <%= new PlaneBo().getOwnerId(value)%>
TEXT
The server doesn't really care what's in the sections marked TEXT; it just sends them straight to the browser as they are. But it does care about what's in the <%# ... %> and <%= ... %> tags.
You get an error because the server doesn't understand document.writeln(m). It's not aware of any object named document, so it can't evaluate document.writeln(m). It happens that in JavaScript there is an object document and a function document.writeln, but that's irrelevant. The server doesn't know anything about JavaScript.
The JavaScript code doesn't execute until the page has finished being sent to the browser. You haven't shown when the function is called: it may be after an input field's value has been changed or a button has been clicked. The JavaScript runs in the browser, not on the server, so it can't directly call the Java code on the server.
If you really want to execute some Java code on the server during a call to your JavaScript function, you will need to use an AJAX call. See this question for more information on how to do this.

How do I put javascript programmatically into <head> block?

I need to put some javascript absolutely in the <head> block of the page -- it must execute before the rest of the page because a possible outcome of the script is to redirect to a different page.
However, when I use RegisterClientScriptInclude (to put some jQuery in there) and RegisterClientScriptBlock for my code which uses the jQuery, it puts it near the top of the <body> block, and it does not execute. I can't see a way to programmatically put this javascript into the <head> block -- it must be programmatically because sometimes I don't want it there, and sometimes I do.
I've tried to see if I can directly reference Content1, the ID of the asp:Content element corresponding to the <head> block, but no go.
Just in case anyone thinks that RegisterStartupScript might work: it doesn't. It puts it lower in the <body> block than everything else. Oddly enough.
Want some code? Here:
Type csType = this.GetType();
ClientScriptManager clientScript = Page.ClientScript;
if (!clientScript.IsClientScriptIncludeRegistered(jqueryScriptName))
{
clientScript.RegisterClientScriptInclude(jqueryScriptName, "~/Scripts/jquery-1.7.1.min.js");
}
if (!clientScript.IsClientScriptBlockRegistered(citrixDetectorScriptName))
{
clientScript.RegisterClientScriptBlock(csType, citrixDetectorScriptName, citrixDetectorScriptText, true);
}
By popular demand, how I detect the ActiveX component. This is JScript.
try {
var icaObj = new ActiveXObject("Citrix.ICAClient");
var CitrixVersion = icaObj.ClientVersion.split(".");
var MajorMinorVersion = CitrixVersion[0] + "." + CitrixVersion[1];
if (MajorMinorVersion == "11.0") {
// Citrix is OK
}
else {
window.navigate("WrongCitrix.aspx?Citrix=" + MajorMinorVersion);
}
}
catch (e) {
window.navigate("NoCitrix.aspx");
}
If the ActiveX component is not present, then redirection is a page that tells the user they need to install it. If the ActiveX component is any other version than 11.0, then the redirect is to a page that explains this and how to deal with the situation (backrevving for example).
An prior check during page load checks to make sure they have Internet Explorer v4 thru v9, because any other version will not work with the product (and IE10+ will crash if it even tries to load v11.0 of the ActiveX component).
If I understand your question, you can insert PlaceHolder control wherever you want inside the page.
<%# Page Language="C#" AutoEventWireup="True"
CodeBehind="Default.aspx.cs" Inherits="WebApplicationTelerik.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script type="text/javascript"
src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<asp:PlaceHolder runat="server" ID="PlaceHolder1"></asp:PlaceHolder>
</head>
<body>
<form id="form1" runat="server">
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(new LiteralControl(
"<script type=\"text/javascript\"> alert('here'); </script>"));
}
document.GetElementsByTagName("head")[0].appendChild( newScriptNode );
or jQuery
$("head")[0].append( newScriptNode );
If you really must insert JavaScript into the head tag, you can just make it an ASP.NET control and insert a control into it's child collection.
E.g. In the ASPX file:
<head runat="server" id="header">...</head>
In the code behind:
header.Controls.Add(new Literal("<script type='text/javascript'>...</script>"));
Although I do think you need to think about your process, it would be more efficient to redirect the user in the back-end before the page is rendered.
Oh and RegisterStartupScript correctly places your JavaScript after your html for increased load performance.

How to load another html file using JS

I'm trying to create a website, and I'm trying to figure out how to load a page.
For example:
You click on the navigator "Home" then a the bottom of the screen It loads a page witch text saying for example "Hello Word!".
Does anybody know what to do? I'm pretty sure It involves JavaScript.
To dynamically load content, you could make an AJAX call using XMLHttpRequest().
In this example a url is passed to the loadPage() function, in which the loaded content is returned.
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function loadPage(href)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", href, false);
xmlhttp.send();
return xmlhttp.responseText;
}
</script>
</head>
<body>
<div onClick="document.getElementById('bottom').innerHTML =
loadPage('hello-world.html');">Home</div>
<div id="bottom"></div>
</body>
</html>
When the div element containing text of "Home" is clicked, it sets the html of div element with id of "bottom" to content found in the "hello-world.html" document at the same relative location.
hello-world.html
<p>hello, world</p>
Ok, what you are looking for is a single page application.
There are plenty of technologies implementing it, but not that easy.
Here is a tutorial I followed for doing it : http://andru.co/building-a-simple-single-page-application-using-angularjs
If you want to go further with SPAs, you will certainly need angular templates.
It's not necessary to use Ajax calls to load html. Use them when need the server to process data successfully before loading the page, if processing was successful.
If you don't have this concern, and you just want to load the html without data processing, a simple anchor tag will suffice:
click

javascript with jsp

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.

Categories

Resources