How to initialize a hash map at Server startup? - java

I have created a simple login application using JSP form and displaying HomePage through a Servlet.I have also created a HashMap inside servlet which stores a couple of username and passwords.When a user enters username and password it is compared with those present inside the map and appropriate message is displayed.But the problem here is the HashMap is initialized after user hits the Login button i.e,when servlet program starts up.I want to initialize the map before hand and when ever user logs in the comparison with map should take place,instead of initialising map after Logging in.Kindly help me how I can go about it.
Here is what I have done so far
Login.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>Login</title>
</head>
<body>
<center>
<b>LOGIN PAGE</b><br>
</center>
<form name="login" method="post" action="UserAuthentication">
<center>
USER NAME: <input type="text" name="username">
<br>
<br>
PASSWORD: <input type="password" name="password">
<br>
<br>
<input type="submit" value="LOGIN">
</center>
</form>
</body>
</html>
UserAuthentication.java
public class UserAuthentication extends HttpServlet{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws IOException{
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter out = response.getWriter();
Map<String,String>users = new HashMap<String,String>();
users.put("Sheetal", "sss");
users.put("Raj","rrr");
users.put("Anjali", "aaa");
users.put("Bhavya","bbb");
if(users.containsKey(username) && users.containsValue(password))
{
if(password.equals(users.get(username)))
{
out.println("<html>"+
"<body>"+
"Login Successful" + "<br>" +
"Welcome " + username + "<br>" +
"</body>" +
"</html>");
}
}
else
{
out.println("<html>"+
"<body>"+
"Login Unsuccessful" + "<br>" +
"Try again" + "<br>" +
"</body>" +
"</html>");
}
}
}
TIA

Make the hashmap a static in the class (I also assumed its final):
private static final Map<String,String> users = new HashMap<>();
And populate it in the static initializer block:
static {
users.put("Sheetal", "sss");
users.put("Raj", "rrr");
users.put("Anjali", "aaa");
users.put("Bhavya", "bbb");
}
This way, the HashMap will be populated, when the class is registered.
If you did not know about initializers, please read this article.

The best way in your case is to create a singleton class called users, which would be like below.
public class Users{
private static Map<String,String> users = new HashMap<>();
private users(){
users.put("Sheetal", "sss");
users.put("Raj", "rrr");
users.put("Anjali", "aaa");
users.put("Bhavya", "bbb");
}
public static Users singleInstance = new Users();
public boolean validate(String userName,String password)
{
boolean result = false;
if(condition)
result = true;
return result;
}
and in your UserAuthentication.java when you want to do the validation,
if(Users.singleInstance.validate(userName,password))

Related

HttpSession doesn't persist from JSP to Servlet

I've an InitializeServlet that creates and instantiates a HttpSession then redirects to a JSP (betFinalize.jsp). Here I can work on my session. When from that JSP I redirect (through a form) to another Servlet, FinalizeServlet I loose my session. I cannot figure out why. Following code.
InitializeServlet.java
public class InitializeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fName = request.getParameter("fName");
String lName = request.getParameter("lName");
String result = request.getParameter("result");
Bet s = new Bet();
s.setFirstLastName(fName + " " + lName);
s.setResult(result);
s.setMultiplier(calculateMultiplier());
request.getSession(true).setAttribute("bet", s);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/betFinalize.jsp");
rd.forward(request, response);
}
private double calculateMultiplier() {
return 0.8;
}
}
betFinalized.jsp
<%# page import="it.unibo.tw.model.beans.Bet"%>
<%# page import="it.unibo.tw.model.beans.Bets"%>
<%# page session="true"%>
<jsp:useBean id="bet" class="it.unibo.tw.model.beans.Bet" scope="session"></jsp:useBean>
<jsp:useBean id="finalizedBets" class="it.unibo.tw.model.beans.Bets" scope="application"></jsp:useBean>
<!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">
</head>
<body>
<h1>Hi, <%= bet.getFirstLastName() %></h1>
<h2>Current bet: <i><%= bet.toString() %></i></h2>
<form action="finalize" method="get">
<input id="import" type="number" name="import" onkeyup="calculateWin()" ><br />
<input id="win" type="text" name="win" readonly ><br />
<input type="submit">
</form>
<hr />
<ul>
<% for(Bet s : finalizedBets.getList()) { %>
<li><%= s.toString() %></li>
<% } %>
</ul>
</body>
<script>
function calculateWin() {
var multiplier = <%= bet.getMultiplier() %>
var imp = document.getElementById("import").value
document.getElementById("win").value = imp * multiplier
}
</script>
</html>
FinalizeServlet.java
public class FinalizeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
double vincita = Double.parseDouble(request.getParameter("win"));
Bet s = (Bet) request.getSession().getAttribute("bet");
if(s != null) {
// NEVER REACH HERE
s.setWin(vincita);
s.setFinalized(true);
Bets scommesseFinalized = (Bets) getServletContext().getAttribute("scommesseFinalized");
scommesseFinalized.getList().add(s);
}
request.getSession().invalidate();
RequestDispatcher rd = getServletContext().getRequestDispatcher("/start.html");
rd.forward(request, response);
}
}
You're trying to get the wrong attribute. When you set the session variable you have:
request.getSession(true).setAttribute("scommessa", s);
When you try to read it:
request.getSession().getAttribute("bet");
it should be:
request.getSession().getAttribute("scommessa");
instead.
Encode the session id in the action of the form as below:
<form action="<%=response.encodeURL("finalize")%>" method="get">

Sending values from jsp to servlet then back to jsp

I know similar questions have been asked earlier but for some reason it is not working. I am just trying to check if user has entered both the fields on the login page or not. If not, then I want to display the message on jsp saying that they need to enter both the credentials. Here is my JSP:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<!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>Login</title>
</head>
<body>
<h2>Some App</h2>
<form action="login" method="post">
<table>
<tr>
<td>Username</td>
<td><input type="text" name="uname"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" id="pass" name="pass"></td>
</tr>
</table>
<br> <input type="button" value="Submit">
</form>
<c:out value= "${error}"/>
</body>
</html>
Then here is the servlet:
#WebServlet("/login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Login() {
super();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
//Getting values from the form
String username = request.getParameter("uname");
String password = request.getParameter("pass");
System.out.println("Username is: "+ username);
System.out.println("Password is: "+ password);
//User user = new User();
if((username.equals(""))|| password.equals("")){
String message = "Please enter both the credentials";
request.setAttribute("error", message);
//RequestDispatcher rd = request.getRequestDispatcher("/login.jsp");
//rd.forward(request, response);
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
}
else{
RequestDispatcher rd = request.getRequestDispatcher("/index.jsp");
rd.forward(request, response);
}
//Setting values in the session
session.setAttribute("username", username);
session.setAttribute("password", password);
}
}
Since I am trying to experiment with maven, here is my pom.xml file with dependency added for jstl jar:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
Why does that c:out tag not print anything? What am I doing wrong? Any help will be appreciated. Thank You.
You are mixing two styles of returning a response to the client. Try passing the error message using this code:
if((username == null)|| password == null) {
String message = "Please enter both the credentials";
request.setAttribute("error", message);
getServletContext().getRequestDispatcher("/login.jsp").forward(request, response);
}
The rule of thumb is that you have to use request.setAttribute() with forward() and request.getSession().setAttribute() with response.sendRedirect().
try ${sessionScope['error']} instead of ${error}. If that worked then you may have another attribute in another scope with the same name 'error'
You should also check if username or password are empty. i.e. (username != null && username.trim().isEmpty())
Suggestions from everyone was very valuable. There were a few things that I was doing wrong: incorrect servlet mapping (#WebServlet fixed it), changed code to what #NaMaN and #bphilipnyc replied and the biggest mistake due to which I wasn't able to reach servlet was that I had input type as button in jsp. I changed it to input type submit, and then it worked. Thank you guys for replying. Really appreciate it.

How to compare the elements inside map with another element?

I am trying a simple login page using JSP form and Displaying HomePage through a servlet.I am storing a couple of username and passwords inside a hashmap.I would like to compare the username and password entered by the user with those existing inside the hashmap and display an error message if username or password is wrong.How can I achieve this?
TIA
Login.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>Login</title>
</head>
<body>
<center>
<b>LOGIN PAGE</b><br>
</center>
<form name="login" method="post" action="Servlet1">
<center>
USER NAME: <input type="text" name="username">
<br>
<br>
PASSWORD: <input type="password">
<br>
<br>
<input type="submit" value="LOGIN">
</center>
</form>
</body>
Servlet1.java
public class Servlet1 extends HttpServlet{
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws IOException{
String username;
String password;
String uname;
String pwd;
username = request.getParameter("username");
password = request.getParameter("password");
PrintWriter out = response.getWriter();
Map<String,String>users = new HashMap<String,String>();
users.put("Sheetal", "sss");
users.put("Raj","rrr");
}
}
public boolean checkAccess(String username,String password){
return password.equals(users.get(username));
}
Retrieve the user's password from the map and check it against the supplied password.
boolean valid = password.equals(users.get(username));
import java.util.HashMap;
import java.util.Map;
class Main {
public static void main(String args[]) {
Map<String, String> credentials = new HashMap<String, String>();
credentials.put("user", "correctpass");
String inputUsername = "user";
String inputPassword = "correctpass";
String passOnMap = credentials.get(inputUsername);
if (passOnMap != null
&& passOnMap.equals(inputPassword)) {
// correct login
} else {
// wrong user/passw
}
}
}
public class Servlet1 extends HttpServlet{
final Map<String, String> users = new HashMap<>();
#Override
public void init() throws ServletException {
// user name as key and it is unique for every user. password as value.
users.put("user1", "pwd1");
users.put("user2", "pwd2");
users.put("user3", "pwd3");
users.put("user4", "pwd4");
users.put("user5", "pwd5");
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String strUserName = request.getParameter("user1");
String strPassword = request.getParameter("pwd1");
String userpassword = users.get(strUserName);
if (userpassword != null
&& userpassword.equals(strPassword)) {
// login success
} else {
// invalid user
}
}
}
public boolean checkAccess(Map<String, String> users, String username,String password) {
boolean retunValue = Boolean.FALSE;
if (users != null && users.size() > 0 && !username.isEmpty()
&& !password.isEmpty()) {
if (users.get(username) != null) {
if (password.equals(users.get(username)))
retunValue = true;
}
}
return retunValue;
}

How do I print an error message to user screen instead of standard out in JSP?

I was wondering how I can print an error message to the user in the case he/she entered the wrong passowrd in JSP. Given that I have the form set up and validation works, I am trying to add this one check but the output is printed to the standard out ie console, however, I would like for it to be printed to the screen that the user is viewing. Here's my code for authentication:
public boolean verify (String username, String password) {
if (!password.equals("1234")) {
System.out.println("Wrong password!\n");
return false;
}
return true;
}
EDIT: LoginProcessing.java calls the method above and checks the boolean value (logedin), if it is not set I execute the code below, but it still doesn't print to the screen where user can see it.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// skipping initializations for brevity
if (logedin) {
// do stuff
}else {
System.out.println("Wrong password!\n");
response.sendRedirect("login.jsp");
return;
}
}
EDIT 2: Here's what my code looks like in login.html to which I redirect in the code above from the doPost() method, except I removed the println() method.
<%# 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>Login Using JSP</title>
</head>
<body>
<form action="login" method="post">
Please enter your username: <input type="text" name="username"><br>
Please enter your password:<input type="password" name="password"><br>
<input type="submit">
</form>
<c:if test="${!loggedin}">
Sorry. Wrong user name or password
</c:if>
</body>
</html>
In your servlet method:
// check the credentials
boolean loggedIn = verify(username, password);
// store the result in a request attribute, so that the JSP can retrieve it
request.setAttribute("loggedIn", loggedIn);
// let a JSP display the result
request.getRequestDispatcher("/loginResult.jsp").forward(request, response);
In the JSP (using the JSTL), test the value of the loggedIn request parameter:
<c:if test="${loggedIn}">
Congratulations: you're now logged in.
</c:if>
<c:if test="${!loggedIn}">
Sorry. Wrong user name or password
</c:if>

Pass string from .JSP form to .Java class and execute main argument

Here is my index.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">
<jsp:useBean id="ContentLoader" class="com.content.ContentLoader" scope="session"/>
<jsp:setProperty name="ContentLoader" property="*"/>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Content Loader</title>
</head>
<body>
<h1>Content API: Loader</h1>
<a>Select a CSV file from your computer.<br>
Enter the API key and secret for your account<br>
Click submit when you are ready to load the products!! <br>
</a>
<br>
<form action="index.jsp" method="GET">
API Key: <input type="text" name="api_key">
<br>
API Secret: <input type="text" name="api_secret" />
<br>
Choose CSV File: <input type="file" name="csv_file" />
<br>
<input type="submit" value="Submit To Content API" />
</form>
<br>
This is feedback from the program<br>
**strong text**
You entered<BR>
Name: <%= ContentLoader.getApi_key() %><BR>
Email: <%= ContentLoader.getApi_secret() %><BR>
Age: <%= ContentLoader.getCsv_file() %><BR>
</body>
</html>
When I hit the submit button, I want to pass the 3 strings to the Java application.
(key, secret, and the contents of my csv)
Right now I get "The requested resource is not available" error (HTTP Status 404)
Here is my ContentLoader.java
package com.content;
public class ContentLoader {
private String api_key = "testKey2";
private String api_secret= "testSecret";
private String csv_file = "testFileString";
public ContentLoader() {
// TODO Auto-generated constructor stub
}
public void setApi_key(String api_key) {
this.api_key = api_key;
}
public void setApi_secret(String api_secret) {
this.api_secret = api_secret;
}
public void setCsv_file(String csv_file) {
this.csv_file = csv_file;
}
public String getApi_key() {
return api_key;
}
public String getApi_secret() {
return api_secret;
}
public String getCsv_file() {
return csv_file;
}
}
The ContentLoader.java above is supposed to send and receive strings from the JSP form. When the submit button is hit, I need the 3 strings to pass to Application.java, and the main argument needs to be executed. Right now this is not happening, and I don't understand why. Thanks!!!!
This is my Application.java
import java.io.IOException;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class Application implements ServletContextListener{
#Override
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("Tomcat just started");
}
#Override
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("Tomcat just stopped");
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
System.out.println("hi!! Your program is executing");
/**
//Null Credentials
String apiKey = "000";
String apiSecret = "000";
}
}
Web applications doesn't work like that, and Servlet don't need a main method to work, actually it doesn't know how to use it, instead of that you can use http request from your java application (main methode) to call a jsp file that returns 3 paramteres (in xml format or json) and you can pick those parametres and use them in your application as you want.

Categories