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;
}
Related
I am new to this so I am a little bit green in jsf based applications.I am trying to display the set attribute in dashboard.xhtml page
Here is my servlet class:
public class LoginServlet extends HttpServlet{
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
LoginDAO loginService = new LoginDAO();
boolean result = loginService.authenticateUser(username, password);
Users users = loginService.getUserByuserName(username);
if(result == true ){
request.getSession().setAttribute("user", users);
System.out.println("user"+users.getuserName());
response.sendRedirect("dashboard.xhtml");
}
else{
response.sendRedirect("error.jsp");
}
}
}
dashboard.xhtml:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<title>DASHBOARD</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<h:outputText value="#{user.username)}"/>
</body>
But, it is not displaying anything? What am I missing? Any help will be appreciated. Thank you!
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">
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))
A user clicks on edit on the index.jsp page and it sends them to a editCustomer.jsp page. The problem is when I click update it doesnt update the customer information on the index page.
How can I do this using the code I have?
INDEX.JSP
<%#page import="edu.witc.Assignment02.controller.CustomerServlet"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.ArrayList" %>
<!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>Home</title>
</head>
<body>
<ul>
<% String customerString ="";
ArrayList<edu.witc.Assignment02.model.Customer> customers = (java.util.ArrayList)request.getAttribute("customers");
for (edu.witc.Assignment02.model.Customer customer : customers) {
customerString += "<li>" + customer.getName() +
"(" + customer.getCity() + ") (" +
"<a href='editCustomer?id=" + customer.getId() +
"'>edit</a>)</li>";
}%>
<%=customerString %>
</ul>
<body>
</html>
EDITCUSTOMER.JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#page import="edu.witc.Assignment02.controller.CustomerServlet"%>
<!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>Edit Customer</title>
</head>
<body>
<h2>Edit Customer</h2>
<% int customerId =
Integer.parseInt(request.getParameter("id"));%>
<form method='post' action='customer'>
<input type='hidden' name ='id' value='<%=customerId%>'/>
<table>
<tr><td>Name:</td><td>"
<input name='name' />
</td></tr>
<tr><td>City:</td><td>
<input name='city' />
</td></tr>
<tr>
<td colspan='2' style='text-align:right'>
<input type='submit' value='Update'/></td>
</tr>
<tr><td colspan='2'>
<a href='customer'>Customer List</a>
</td></tr>
</table>
</form></body>
</html>
SERVLET
package edu.witc.Assignment02.controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import edu.witc.Assignment02.*;
import edu.witc.Assignment02.model.Customer;
/*
* Not thread-safe. For illustration purpose only
*/
#WebServlet(name = "CustomerServlet", urlPatterns = {
"/customer", "/editCustomer", "/updateCustomer"})
public class CustomerServlet extends HttpServlet {
private static final long serialVersionUID = -20L;
private List<edu.witc.Assignment02.model.Customer> customers = new ArrayList<Customer>();
#Override
public void init() throws ServletException {
Customer customer1 = new Customer();
customer1.setId(1);
customer1.setName("Donald D.");
customer1.setCity("Miami");
customers.add(customer1);
Customer customer2 = new Customer();
customer2.setId(2);
customer2.setName("Mickey M.");
customer2.setCity("Orlando");
customers.add(customer2);
}
private void sendCustomerList(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/index.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
private Customer getCustomer(int customerId) {
for (Customer customer : customers) {
if (customer.getId() == customerId) {
return customer;
}
}
return null;
}
private void sendEditCustomerForm(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String url = "/editCustomer.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
#Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uri = request.getRequestURI();
if (uri.endsWith("/customer")) {
sendCustomerList(response, request);
} else if (uri.endsWith("/editCustomer")) {
sendEditCustomerForm(request, response);
}
}
#Override
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException, ServletException {
// update customer
int customerId = 0;
try {
customerId =
Integer.parseInt(request.getParameter("id"));
} catch (NumberFormatException e) {
}
Customer customer = getCustomer(customerId);
if (customer != null) {
customer.setName(request.getParameter("name"));
customer.setCity(request.getParameter("city"));
}
sendCustomerList(response, request);
}
}
CUSTOMER.JAVA
package edu.witc.Assignment02.model;
public class Customer {
private int id;
private String name;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
I'm not sure what you expect to happen. You are submitting this form
<form method='get' action='customer'>
<table>
<tr>
<td>Name:</td>
<td>
"
<input name='name' />
</td>
</tr>
<tr>
<td>City:</td>
<td>
<input name='city' />
</td>
</tr>
<tr>
<td colspan='2' style='text-align:right'>
<input type='submit' value='Update' />
</td>
</tr>
<tr>
<td colspan='2'>
<a href='customer'>Customer List</a>
</td>
</tr>
</table>
</form>
And handling it with
if (uri.endsWith("/customer")) {
sendCustomerList(response, request);
and
private void sendCustomerList(HttpServletResponse response, HttpServletRequest request)//redirect to index
throws IOException, ServletException {
String url = "/index.jsp";
request.setAttribute("customers", customers);
request.getRequestDispatcher(url).forward(request,response);
}
Nothing in the code above modifies anything in the customers List. Objects don't get changed on their own. You have to make the modifications yourself.
Maybe you meant to submit the form with a POST request. In that case, you would need an <input> field for the id.
Think about the request-response cycle.
Your Servlet container receives an HTTP request, it dispatches your Servlet to handle it. Your servlet performs some logic and forwards to a JSP. The JSP renders some HTML which is written to the body of the HTTP response. The response is sent to the client. In this case, your client is a browser which reads the HTML text and renders it graphically. You can then interact with it, fill in input fields and click buttons. When you do this, the browser takes the values you've entered and produces an HTTP request which it sends to your server. And so on, and so on...
My Jsp file is like this. It has 2 buttons. When i click on 1st button then 1st entity from the datastore should be selected and same with the 2nd button.
<%# 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>
<body style="background-color:black;">
<p>
<p><input type="button" name="first" value="0C F0 0400" style="background-
color:#006600; color:#FFFFFF ; height:100px; width:200px"
onclick="location.href='hello';"> </p>
<p><input type="button" name="first" value="0D F0 0800" style="background-
color:#006600; color:#FFFFFF ; height:100px; width:200px"
onclick="location.href='hello';">
</p>
</body>
</html>
This is the servlet. How to get the 1st entity on the 1st button click and 2nd entity on the 2nd button click.
package pack.exp;
import java.io.IOException;
import javax.servlet.http.*;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
#SuppressWarnings("serial")
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
IOException
{
Key k1 = KeyFactory.createKey("Employee","E1");
Key k2 = KeyFactory.createKey("Employee","E2");
String firstName1 = "Sam";
String lastName1 = "Well";
String firstName2 = "John";
String lastName2 = "Morgan";
Entity bs1 = new Entity(k1);
Entity dm1 = new Entity(k2);
bs1.setProperty("FN", firstName1);
bs1.setProperty("LN", lastName1);
dm1.setProperty("FN", firstName2);
dm1.setProperty("LN", lastName2);
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
datastore.put(bs1);
datastore.put(dm1);
Entity bs2 = null;
Entity dm2 = null;
try
{
bs2= datastore.get(k1);
dm2= datastore.get(k2);
}
catch (EntityNotFoundException e)
{
e.printStackTrace();
}
String fName1= (String) bs2.getProperty("FN");
String lName1= (String) bs2.getProperty("LN");
String fName2= (String) dm2.getProperty("FN");
String lName2= (String) dm2.getProperty("LN");
resp.setContentType("text/plain");
resp.getWriter().println("Person1 Details------> " + fName1 + " " + lName1);
resp.getWriter().println("Person2 Details------> " + fName2 + " " + lName2);
}
}
First you need to store the value into the datastore using doGet() method of servlet.
You can do that using this code:
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
IOException
{
Entity employee1=new Entity("Employee","Employee1");
Entity employee2=new Entity("Employee","Employee2");
employee1.setProperty("FN", "Sam");
employee1.setProperty("LN", "Sam");
employee2.setProperty("FN", "John");
employee2.setProperty("LN", "Morgan");
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
try{
datastore.put(employee1);
datastore.put(employee2);
}
catch(DatastoreFailureException d){
d.printStackTrace();
}
}
Then in the doPost Method get the value for the button clicked. JSP code I have answered in your other question.
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws
IOException
{
String key=req.getParameter("good");
Key key = KeyFactory.createKey("Employee", key);
Entity employee=datastore.get(key);
resp.setContentType("text/plain");
resp.getWriter().println("Person Details------> " + employee.getProperty("FN")+ " " +employee.getProperty("LN"));
}