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.
Related
1.How to find that your website is being hit in the next tab of the same browser?
2. How to prevent the website from being opened in the second tab?
If the browser first calls your site, you create a session on server side which results in sending the session cookie to the browser. In your HTML you can embed a hidden form value. This hidden value must be included in every subsequent call. Best is to use always POST so that the hidden value isn't included in the URL.
If the user opens a second tab and want to open a URL of your site the hidden parameter is not included but the session cookie from the first tab is.
So at server side you know there is already a session but the hidden value is missing. So you can send a totally different response.
Update
Here a small example.
In web content folder there is a subfolder protected. All included JSP files should only be opened in one tab. Here there is only MyJsp.jsp.
In the root folder there are two JSPs: error.jsp which is displayed when someone is trying to open a protected JSP in a second tab. And index.jsp which redirects to protected/MyJsp.jsp.
And there is a servlet filter mapped to the protected folder. This filter will be called before executing the JSPs in this folder.
protected/MyJsp.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<p>Hello,
<c:choose>
<c:when test="${not empty param.name}">
<c:out value="${param.name}" />.
</c:when>
<c:otherwise>
stranger.
</c:otherwise>
</c:choose>
</p>
<form method="post">
<label>Please enter your name</label>
<input id="name" name="name" type="text"/>
<input id="marker" name="marker" type="hidden"
value="<c:out value="${sessionScope.marker}"/>"/>
<button type="submit">OK</button>
</form>
</body>
</html>
This JSP is asking for a name. Form submit calls the same JSP via POST. The hidden field is filled with a value from the session.
index.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!--include the library-->
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:redirect url="protected/MyJsp.jsp"/>
The servlet filter:
#WebFilter("/protected/*")
public class OneTabFilter implements Filter {
private static final String MARKER_NAME = "marker";
private static final String MARKER_VALUE = "4711*0815";
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
final HttpServletRequest req = (HttpServletRequest) request;
final HttpServletResponse rsp = (HttpServletResponse) response;
HttpSession session = req.getSession(false);
if(session == null) {
session = req.getSession(true);
// Put the marker value into session so it is usable in JSP files.
session.setAttribute(MARKER_NAME, MARKER_VALUE);
// pass the request along the filter chain
chain.doFilter(request, response);
} else {
if(MARKER_VALUE.equals(req.getParameter(MARKER_NAME))) {
// pass the request along the filter chain
chain.doFilter(request, response);
} else {
// Redirect to the error page.
// The error page itself is not affected by this filter.
rsp.sendRedirect(req.getServletContext().getContextPath() + "/error.jsp");
}
}
}
// ...
}
Try it yourself!
I'm actually trying to access variable of other HTML file using JS.
I mean, I have a file (file1.htm) that open dialog box and I would like to send information of the file selected to another file (file2.htm) and modify a value in this file. I found solution but only for JS files, and not HTML :/
I had already done it with 2 files but file1a was the parent of the other, so I used
parent.framWin = window; in file2a and
framWin.divX=document.getElementById("one").offsetWidth; for example in file1a to modify the variable divX in file2a (I'm pretty sure this is not the best solution, but it works ;) ). Here, in this case, file1 and file2 are not parent, and they are just located in the same folder.
I tried <script type="text/javascript" src="file1.htm"> to access var but it doesn't seem to work.
Do you have any idea how I can accomplish this?
Thanks a lot!
(Here's my code :
file1.htm :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>SiteMap</title>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
<style type="text/css">
</style>
<script type="text/javascript">
<!--
function OK(e){
var name = document.getElementById("dialog").value;
//Here I would like to do something like File2.NameSpace1 = name;
//And File2.modifyMyName(); // But here, it's another question, to use JS script in another file ;)
}
//-->
</script>
</head>
<body >
<form action='' method='POST' enctype='multipart/form-data'>
<input type='file' name='userFile' onchange="OK()" id="dialog">
</form>
</body>
</html>
and file2.htm:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>SiteMap</title>
<meta http-equiv="Content-Type" content="application/xhtml+xml; charset=utf-8" />
<script type="text/javascript">
<!--
var NameSpace1;
function modifyMyName(){
document.GetElementById("first").src = NameSpace1;
}
//-->
</script>
</head>
<body>
<div>
<img src ="" id="first" />
</div>
</body>
I know this won't work properly because there are some errors here in the syntax. But the problem is visible ;)
Thanks again :)
You can't simply modify the content of file on the server using client side code.
The examples you've cited just change the data that is loaded into the browser at the time the code runs while leaving the data on the server untouched.
There are two approaches you can take to this:
Store the changes in the browser.
In page one, use localstorage to record information about the change you want to make. (You'd probably want to convert the image into a data: scheme URL to achieve this given your example code).
In page two, have some more JS that reads from localstorage and uses that information to make the change to itself after it loads.
Send the changes to the server.
Submit a form (so you don't need to use client side code at all) or use Ajax to send information about the change to the server.
Have server side code read it and then store it in a session (if you want the change to be on a per-user basis) or somewhere more permanent (in a database if you are sensible but you could modify the file directly) (if you want it to be shared between users).
Page two would then be a server side program that would read that data and use it to generate the page.
You can use localStorage to perform this operation.
function OK(e){
var name = document.getElementById("dialog").value;
window.localStorage.setItem('dialogValue', "Name");
}
And In your file2.html
function modifyMyName(){
var NameSpace1 = window.localStorage.getItem('dialogValue');
document.GetElementById("first").src = NameSpace1;
}
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" />
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.
I am developing a dynamic web application using the following technologies on Eclipse Luna : JSP for server-side scripting, Apache Tomcat v7.0, Oracle 11g as my database and Jquery.
Below is my first .jsp page which is an elementary registration page :
<%# 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>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="ValidateRegister.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome</title>
</head>
<body>
<%#include file="Home.jsp" %> <br/>
<div id="form">
<form id="login" action="RegisterProcess.jsp" method="post" name="login">
<table>
<tr><td>User Name</td><td><input type="text" name="uname"/><br/></td><td><p id="unamecheck"></p></td></tr>
<tr><td>Email ID</td><td><input type="text" name="uemail"/><br/></td><td></td></tr>
<tr><td>Password</td><td><input type="password" name="upass" /><br/></td><td></td></tr>
<tr><td></td><td><input type="submit" id="submit" value="Register"/></td><td></td></tr>
</table>
</form>
</div>
</body>
</html>
This page gathers user credentials and on form submission the following javascript is triggered:
$(document).ready(function() {
$('#submit').click(function() {
var result=validateForm();
if(result===false)
return result;
else
checkUsername();
});}
);
function validateForm()
{
//does usual validation like empty string etc..
}
function checkUsername()
{
$.ajax(
{
url:"RegisterProcess.jsp",
data:$("#login").serialize(),
type:"post",
dataType:"json",
success:function(data)
{
$("#unamecheck").text(data);
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" + status + errorThrown);
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
complete:function(xhr,status)
{
alert( "The request is complete!" );
}
});
}
The jsp page being referenced is :
<%# 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>Processing</title>
</head>
<body>
<%#page import="bean.RegisterDao"%>
<jsp:useBean id="obj" class="bean.User"/>
<jsp:setProperty name="obj" property="*"/>
<%
final int status=RegisterDao.register(obj);
if(status>0)
out.print("You are successfully registered");
else
out.print("Username already exists!");
%>
</body>
</html>
When I press submit the form, I get the alert message :"Sorry, there was a problem!error" followed by "The request is complete!" and then I'm redirected to the page RegisterProcess.jsp, which outputs the correct thing :"Username already exists" or "Registration successful".
I have used Firebug to debug but could not decipher much. Any help would be much appreciated as I could not find any similar question been asked previously.
You appear to be confused about what the $.ajax call is actually doing. AJAX is a technology that allows browsers to make asynchronous HTTP calls to resources without requiring the entire browser page to be loaded. What you're doing in your $.ajax call is asking for the browser to submit the data from your form to the URL, RegisterProcess.jsp, and then to process the result in some way.
By specifying the data type of json in your $.ajax call, you're asking jQuery to treat the response from the server as a JSON object, but the RegisterProcess.jsp page renders as HTML. Therefore, the $.ajax call interprets the response as an error and displays the message accordingly.
The reason you're subsequently redirected to RegisterProcess.jsp in your browser is that you don't prevent the default submission of the registration form. One way of doing that is to issue a preventDefault() on the incoming event, or return false from your event handler.
Restructure your code so that you submit an $.ajax request to a resource that returns JSON, or remove the json data type specifier from the $.ajax call.
Take a look at how your form is set up. Upon submission, your form makes a POST to RegisterProcess.jsp here:
<form id="login" action="RegisterProcess.jsp" method="post" name="login">
Additionally, you're making a second POST using AJAX whenever the submit button is being pressed. More than likely, you've got a race condition.
The form's POST is completing first and issuing a redirect, which interrupts your AJAX's POST in JavaScript. I'll bet that if you look at what error is being thrown, it will be some form of interrupt exception.
Do you want to redirect your user to RegisterProcess.jsp? If not, remove the action and method from your <form> and let your AJAX call do the verifying.
Is the user supposed to be redirected to ReigsterProcess.jsp? If so, change your form to this and remove your AJAX call:
<form id="login" name="login" action="RegisterProcess.jsp" method="post" onsubmit="return validateForm();">
When clicking submit, now the form will first look for a true/false return from validateForm() before submitting the POST and redirecting to RegisterProcess.jsp.