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")%>
Related
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
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'm trying to keep a user logged in after they have entered their details on the login screen. I'm using apache tomcat and MS access database. I can log in with a user stored in my database. But I can't figure out how to keep the user logged in throughout my website. I have been reading up about sessions and trying sample code but I can't get it to work, I keep getting different errors. I managed to "Welcome" the user by name after login, but I can't keep the welcome user message, if I click on any other of my webpages.
loginJsp.jsp-
<sql:setDataSource
var = "bookdB"
scope = "session"
driver = "sun.jdbc.odbc.JdbcOdbcDriver"
url = "jdbc:odbc:bookdB"
/>
<sql:query var ="NameCheck" scope = "session" dataSource = "${bookdB}">
SELECT * FROM Users
WHERE Username = ?
AND Password = ?
<sql:param value = "${param.user}" />
<sql:param value = "${param.password}" />
</sql:query>
<c:if test = "${NameCheck.rowCount == 0}">
<jsp:forward page = "loginError.html"/>
</c:if>
<c:if test = "${NameCheck.rowCount != 0}">
<jsp:forward page = "index.jsp"/>
index.jsp
<sql:query dataSource="${bookdB}" var="result">
SELECT * FROM Users
WHERE Username = ?
AND Password = ?
<sql:param value = "${param.user}" />
<sql:param value = "${param.password}" />
</sql:query>
<font color="orange" face="Futura Std-Light" size="4">
<c:forEach var="row" items="${result.rows}">
Welcome ${row.FirstName}!
</c:forEach>
</font>
Any help would be much appreciated, Thanks!
Is this right:
<c:if test = "${NameCheck.rowCount == 0}">
HttpSession session = request.getSession();
session.setAttribute("connecte", "true");
session.setAttribute("login", "${param.user}");
<jsp:forward page = "loginError.html"/>
</c:if>
in your servlet action handler add this:
HttpSession session = request.getSession();
session.setAttribute("connecte", "true");
session.setAttribute("login", "TOM");
in your JSP add this on the top of your page
<%
if (session.getAttribute("connecte") == null
|| !((String) session.getAttribute("connecte"))
.equals("true")) {
String redirectURL = "/path/ToYour/login.jsp;
response.sendRedirect(redirectURL);
}
%>
<h1>Hello <%= session.getAttribute("login") %></h1>
if it's OK it will show
Hello Tom
#
login.jsp:
<!DOCTYPE html>
<html>
<head>
<meta charset="US-ASCII">
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="post">
Username: <input type="text" name="user">
<br>
Password: <input type="password" name="pwd">
<br>
<input type="submit" value="Login">
</form>
</body>
</html>
#
LoginServlet.java:
package com.journaldev.servlet.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "Pankaj";
private final String password = "journaldev";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// get request parameters for userID and password
String user = request.getParameter("user");
String pwd = request.getParameter("pwd");
if(userID.equals(user) && password.equals(pwd)){
Cookie loginCookie = new Cookie("user",user);
//setting cookie to expiry in 30 mins
loginCookie.setMaxAge(30*60);
response.addCookie(loginCookie);
response.sendRedirect("LoginSuccess.jsp");
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
PrintWriter out= response.getWriter();
out.println("<font color=red>Either user name or password is wrong.</font>");
rd.include(request, response);
}
}
}
#
LoginSuccess.jsp:
<%# page language="java" contentType="text/html; charset=US-ASCII"
pageEncoding="US-ASCII"%>
<!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=US-ASCII">
<title>Login Success Page</title>
</head>
<body>
<%
String userName = null;
Cookie[] cookies = request.getCookies();
if(cookies !=null){
for(Cookie cookie : cookies){
if(cookie.getName().equals("user")) userName = cookie.getValue();
}
}
if(userName == null) response.sendRedirect("login.html");
%>
<h3>Hi <%=userName %>, Login successful.</h3>
<br>
<form action="LogoutServlet" method="post">
<input type="submit" value="Logout" >
</form>
</body>
</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>