MVC pattern in jsp,java,servlet - java

I am trying to create a register page which business logic is managed in servlet (Controller class), parameter values are called from a Javabean (Bean class) and uses a class to handle the database connectivity (Dbconnect class). We register and then we have to sign in through index.jsp. If the user is valid, the system should display a welcome page (welcome.jsp) showing the user name.
I don't know how to connect these classes to be called through my jsp to process the login. Here is the code showing what I have tried. I had seen many web source but couldn't understand the process..
This is how I think the communication of classes should be:
Dbconnection.java--->bean.java--->Controller.java--->register.jsp--->login.jsp--->welcome.jsp
Index.jsp:
User name:<input type="text" name="username">
Password:<input type="password" name="password">
<input type="submit" name="Login"> Register
Register.jsp
<form action="Loginservlet" method="post">
User name:<input type="text" name="name" >
Password:<input type="password" name="pass">
Email-id<input type="text" name="emailid">
phone number:<input type="text" name="phone">
<input type="submit" value="submit">Login
</form>
Bean.java
package Databases;
public class Bean
{
private String username;
private String password;
private String emailid;
private String phone;
/**
* #return the username
*/
public String getUsername()
{
return username;
}
/**
* #param username the username to set
*/
public void setUsername(String username)
{
this.username = username;
}
/**
* #return the password
*/
public String getPassword()
{
return password;
}
/**
* #param password the password to set
*/
public void setPassword(String password)
{
this.password = password;
}
/**
* #return the emailid
*/
public String getEmailid()
{
return emailid;
}
/**
* #param emailid the emailid to set
*/
public void setEmailid(String emailid)
{
this.emailid = emailid;
}
/**
* #return the phone
*/
public String getPhone()
{
return phone;
}
/**
* #param phone the phone to set
*/
public void setPhone(String phone)
{
this.phone = phone;
}
}
Dbconnect.java
package Databases;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
public class Dbconnect
{
public static void main(String args[]) throws ClassNotFoundException
{
Dbconnect db = new Dbconnect();
db.dbconnect();
}
public void dbconnect() throws ClassNotFoundException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mine", "root", "android");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from user");
while(rs.next())
{
ArrayList al=new ArrayList();
al.add(rs.getString("name"));
al.add(rs.getString("password"));
al.add(rs.getString("email"));
Iterator it=al.iterator();
while(it.hasNext())
{
System.out.println("value are:"+it.next());
}
}
Controller.java:
package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.PreparedStatement;
import Databases.Dbconnect;
import Databases.*;
/**
* Servlet implementation class Loginservlet
*/
public class Controller extends HttpServlet
{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String pass = request.getParameter("pass");
String email = request.getParameter("emailid");
String pn = request.getParameter("phone");
System.out.println("Name :" + name);
System.out.println("pass :" + pass);
System.out.println("emailid :" + email);
System.out.println("phone:" + pn);
String a = Bean.setUsername(name);
String b=Bean.setPassword(name);
String c=Bean.setEmailid(name);
String dBean.setPhone(name);
String sql = "insert into user(name,password,email,phone) values(?,?,?,?)";
Dbconnect a = new Dbconnect();
a.dbconnect();
PreparedStatement prep = a.dbconnect().prepareStatement(sql);
// Setting the values which we got from JSP form
prep.setString(1, a);
prep.setString(2, b);
prep.setString(3, c);
prep.setString(4, d);
prep.executeUpdate();
prep.close();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>WebprojectTry</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>Controller</display-name>
<servlet-name>Controller</servlet-name>
<servlet-class>servlet.Controller</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Controller</servlet-name>
<url-pattern>/Controller</url-pattern>
</servlet-mapping>
</web-app>

Related

Registration form using JDBC and Servlet in java

I have problem accessing database with servlet java. I want to add users with an html registration form. this is the html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Registration Page</title>
<!---Custom CSS File--->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<header>Registration Form</header>
<form action="register" method="post" class="form">
<div class="input-box">
<label>Full Name</label>
<input type="text" name="txtUname" placeholder="Enter full name" required />
</div>
<div class="input-box">
<label>Email Address</label>
<input type="email" name="Email" placeholder="Enter email address" required />
</div>
<div class="input-box">
<label>Password</label>
<input type="password" name="Pass" placeholder="Password" required />
</div>
<button>REGISTER</button>
</form>
</body>
</html>
This is the servlet (RegistrationControllerServlet.java)
package com.loginpagedemo.controller;
import java.io.IOException;
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 com.loginpagedemo.dao.UserDao;
import com.loginpagedemo.daoimpl.UserDaoImpl;
import com.loginpagedemo.pojo.User;
#WebServlet("/register")
public class RegistrationControllerServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String uname = request.getParameter("txtUname");
String password = request.getParameter("Pass");
String email = request.getParameter("Email");
User u = new User(uname,password,email);
UserDao daoImpl = new UserDaoImpl();
if(daoImpl.addNewUser(u)) {
response.sendRedirect("Success?msg=regsuccess");
}
else {
response.sendRedirect("error?msg=regerror");
}
}
}
This is the java class (User.java):
package com.loginpagedemo.pojo;
public class User {
private String username;
private String emailaddress;
private String password;
public User() {
}
public User(String username,String emailaddress,String password){
this.username = username;
this.emailaddress =emailaddress;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmailaddress() {
return emailaddress;
}
public void setEmailaddress(String emailaddress) {
this.emailaddress = emailaddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
This is the java Interface (UserDao.java):
package com.loginpagedemo.dao;
import com.loginpagedemo.pojo.User;
public interface UserDao {
boolean checkUserCredentials(User user);
boolean addNewUser(User user);
}
This is the java class (DbConnection.java):
package com.loginpagedemo.connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DbConnection {
public static Connection getDatabaseConnection(){
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/28thnovadv",
"root","ROOT#123");
return con;
}
catch(ClassNotFoundException | SQLException exc) {
exc.printStackTrace();
return null;
}
}
}
This is the java class (UserDaoImpl.java):
package com.loginpagedemo.daoimpl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.loginpagedemo.connection.DbConnection;
import com.loginpagedemo.dao.UserDao;
import com.loginpagedemo.pojo.User;
public class UserDaoImpl implements UserDao {
#Override
public boolean checkUserCredentials(User user) {
try(Connection con =
DbConnection.getDatabaseConnection()){
PreparedStatement st = con.prepareStatement(
"SELECT * FROM userdata WHERE username=? AND email=? AND password=?");
st.setString(1, user.getUsername());
st.setString(2, user.getEmailaddress());
st.setString(3, user.getPassword());
ResultSet rs =st.executeQuery();
if(rs.isBeforeFirst())
return true;
else
return false;
}
catch(SQLException | NullPointerException exc){
exc.printStackTrace();
return false;
}
}
#Override
public boolean addNewUser(User user) {
try(Connection con =
DbConnection.getDatabaseConnection()){
PreparedStatement st = con.prepareStatement(
"INSERT INTO userdata VALUES(?,?,?)");
st.setString(1, user.getUsername());
st.setString(2, user.getEmailaddress());
st.setString(3, user.getPassword());
int count = st.executeUpdate();
if(count > 0)
return true;
else
return false;
}
catch(SQLException | NullPointerException exc){
exc.printStackTrace();
return false;
}
}
}
This is the Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>LoginpageJDBC</display-name>
<welcome-file-list>
<welcome-file>RegistartionFrom.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>registration</servlet-name>
<servlet-class>com.loginpagedemo.controller.RegistrationControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>registration</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>
Folder Structure
error after updated
I'm sorry that is a long question, but I am in despair
Looks like your implementation of method dopost() is wrong.
It should be doPost().
https://jenkov.com/tutorials/java-servlets/httpservlet.html
Like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
You can also try to configure manually the servlet in WEB-INF/web.xml.
Something like:
<web-app>
<servlet>
<servlet-name>registration</servlet-name>
<servlet-class>com.loginpagedemo.controller.RegistrationControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>registration</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>
https://javapapers.com/servlet/what-is-servlet-mapping/

Dynamic Web Project, create object with variables submitted by for with GET method

I am trying to get the values from a form in order to create an object with those values. How would I do this? Also currently when I hit submit I get the http 404 error. I know I'm doing this wrong, I just don't know how to fix it!
I have created the form with the following code:
<html lang="en">
<head>
<title>Example</title>
</head>
<body>
<h1>Welcome to Loggy!</h1>
<form id="logForm" action="LogsServlet" method="GET">
<h3>What have you been up to today?</h3>
<br>
<label id="logTitleLabel" for="logTitle">Title :</label>
<br>
<input type="text" id="logTitle" name="logTitle">
<br>
<label id="logDescriptionLabel" for="LogDescription">Description</label>
<br>
<input type="text" id="logDescription" name="logDescription">
<label id="logContentLabel" for="logContent">Content :</label>
<br>
<input type="text" id="logContent" name="logContent">
<button type="submit" id="submitLog">Submit Log</button>
</form>
</body>
</html>
Here are the abstract Log Class and TextLog Class:
import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;
public abstract class Log {
private UUID id;
private String title;
private String description;
private String content;
private Timestamp createTimestamp;
//Constructor
Log(String title,String description, String content){
this.setTitle(title);
this.description=description;
this.content=content;
};
public void create() {
//call UUID method
id();
//create new timeStamp
Date date= new Date();
Timestamp createTimestamp = new Timestamp(date.getTime());
this.createTimestamp=createTimestamp;
}
public UUID id() {
UUID uuid = UUID.randomUUID();
id = uuid;
return id;
}
//GETTERS AND SETTERS
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Timestamp getCreateTimestamp() {
return createTimestamp;
}
public void setCreateTimestamp(Timestamp createTimestamp) {
this.createTimestamp = createTimestamp;
}
}
public class TextLog extends Log {
public TextLog(String title,String description, String content) {
super(title,description, content);
}
}
I am trying to get the values from the form and then create a Log object of type TextLog with the variables submitted in the form. Here is my Servlet:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LogsServlet
*/
//#WebServlet(description = "Loggy Logs", urlPatterns = { "/LogsServlet" })
public class LogsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LogsServlet() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//set content type
response.setContentType("text/html");
//get print writer
PrintWriter writer = response.getWriter();
//generate content
request.getParameter("logTitle");
request.getParameter("logDescription");
request.getParameter("logContent");
}
}
This is the first time I have worked with this, and I am quite lost of how to set it! I will also have to display the object in a list after and add it to a database if that makes a difference.
Any advice would be appreciated!
This is a common issue on Tomcat 10 because the change from Java EE to Jakarta EE, so you can change your project, using Jakarta EE 9
<dependency>
<groupId>jakarta.platform</groupId>
<artifactId>jakarta.jakartaee-api</artifactId>
<version>9.0.0</version>
<scope>provided</scope>
</dependency>
and importing this packages
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
If you don´t want do that, you can downgrade to Tomcat 9. Don´t forget uncomment
//#WebServlet(description = "Loggy Logs", urlPatterns = { "/LogsServlet" })
For related documentation follow this link
Tomcat 10.0.4 doesn't load servlets (#WebServlet classes) with 404 error

MySql date one day split

I'm trying to do a very simple java web app which allows to informations of a person: fristname, surname, date of birth and store them in a MySql db.
The issue is that when I try to insert a date(e.g.07/03/2019), on db the date is one day before(06/03/2019).
How is it possible to fix that?
Below the code:
The bean
package bean;
import java.io.Serializable;
import java.sql.Date;
public class Persona implements Serializable {
private int idPersona;
private String nome;
private String cognome;
private Date dataNascita;
public Persona() {
super();
}
public Persona(String nome, String cognome, Date dataNascita) {
super();
this.nome = nome;
this.cognome = cognome;
this.dataNascita = dataNascita;
}
public Persona(int idPersona, String nome, String cognome, Date dataNascita)
{
super();
this.idPersona = idPersona;
this.nome = nome;
this.cognome = cognome;
this.dataNascita = dataNascita;
}
public int getIdPersona() {
return idPersona;
}
public void setIdPersona(int idPersona) {
this.idPersona = idPersona;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public Date getDataNascita() {
return dataNascita;
}
public void setDataNascita(Date dataNascita) {
this.dataNascita = dataNascita;
}
}
The servlet
package servlet;
import java.io.IOException;
import java.sql.Date;
import java.sql.SQLException;
import java.text.ParseException;
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 bean.Persona;
import dao.ProvaDao;
import utility.ManipolazioneDate;
#WebServlet("/Inserimento")
public class Inserimento extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public Inserimento() {
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String nome = request.getParameter("nome");
String cognome = request.getParameter("cognome");
String dataNascita = request.getParameter("dataNascita");
Date dataN = null;
try {
dataN = (Date) ManipolazioneDate.convertiData(dataNascita);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Persona p = new Persona(nome, cognome, dataN);
System.out.println(p.getNome());
System.out.println(p.getCognome());
System.out.println(p.getDataNascita());
try{
ProvaDao.registraPersona(p);
}catch(SQLException e){
e.printStackTrace();
}
}
}
A class with a static method to parse a String date format into a java.sql.Date format
package utility;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ManipolazioneDate {
public static Date convertiData(String data) throws ParseException{
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date parser = format.parse(data);
java.sql.Date dataSql = new java.sql.Date(parser.getTime());
return dataSql;
}
}
Dao
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import bean.Persona;
import utility.Connessione;
public class ProvaDao {
public static void registraPersona(Persona persona) throws SQLException{
Connection conn = Connessione.getConnection();
PreparedStatement ps = null;
String ins = "insert into prova2.persona(nome, cognome, dataNascita)
values(?,?,?)";
try{
ps = conn.prepareStatement(ins);
ps.setString(1, persona.getNome());
ps.setString(2, persona.getCognome());
ps.setDate(3, persona.getDataNascita());
ps.executeUpdate();
System.out.println("Persona inserita");
}catch(SQLException e){
System.out.println(e.getMessage());
System.out.println("Errore nell'inserimento");
}finally{
if(ps != null){
ps.close();
}
if(conn != null){
conn.close();
}
}
}
}
JSP with form
<%# 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>
<div align="center">
<form action="/Prova/Inserimento" method="get">
<p>Nome</p>
<input type="text" value="" name="nome">
<br>
<p>Cognome</p>
<input type="text" value"" name="cognome">
<br>
<p>Data di nascita</p>
<input type="text" value="" name="dataNascita">
<br>
<input type="submit" value="Invia">
</form>
</div>
</body>
</html>
Thank you.
Maybe code is not wrong. (Because code does not manipulate datetime.)
At java code, do SELECT CURRENT_TIMESTAMP; get and check the timestamp. If the timestamp is wrong, it is due to MySQL server.

something wrong with Beanutils in servlet

When I use Beanutils in a servlet, I find that this doesn't work
package servlet.web15;
import org.apache.commons.beanutils.BeanUtils; 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 java.io.IOException;
import java.io.PrintWriter; import
java.lang.reflect.InvocationTargetException; import java.util.HashMap;
import java.util.Map;
#WebServlet(name = "RegisterServlet", urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter responseWriter = response.getWriter();
Map<String, String[]> parameterMap = request.getParameterMap();
for (Map.Entry<String, String[]> entry :
parameterMap.entrySet()) {
String name = entry.getKey();
for (String str :
entry.getValue()) {
responseWriter.println(name + ": " + str);
}
}
Bean bean = new Bean();
responseWriter.println(bean.toString());
try {
BeanUtils.populate(bean, parameterMap);
} catch (IllegalAccessException e) {
responseWriter.println(e.getCause());
} catch (InvocationTargetException e) {
responseWriter.println(e.getCause());
}
responseWriter.println(bean.toString()); // this statement doesn't work, something wrong with the try and catch
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
and the html snippet is like this
<div class="form form-signup">
<form action="/register" method="post">
<lable>FULL NMAE</lable>
<input type="text"
placeholder="Your full name" name="name">
<lable>E-MAIL</lable>
<input type="email"
placeholder="Your e-mail" name="email">
<lable>PASSWORD</lable>
<input type="password"
placeholder="Your password" name="password">
<p class="terms">
<input type="checkbox">
I agree all statments in
terms of service
</p>
<input type="submit"
class="form-btn"
value="Sign Up"/>
I'm already member
</form>
</div>
this is Bean.class
package servlet.web15;
public class Bean {
private String name;
private String email;
private String password;
public Bean() {
}
public Bean(String name, String email, String password) {
this.name = name;
this.email = email;
this.password = password;
}
#Override
public String toString() {
return "Bean{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", password='" + password + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
so I try to find something help, and then , I was told this is a bug in this.
So I did it according to the contents of the link, I modified the contents of the plugin folder, but this does not work, and my idea was broken up.
how do i fix this problem?
Tomcat version: 9.0.12
ps: the error message was same as that link. it like
11-Apr-2017 18:20:06.973 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deploying web application directory C:\servers\apache-tomcat-8.5.13\webapps\manager
11-Apr-2017 18:20:07.084 INFO [localhost-startStop-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory C:\servers\apache-tomcat-8.5.13\webapps\manager has finished in 112 ms

How to redirect user to an error page from login control upon entering wrong username and/or password?

I created a login form, and when I log in using a correct username and password it works fine.
I want to pop up an error message or error page when I enter a wrong username or password.
That means the controller will compare the given username with all the usernames in the database and if the given username is not found, an error message or error page should be displayed.
How can I do this with HTML or JavaScript? Is there a way to create a simple error message in the servlet? but I need to reload the page again.
<html>
<body>
<form action="search" onsubmit="return validateForm()">
<table>
<tr><td>Username</td>
<td><input type=text name=LoginId /></td>
</tr>
<tr><td>Password</td>
<td><input type=password name=LoginPassword /> </td>
</tr>
<tr>
<td colspan=2>
<center>
<input type=submit value=SignIn /><br>If you forgot your password, Reset your password.
</center>
</td>
</tr>
</table>
</form>
</body>
</html>
SearchServlet.java
/**
* #see HttpServlet#HttpServlet()
*/
public SearchServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
CustomerDAO customerDAO = new CustomerDAO();
String username = request.getParameter("LoginId");
String password = request.getParameter("LoginPassword");
Login login = customerDAO.getLoginByName(username, password);
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<center><h1>User Information</h1></center>");
out.println("<center><table border=0x>");
out.println("<tr>");
out.println("<td>Login Id : </td><td>"+login.getLoginId()+"</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>City : </td><td>"+login.getCity()+"</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>State : </td><td>"+login.getState()+"</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>Cell Number : </td><td>"+login.getCellnumber()+"</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>Email :</td><td>"+login.getEmail()+"</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>Address :</td><td>"+login.getAddress()+"</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>ZipCode : </td><td>"+login.getZipcode()+"</td>");
out.println("</tr>");
out.println("</table></center>");
out.println("<p>If these details are correct press continue or to change your information press update.</p>");
out.println("<form action='Continue.jsp'>");
out.println("<center><input type=submit value=continue></center>");
out.println("</form>");
out.println("<form action='search'>");
out.println("<center> update </center>");
out.println("</form>");
out.println("</body></html>");
Login l = new Login();
l.setLoginId(request.getParameter("LoginId"));
if(l!=null) {
HttpSession session = request.getSession();
session.setAttribute("l", l);
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
CustomerDAO.java
public class CustomerDAO extends BaseDAO{
public Login getLoginByName(String username, String password) {
Login login = null;
try {
BaseDAO baseDAO = new BaseDAO();
Connection c =baseDAO.getConnection();
// String query = "select * from test.Login where LoginId=? && LoginPassword=?";
String query = "select * from test.Customer where LoginId=? && LoginPassword=?";
PreparedStatement ps = c.prepareStatement(query);
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
login = new Login();
login.setLoginId(rs.getString("LoginId"));
login.setCity(rs.getString("City"));
login.setState(rs.getString("State"));
login.setCellnumber(rs.getString("PhoneNumber"));
login.setEmail(rs.getString("Email"));
login.setAddress(rs.getString("Address"));
login.setZipcode(rs.getInt("ZipCode"));
System.out.println();
}
c.close();
}catch(Exception e) {
System.err.println("Username or Password you enterd is incorrect.");
}
return login;
}
Login.java
package com.dao;
public class Login {
String LoginId;
String password;
String confirmpassword;
String city;
String state;
String cellnumber;
int zipcode;
String Email;
String Address;
public Login() {
// TODO Auto-generated constructor stub
}
public String getLoginId() {
return LoginId;
}
public void setLoginId(String loginId) {
LoginId = loginId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmpassword() {
return confirmpassword;
}
public void setConfirmpassword(String confirmpassword) {
this.confirmpassword = confirmpassword;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCellnumber() {
return cellnumber;
}
public void setCellnumber(String cellnumber) {
this.cellnumber = cellnumber;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
public void setEmail(String email) {
Email = email;
}
public String getEmail() {
return Email;
}
public void setAddress(String address) {
Address = address;
}
public String getAddress() {
return Address;
}
}
after this :
PrintWriter out = response.getWriter();
add ->
if (login == null){
out.println("<html><body>");
out.println("<center><h1>Login failed, wrong username or password</h1></center>");
out.println("</body>");
out.println("<script type='text/javascript'>");
out.println("function reload() {");
out.println("setTimeout(function(){");
out.println("window.location = '"+request.getContextPath()+"/search';}");
out.println("}, 5000);");
out.println("reload();");
out.println("</script>");
out.println("</html>");
}
}
but that is a bad way to do authentication, you will have to write your own authorization filters, and thats a lot of redudant code, instead of this use web containers authentication mechanism see securing web app
it's easy to override, can add custom login, add softlogin, roles, and stuff like this.

Categories