JSP simple program - html

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>

Related

Java Servlet and JSP cannot view arraylist from session initially

I'm a complete beginner to JSPs and servlets and I would appreciate it if you could help me on this small problem. I have an index.html file that has links to two JSP files: addItem.jsp (user can input item into their todDo list, and submit button links to servlet), and toDoList.jsp (shows the toDO list and redirects via a button to addItem.jsp)
The problem I am having is that when I view the toDoList.jsp before adding an item to the list, the list does not appear. However, I add an item on addItem.jsp, the list shows from the servlet, and now I can view the full list, including the item that was added on toDoList.jsp.
How can I change my code so that I don't have to add something to the list to view it?
toDoList.jsp :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="javax.servlet.http.HttpSession" %>
<%#page import="java.util.ArrayList" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>My ToDo List:</h1>
<% ArrayList<String> toDoList = new ArrayList<String>();%>
<% if(session.getAttribute("toDoList") != null) { // If the list exists in the session %>
<% toDoList = (ArrayList<String>) session.getAttribute("toDoList");%>
<% for(String toDoItem:toDoList) { %>
<% out.println(toDoItem); %><br>
<% } %>
<% } else {%>
<h3>Your list is empty!</h3>
<% } %>
<form action="addItem.jsp" method="post">
<fieldset>
<input type="submit" value="Add Item">
</fieldset>
</form>
</body>
addItem.jsp :
<!DOCTYPE html>
<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="Servlet1" method="post">
<fieldset>
<label>New ToDo Item:</label>
<input type="text" name="item"><br>
<input type="submit" value="Submit">
</fieldset>
</form>
</body>
The main Servlet1 code:
#WebServlet(urlPatterns = {"/Servlet1"})
public class Servlet1 extends HttpServlet {
ArrayList<String> toDoList = new ArrayList<String>();
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String item = request.getParameter("item");
toDoList.add(item);
HttpSession session = request.getSession();
boolean is_toDoList_Initilized = false;
if(session.getAttribute("toDoList") == null) {
is_toDoList_Initilized = false;
session.setAttribute("toDoList", toDoList);
} else is_toDoList_Initilized = true;
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Servlet1</title>");
out.println("</head>");
out.println("<body>");
for(String toDoItem:toDoList) {
out.println(toDoItem + "<br>");
}
out.println(is_toDoList_Initilized);
out.println("</body>");
out.println("</html>");
}
}
I think you just need to call that servlet before redirecting your toDoList.jsp from your index page.
Flow will be like
flow 1: index.jsp > servlet1 > toDoList
flow 2: index.jsp > addItem.jsp > servlet1 > toDoList

HTML onload script triggered too many times?

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>

Issue with web application using JSP and Hibernate

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 )

JSP and MYSQL: how do I relay a SQL Exception

I am trying to create a login screen which will allow a user to enter a unqiue ID. How do I relay the information to a user that the ID chosen is not unique. So far all I'm able to do is trigger the exception.
Registration.jsp
<%# 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>Enter Your details here</title>
</head>
<body>
<h3>Enter User ID</h3>
<br>
<form action = "RegistrationServlet" method = "post">
Enter User ID : <input type = "text" name ="newUserId"/>
<br>Enter your Password : <input type = "password" name ="newUserPassword"/>
<br>Enter your First Name :<input type = "text" name = "newUserFirstName"/>
<br>Enter your Last Name : <input type = "text" name ="newUserLastName"/>
<br><input type = "submit"/>
<br>
<%=session.getAttribute("notUniqueUserID")%>
</form>
</body>
</html>
RegististrationServlet
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
boolean notUniqueUserID = true;
request.getSession(notUniqueUserID);
response.sendRedirect("registration.jsp");
}
This is not the best solution as it will reload the form and the user will need to enter all the data again, I would suggest you to use AJAX for this kind of verification.
Anyway here is a piece of code to set one attribute to the request and get it in the jsp.
Servlet:
}catch (SQLException e) {
e.printStackTrace();
boolean notUniqueUserID = true;
request.setAttribute("notUniqueUserID", "Not Unique User ID");
request.getRequestDispatcher("registration.jsp").forward(request, response);
}
JSP:
<%=request.getAttribute("notUniqueUserID")%>

Sessions JSP button click

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"));
%>