Hi I want to do a JSP program where there is a number displayed and a button. When the user clicks this button the number above it increments. I want to include sessions in this program.
What I have done is this:
This is the form in html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Form</title>
</head>
<body>
<%! public void displayNum(){ %>
Number: <%=session.getAttribute("Counter") %>
<%! } %>
<FORM METHOD=POST ACTION="getcount.jsp">
<button TYPE="button" ONCLICK= "displayNum()">Add 1</button>
</FORM>
</body>
</html>
and this is myJSP file:
<%
AddCount addCount = new AddCount();
addCount.setCounter(addCount.addCounter(addCount.getCounter()));
int counter = addCount.getCounter();
session.setAttribute("Counter", counter);
%>
where AddCount is a java class with a variable counter, setter and getter and a function to increase the counter - addCount(num); all I'm getting when running the file is a button without any text in it :/
I've been trying over and over again. Can someone help me please?
Thankss!
You are adding java code in html, which is not possible.
Second thing even if you are having a static int counter in AddCount it wont work as many user s may use this page and expect only one increment for their each click.
So what you should do is write a jsp file like this index.jsp
<%Integer counter = (Integer)request.getSession().getAttribute("counter")
if(counter==null) {counter=0;}
counter ++;
request.getSession().setAttribute("counter",counter);
%>
<div>counter=<%=counter%></div><br>
+1
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Form</title>
</head>
<body>
function displayNum()
{
<%
AddCount addCount = new AddCount();
addCount.setCounter(addCount.addCounter(addCount.getCounter()));
int counter = addCount.getCounter();
session.setAttribute("Counter", counter);
%>
document.getElementById("demo").innerHTML="<%=session.getAttribute("Counter")%>";
}
<p id="demo"> {number will be displayed here} </p>
<button TYPE="button" ONCLICK= "displayNum()">Add 1</button>
</body>
</html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="jquery.js"></script>
<title>My Form</title>
</head>
<body>
<script>
$(document).ready(function() {
$("button").click(function() {
$("#div1").load("increament.jsp");
});
});
</script>
<div id="div1"> {number will be displayed here} </div>
<button>Add 1</button>
</body>
</html>
and increament.jsp file :
<%
int count;
if (session.getAttribute("Counter") == null) {
count = 1;
} else {
count = (Integer) session.getAttribute("Counter");
count++;
}
session.setAttribute("Counter", count);
out.println(session.getAttribute("Counter"));
%>
Related
I am developing a college project and i will try to explain my problem using a small example.
Below there are 3 jsp pages (index.jsp , test.jsp , logged.jsp) and i want that if the user try to access logged.jsp directly by entering url http://localhost:8080/sessionTest/logged.jsp then he will be redirected to index.jsp.
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<form action ="test.jsp" method="post">
enter user id :<input type="text" name="user">
Enter password:<input type="password" name="pass">
<input type="submit" value="submit">
</form>
</body>
</html>
test.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String user= request.getParameter("user");
String pass= request.getParameter("pass");
if(user.equals("snow")&& pass.equals("123"))
{
session.setAttribute("user", user);
RequestDispatcher r = request.getRequestDispatcher("logged.jsp");
r.forward(request, response);
}
else {
out.println("wrong pass or id");
}
%>
</body>
</html>
logged.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<% session = request.getSession(false);
if(session==null)
{
response.sendRedirect("index.jsp");
}
else{
out.println("welcome its old session");
}
%>
</body>
</html>
please , help me with some code and explain how it works
Try this one may be it helps you :
<%
HttpSession session = request.getSession();
if(null!=session.getAttribute("username")){
out.write("username is "+session.getAttribute("username").toString());
}
else{
response.sendRedirect("/index.jsp");
}
%>
I created a simple ASP.Net html page. I would like to put a password check, ONLY when the page is initially loaded, I did it with a script and assigned the tag onload to the body. The problem is, that the password check is triggered every time I press a button. Why does this happens? How can I execute that password check ONLY when you open the page?
Thanks in advance.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="FotoDiClasse.aspx.cs" Inherits="FotoDiClasse" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Choose your sweatshirt</title>
<!-- password control -->
<script>
var password;
var pass1 = "1234";
var firstTime = true;
function checkPassword()
{
if (firstTime)
firstTime = false;
password = prompt("Enter password to access the site", '');
if (password != pass1) window.location = "http://www.google.com";
}
</script>
</head>
<body onload="checkPassword()">
<form id="form1" runat="server">
<div>
<asp:Button ID="CreateButton" runat="server" Text="Create" Width="240px" OnClick="CreateButton_Click" />
<asp:Button ID="SendButton" runat="server" Text="Send" Width="240px" OnClick="SendButton_Click" />
</div>
</form>
</body>
</html>
This "first time" flag doesn't work
It is called PostBack. Every time a Button is pressed the Page performs a Form Post (PostBack). That means the page is reloaded.
With the snippet below you can call a JavaScript function only when the page is first loaded.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "runScript", "alert('This is not a PostBack');", true);
}
}
It happens because every time you press a button your page is loaded and onload() method is called and hence every time that method is called.
To overcome this problem you need to set some sort of function that check whether your page is loaded first time or not to do this you can use cookie to store that session.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="FotoDiClasse.aspx.cs" Inherits="FotoDiClasse" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Choose your sweatshirt</title>
<!-- password control -->
<script>
var password;
var pass1 = "1234";
var firstTime = true;
function checkPassword()
{
if (firstTime)
firstTime = false;
password = prompt("Enter password to access the site", '');
if (password != pass1) window.location = "http://www.google.com";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="CreateButton" runat="server" Text="Create" Width="240px" OnClick="CreateButton_Click" />
<asp:Button ID="SendButton" runat="server" Text="Send" Width="240px" OnClick="SendButton_Click" onblur="checkPassword()"/>
</div>
</form>
</body>
</html>
Below is my index.html and action.jsp code
When I am submitting the values from index.html to action.jsp instead of getting the output of out.println in action.jsp I am getting the complete action.jsp as my output.
Advise what is the issue and how to rectify it also advise if the directory structure is correct i.e.; all files are placed where they are usually supposed to be placed or not
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="action.jsp" method="post">
Name <input type="text" name = "name"> <br>
Password <input type="password" name="password"> <br>
<input type="submit" value="submit">
</form>
</body>
</html>
// Below is action.jsp
<%#page import="p1.NewHibernateUtil"%>
<%#page import="org.hibernate.Transaction"%>
<%#page import="p1.User"%>
<%#page import="org.hibernate.Session"%>
<%#page import="org.hibernate.SessionFactory"%>
<%#page import="org.hibernate.cfg.Configuration"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
out.println("In scriplet tag");
Configuration cfg = new Configuration();
out.println("Configuration object created");
cfg.configure("hibernate.cfg.xml");
out.println("Configured");
// SessionFactory sf = NewHibernateUtil.getSessionFactory();
// out.println("SessionFactory created");
// Session ses = sf.openSession();
// Transaction t = ses.beginTransaction();
// String n = request.getParameter("name");
// String p = request.getParameter("password");
//
// out.println("Welcome " + n);
// User u1 = new User(n, p);
// ses.save(u1);
// t.commit();
// ses.close();
// out.println("Data inserted successfully");
%>
</body>
</html>
As per my assumption you are running the given example without using web server. You will require web server to run given code.
Consider using web server (ex. Tomcat http://tomcat.apache.org/tomcat-8.0-doc/index.html )
I know a iframe tag can access to parent element with same domain + ports.
However, what if parent and iframe has different domain + port ?
i.e.
parent's domain is http://aaa.com:63342, and iframe domain is http://aaa.com:9080.(Please note that they have different ports)
Both of pages have <meta http-equiv='X-Frame-Options' content='ALLOWAll'> in their headers.
first, parent frame call iframe with form submit. like...
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='X-Frame-Options' content='ALLOWAll'>
<title>ParentWindows with aaa.com:63342</title>
</head>
<body>
<form name='form' method='post' id='form' action=''>
<input type='text' name='greetings' value='Hello from the otherside'>
</form>
<script>
document.form.target = 'iframe';
document.form.action = 'http://aaa.com:9080//inFrame.jsp';
document.form.submit();
</script>
</body>
<iframe src="" name='iframe'></iframe>
</html>
Then a server returns like below in jsp
<%
response.setHeader("X-Frame-Options", "ALLOWAll");
String greetings = request.getParameter("greetings");
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='X-Frame-Options' content='ALLOWAll'>
<title>iframe with aaa.com:9080</title>
</head>
<body>
<div>
greetings message : <%= greetings %>
</div>
</body>
<script>
var div = document.createElement('div');
div.textContent = 'Echo Hello';
parent.document.body.appendChild(div);
</script>
</html>
It is simple version of the situation what I am in. However, when I do like this, browser console shows error like..
Uncaught SecurityError: Blocked a frame with origin "http://localhost:9080" from accessing a frame with origin "http://localhost:63342". Protocols, domains, and ports must match.
Now I am doubting with this method(calling different hosts between iframe and parent) is possible at first place... Is it possible?
How can I make this works?
Thanks a lot
Detour to original frame.
something like...
original page with aaa.com:63342/original.html is
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='X-Frame-Options' content='ALLOWAll'>
<title>ParentWindows with aaa.com:63342</title>
<script>
function setGreetings(greetings){
document.getElementById('greetings').value = greetings;
}
</script>
</head>
<body>
<form name='form' method='post' id='form' action=''>
<input type='text' id='greetings' name='greetings' value='Hello from the otherside'>
</form>
<script>
document.form.target = 'iframe';
document.form.action = 'http://aaa.com:9080//inFrame.jsp';
document.form.submit();
</script>
</body>
<iframe src="" name='iframe'></iframe>
</html>
Then page(jsp) which imported into the original page(inside of iframe) looks like... I can call aaa.com:9080/inFrame.jsp
<%
response.setHeader("X-Frame-Options", "ALLOWAll");
String greetings = request.getParameter("greetings");
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='X-Frame-Options' content='ALLOWAll'>
<title>iframe with aaa.com:9080</title>
</head>
<body>
<div>
greetings message : <%= greetings %>
</div>
<iframe id='iframe' src="http://localhost:63342/third.html?greetings=<%= greetings %>"></iframe>
</body>
</html>
This is the third frame aaa.com:63342/third.html, final
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='X-Frame-Options' content='ALLOWALL'>
<title>ACCESS TO TOP FRAME on localhost:63342</title>
</head>
<body>
<script>
function setGrandfather(){
var greetings = getParams()['greetings'];
window.top.setGreetings(greetings);
}
//parsing parameters
function getParams() {
var param = new Array();
var url = decodeURIComponent(location.href);
url = decodeURIComponent(url);
var params;
params = url.substring( url.indexOf('?')+1, url.length );
params = params.split("&");
var size = params.length;
var key, value;
for(var i=0 ; i < size ; i++) {
key = params[i].split("=")[0];
value = params[i].split("=")[1];
param[key] = value;
}
return param;
}
</script>
</body>
</html>
What happens here
the original page has iframe which has different domain
the second page(iframed in the original page) also has an iframe which has same origin with original page
the second page will send data to its iframe(the third page) with post/get. I wish it could access other frame element via parent.document or iframe.contentDocument.document, but these will be blocked by SAMEORIGIN policy.
In third page you can access functions and elements of the original frame since they have same origin(domain + ports).
CAUTION
frames can not communicate directly
only those pages has common url, possible to set sub domain via document.domain
I am trying to do a JSP program where there is a number and a button. Upon clicking the button, the number above increments. I need to use sessions in this program.
This is the code I did:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title> Welcome </title>
</head>
<body>
<%
// check if there already is a "Counter" attrib in session
AddCount addCount = null;
int test = 0;
String s;
try {
s = session.getAttribute("Counter").toString();
} catch (NullPointerException e){
s = null;
}
if (s == null){
// if Counter doesn't exist create a new one
addCount = new AddCount();
session.setAttribute("Counter", addCount);
} else {
// else if it already exists, increment it
addCount = (AddCount) session.getAttribute("Counter");
test = addCount.getCounter();
addCount.setCounter(test);
addCount.addCounter(); // increment counter
session.setAttribute("Counter", addCount);
}
%>
<%! public void displayNum(){ %>
<p> Count: <%= test %> </p>
<%! } %>
<input TYPE="button" ONCLICK="displayNum()" value="Add 1" />
</body>
</html>
The result is that every time I run the program, the number increments.. however I do not want this to happen.. I want the number to increment upon clicking the button :/ What am I doing wrong?
Thanks for any help. Would be very much appreciated!
A schematic JSP, as it could have been done.
Here I assume that the page is named "counter.jsp" and that the AddCount class resides in a package "mypkg".
JSP encodings can be set in the HTML header lines, before the first HTML browser text.
For ISO-8859-1 you may actually use encoding Windows-1252, with extra chars, like special comma-like quotes. Even MacOS browsers will accept these.
Here I check whether the button was clicked, as whether the form parameter "somefield" is present. (There are other possibilities.)
session="true" is crucial here.
<%#page contentType="text/html; charset=Windows-1252"
pageEncoding="Windows-1252"
session="true"
import="java.util.Map, java.util.HashMap, mypkg.AddCount" %>
<%
// Check if there already is a "Counter" attrib in session
AddCount addCount = (AddCount)session.getAttribute("Counter");
if (addCount == null) {
// If Counter doesn't exist create a new one
addCount = new AddCount();
session.setAttribute("Counter", addCount);
}
// Inspect GET/POST parameters:
String somefield = request.getParameter("somefield");
if (field != null) {
// Form was submitted:
addCount.addCounter(); // increment counter
}
int count = addCount.getCounter();
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome - counter.jsp</title>
</head>
<body>
<p> Count: <%= count %></p>
<form action="counter.jsp" method="post">
<input type="hidden" name="somefield" value="x" />
<input type="submit" value="Add 1" />
</form>
</body>
</html>