SlideShare une entreprise Scribd logo
1  sur  10
package model.bo;
import
import
import
import

java.sql.SQLException;
java.util.ArrayList;
model.bean.Account;
model.dao.ShowUserDAO;

public class CheckLoginBO {
private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-+]+(.[_A-Zaz0-9-]+)*@"
+ "[A-Za-z0-9-]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})$";
public boolean isValidAccount(String account, String firstName,
String lastName, String email) {
//check vaild input
boolean vaildMail =email.matches(EMAIL_PATTERN);
if ((account == null || "".equals(account))
|| (firstName == null || "".equals(firstName))
|| (lastName == null || "".equals(lastName))
|| (email == null|| "".equals(email)) || !vaildMail) {
return false;
}
else {
return true;
}
}
public ArrayList<Account> getAccountDetail() throws SQLException {
ArrayList<Account> listAccount = new ArrayList<Account>();
ShowUserDAO showUserDAO = new ShowUserDAO();
listAccount = showUserDAO.getAllUser();
return listAccount;
}
/**
* CheckDulication user
* @param account
* @return
*/
public boolean checkDulication(String account) {
// TODO Auto-generated method stub
return false;
}
}
=====================================================
<%@page import="model.bean.Account"%>
<%@page import="java.util.ArrayList"%>
<%@ 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>
<%
ArrayList<Account> accountList = new ArrayList<Account>();
Account accounts = new Account();
String account = request.getParameter("account");
String fistName = request.getParameter("fistName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
session.setAttribute("account",account);
session.setAttribute("fistName",fistName);
session.setAttribute("lastName",lastName);
session.setAttribute("email",email);
accountList = (ArrayList<Account>) request.getAttribute("accList");
%>
<table>
<tr>
<th>account</th>
<th>firstName</th>
<th>lastName</th>
<th>email</th>
</tr>
<tr>
<td><%=account%></td>
<td><%=fistName%></td>
<td><%=lastName%></td>
<td><%=email%></td>
</tr>
</table>
<br>
<table>
<tr>

</tr>
<%

<th>account</th>
<th>firstName</th>
<th>lastName</th>
<th>email</th>
for (Account accc : accountList) {

%>
<tr>
<td><%=accc.getAccount()%></td>
<td><%=accc.getFistName()%></td>
<td><%=accc.getLastName()%></td>
<td><%=accc.getEmail()%></td>
</tr>
<%
}
%>
</table>
<br>
<%
String returnPage = "Login.jsp";
%>
<input type="button" value="Change"
onClick="javascript:window.location='<%=returnPage%>';">
<%
String updatePage = "UpdateServlet";
%>
<input type="button" value="Save"
onClick="javascript:window.location='<%=updatePage%>';">
</body>
</html>
=============================================================================
<%@ 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>
<form action="CheckAccountLoginServlet" method="post">
<H2 >Input your information</H2>
<table>
<tr>
<td>Account</td>
<td><Input type="text" id="account" name="account"
/></td>
</tr>
<tr>
<td>First name</td>
<td><Input type="text" id="firstName" name="fistName"
/></td>
</tr>
<tr>
<td>Last name</td>
<td><Input type="text" id="lastName" name="lastName"
/></td>
</tr>
<tr>
<td>Email</td>
<td><Input type="text" id="email" name="email" /></td>
</tr>
<tr>
<td style="text-align:center" colspan="2">
<Input type="submit" value="Submit" />
<Input type="reset" value="Reset" />
</td>
</tr>
</table>
</form>
</body>
</html>
================================================================================
========
package model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class UpdateDAO {
public void update(String account, String fistName, String lastName,
String email) {
Connection con = null;
PreparedStatement ps = null;
GetConnectionDAO connectionDAO = new GetConnectionDAO();
String query = "update account set fist_name=?,last_name=?,email=?
where useraccount =?";
try {
con = connectionDAO.getConnection();
ps = con.prepareStatement(query);
ps.setString(1, "fist_name");
ps.setString(2, "last_name");
ps.setString(3, "email");
ps.setString(4, "useraccount");
ps.executeUpdate();
ps.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("Not Update!

");

}
}
}
================================================================================
========================
package model.dao;
import
import
import
import
import

java.sql.Connection;
java.sql.PreparedStatement;
java.sql.ResultSet;
java.sql.SQLException;
java.util.ArrayList;

import com.sun.org.apache.regexp.internal.recompile;
import com.sun.xml.internal.ws.api.pipe.NextAction;
import model.bean.Account;
public class ShowUserDAO {
static GetConnectionDAO getConnectionDAO = new GetConnectionDAO();
/**
*
* @return List Account
* @throws SQLException
*/
public ArrayList<Account> getAllUser() throws SQLException {
ArrayList<Account> accounts = new ArrayList<Account>();
String query = "SELECT useraccount,fist_name,last_name,email FROM
account";
Connection con = null;
PreparedStatement ps = null;
ResultSet set = null;
try {
con = getConnectionDAO.getConnection();
System.out.println(con);
ps = con.prepareStatement(query);
set = ps.executeQuery();
while (set.next()) {
Account account = new Account();
account.setAccount(set.getString("useraccount"));
account.setFistName(set.getString("fist_name"));
account.setLastName(set.getString("last_name"));
account.setEmail(set.getString("email"));
accounts.add(account);
//TODO Xem Lai-->
}
ps.close();
set.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
}
return accounts;
}
public boolean duplicateCheck(String account){
Connection con = null;
PreparedStatement ps = null;
ResultSet set = null;
String query ="SELECT useraccount FROM account ";
boolean check = false;
try {
con = getConnectionDAO.getConnection();
ps = con.prepareStatement(query);
set = ps.executeQuery();
while (set.next()) {
if(set.getString("useraccount").equals(account)){
check = true;
break;
}else{
check = false;
}
}
set.close();
ps.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
return check;
}
}
================================================================================
=============
package model.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class InsertDAO {
public void insert(String account, String fistName, String lastName,
String email) {
Connection con = null;
PreparedStatement ps = null;
String query = "insert into account(useraccount,
fist_name,last_name,email) values (?,?,?,?)";
try {
GetConnectionDAO connectionDAO = new GetConnectionDAO();
con = connectionDAO.getConnection();
ps = con.prepareStatement(query);
ps.setString(1, account);
ps.setString(2, fistName);
ps.setString(3, lastName);
ps.setString(4, email);
ps.executeUpdate();
System.out.println("Insert .....");
ps.close();
con.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
=======================================================================
package model.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class GetConnectionDAO {
public Connection getConnection(){
Connection con = null;
try{
Class.forName("com.mysql.jdbc.Driver");
if(con == null || con.isClosed()){
String ulr ="jdbc:mysql://localhost:3306/TRANEES";
con = DriverManager.getConnection(ulr,"root","1234");
}
}catch(SQLException e){
e.printStackTrace();
}
catch(Exception e){
System.out.println("ket noi ko duoc");
e.printStackTrace();
}
return con;
}
}
===============================================================================
package model.bean;
public class Account {
private String account;
private String fistName;
private String lastName;
private String email;
public Account() {
// TODO Auto-generated constructor stub
}
public Account(String account,String fistName,String lastName,String
email) {
this.account = account;
this.fistName =fistName;
this.lastName =lastName;
this.email = email;
}

}

public String getAccount() {
return account;
public void setAccount(String account) {
this.account = account;
}
}

public String getFistName() {
return fistName;
public void setFistName(String fistName) {
this.fistName = fistName;

}
}

public String getLastName() {
return lastName;
public void setLastName(String lastName) {
this.lastName = lastName;

}
}

public String getEmail() {
return email;
public void setEmail(String email) {
this.email = email;

}
}
=================================================================
package controller;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import
import
import
import
import

javax.servlet.RequestDispatcher;
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;

import
import
import
import

model.bean.Account;
model.bo.CheckLoginBO;
model.dao.InsertDAO;
model.dao.UpdateDAO;

/**
* Servlet implementation class UpdateServlet
*/
public class UpdateServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public UpdateServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
*
response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
*
response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {

String
String
String
String

account = request.getParameter("account");
fistName = request.getParameter("fistName");
lastName = request.getParameter("lastName");
email = request.getParameter("email");

request.setAttribute("account", account);
request.setAttribute("fistName", fistName);
request.setAttribute("lastName", lastName);
request.setAttribute("email", email);
System.out.println(account +fistName+lastName+email);
UpdateDAO updateDAO = new UpdateDAO();
InsertDAO insertDAO = new InsertDAO();
CheckLoginBO checkLoginBO = new CheckLoginBO();
RequestDispatcher rd =
request.getRequestDispatcher("ShowTranees.jsp");
ArrayList<Account> accList = new ArrayList<Account>();
if (checkLoginBO.checkDulication(account)) {
//update
updateDAO.update(account, fistName, lastName, email);
try {
accList = checkLoginBO.getAccountDetail();
} catch (SQLException e) {
System.out.println("Get Db Fail!");
e.printStackTrace();
}
request.setAttribute("accList", accList);
rd.forward(request, response);
System.out.println("Updated !!!!!!");
} else {
//insert
insertDAO.insert(account, fistName, lastName, email);
try {
accList = checkLoginBO.getAccountDetail();
} catch (SQLException e) {
System.out.println("Get Db Fail!");
e.printStackTrace();
}
request.setAttribute("accList", accList);
rd.forward(request, response);
System.out.println("Inserted !!!!1");
}
}
}
=============================================================================
package controller;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import
import
import
import
import

javax.servlet.RequestDispatcher;
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;

import model.bean.Account;
import model.bo.CheckLoginBO;
/**
* Servlet implementation class CheckLoginServlet
*/
public class CheckAccountLoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public CheckAccountLoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String account = request.getParameter("account");
String fistName = request.getParameter("fistName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
ArrayList<Account> accList = new ArrayList<Account>();
CheckLoginBO checkLoginBO = new CheckLoginBO();
{

if (checkLoginBO.isValidAccount(account, fistName, lastName, email))
try {

checkLoginBO.getAccountDetail();

accList =

} catch (SQLException e) {
System.out.println("Get Db Fail!");
e.printStackTrace();
}

request.setAttribute("account", account);
request.setAttribute("fistName", fistName);
request.setAttribute("lastName", lastName);
request.setAttribute("email", email);
request.setAttribute("accList", accList);
RequestDispatcher rd =
request.getRequestDispatcher("ShowTranees.jsp");
rd.forward(request, response);
} else {
response.sendRedirect("Login.jsp");
}
}
}

Contenu connexe

Tendances

Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)진성 오
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012Sandeep Joshi
 
exportDisabledUsersRemoveMailbox
exportDisabledUsersRemoveMailboxexportDisabledUsersRemoveMailbox
exportDisabledUsersRemoveMailboxDaniel Gilhousen
 
Android Testing
Android TestingAndroid Testing
Android TestingEvan Lin
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2eugenio pombi
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoThe Software House
 
Dealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsDealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsClinton Dreisbach
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Leonardo Soto
 
Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17LogeekNightUkraine
 
Let the type system be your friend
Let the type system be your friendLet the type system be your friend
Let the type system be your friendThe Software House
 
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVERINSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVERDarwin Durand
 
Devoxx 2012 hibernate envers
Devoxx 2012   hibernate enversDevoxx 2012   hibernate envers
Devoxx 2012 hibernate enversRomain Linsolas
 

Tendances (19)

Writing Good Tests
Writing Good TestsWriting Good Tests
Writing Good Tests
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
exportDisabledUsersRemoveMailbox
exportDisabledUsersRemoveMailboxexportDisabledUsersRemoveMailbox
exportDisabledUsersRemoveMailbox
 
Lucene
LuceneLucene
Lucene
 
Specs2
Specs2Specs2
Specs2
 
Android Testing
Android TestingAndroid Testing
Android Testing
 
PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2PHPUnit elevato alla Symfony2
PHPUnit elevato alla Symfony2
 
Developer Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duoDeveloper Experience i TypeScript. Najbardziej ikoniczne duo
Developer Experience i TypeScript. Najbardziej ikoniczne duo
 
SOLID Principles
SOLID PrinciplesSOLID Principles
SOLID Principles
 
Dealing with Legacy PHP Applications
Dealing with Legacy PHP ApplicationsDealing with Legacy PHP Applications
Dealing with Legacy PHP Applications
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)Jython: Python para la plataforma Java (EL2009)
Jython: Python para la plataforma Java (EL2009)
 
PureScript & Pux
PureScript & PuxPureScript & Pux
PureScript & Pux
 
Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17Alexey Tsoy Meta Programming in C++ 16.11.17
Alexey Tsoy Meta Programming in C++ 16.11.17
 
Let the type system be your friend
Let the type system be your friendLet the type system be your friend
Let the type system be your friend
 
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVERINSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
INSERCION DE REGISTROS DESDE VISUAL.NET A UNA BD DE SQL SERVER
 
Fp java8
Fp java8Fp java8
Fp java8
 
Devoxx 2012 hibernate envers
Devoxx 2012   hibernate enversDevoxx 2012   hibernate envers
Devoxx 2012 hibernate envers
 

Similaire à Java day9n

PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsGuilherme Blanco
 
Modul Praktek Java OOP
Modul Praktek Java OOP Modul Praktek Java OOP
Modul Praktek Java OOP Zaenal Arifin
 
TestFest - Respect\Validation 1.0
TestFest - Respect\Validation 1.0TestFest - Respect\Validation 1.0
TestFest - Respect\Validation 1.0Henrique Moody
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB jhchabran
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHPGuilherme Blanco
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosDivante
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShellGaetano Causio
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologyDaniel Knell
 
Ex[1].3 php db connectivity
Ex[1].3 php db connectivityEx[1].3 php db connectivity
Ex[1].3 php db connectivityMouli Chandira
 
Get better at Refactoring (Voxxed Days)
Get better at Refactoring (Voxxed Days)Get better at Refactoring (Voxxed Days)
Get better at Refactoring (Voxxed Days)Stanly Lau
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wildJoe Morgan
 
Scala Quick Introduction
Scala Quick IntroductionScala Quick Introduction
Scala Quick IntroductionDamian Jureczko
 
Get better at Refactoring | Stanly Lau
Get better at Refactoring | Stanly LauGet better at Refactoring | Stanly Lau
Get better at Refactoring | Stanly LauAgileTour@TW
 
Get better at Refactoring
Get better at RefactoringGet better at Refactoring
Get better at RefactoringStanly Lau
 

Similaire à Java day9n (20)

Week 12 code
Week 12 codeWeek 12 code
Week 12 code
 
PHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object CalisthenicsPHP for Adults: Clean Code and Object Calisthenics
PHP for Adults: Clean Code and Object Calisthenics
 
Zero to SOLID
Zero to SOLIDZero to SOLID
Zero to SOLID
 
Modul Praktek Java OOP
Modul Praktek Java OOP Modul Praktek Java OOP
Modul Praktek Java OOP
 
TestFest - Respect\Validation 1.0
TestFest - Respect\Validation 1.0TestFest - Respect\Validation 1.0
TestFest - Respect\Validation 1.0
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Why is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenariosWhy is crud a bad idea - focus on real scenarios
Why is crud a bad idea - focus on real scenarios
 
Everything About PowerShell
Everything About PowerShellEverything About PowerShell
Everything About PowerShell
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Ex[1].3 php db connectivity
Ex[1].3 php db connectivityEx[1].3 php db connectivity
Ex[1].3 php db connectivity
 
Get better at Refactoring (Voxxed Days)
Get better at Refactoring (Voxxed Days)Get better at Refactoring (Voxxed Days)
Get better at Refactoring (Voxxed Days)
 
ddd+scala
ddd+scaladdd+scala
ddd+scala
 
ES6 patterns in the wild
ES6 patterns in the wildES6 patterns in the wild
ES6 patterns in the wild
 
Scala Quick Introduction
Scala Quick IntroductionScala Quick Introduction
Scala Quick Introduction
 
Get better at Refactoring | Stanly Lau
Get better at Refactoring | Stanly LauGet better at Refactoring | Stanly Lau
Get better at Refactoring | Stanly Lau
 
Get better at Refactoring
Get better at RefactoringGet better at Refactoring
Get better at Refactoring
 

Plus de vacbalolenvadi90 (7)

Quiz test JDBC
Quiz test JDBCQuiz test JDBC
Quiz test JDBC
 
Ass2 1 (2)
Ass2 1 (2)Ass2 1 (2)
Ass2 1 (2)
 
Bai day1
Bai day1Bai day1
Bai day1
 
Final
FinalFinal
Final
 
sqlKey
sqlKeysqlKey
sqlKey
 
Abcxyz
AbcxyzAbcxyz
Abcxyz
 
SQL DdaHKH Huế
SQL DdaHKH HuếSQL DdaHKH Huế
SQL DdaHKH Huế
 

Dernier

Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Bhuvaneswari Subramani
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 

Dernier (20)

Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 

Java day9n

  • 1. package model.bo; import import import import java.sql.SQLException; java.util.ArrayList; model.bean.Account; model.dao.ShowUserDAO; public class CheckLoginBO { private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-+]+(.[_A-Zaz0-9-]+)*@" + "[A-Za-z0-9-]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})$"; public boolean isValidAccount(String account, String firstName, String lastName, String email) { //check vaild input boolean vaildMail =email.matches(EMAIL_PATTERN); if ((account == null || "".equals(account)) || (firstName == null || "".equals(firstName)) || (lastName == null || "".equals(lastName)) || (email == null|| "".equals(email)) || !vaildMail) { return false; } else { return true; } } public ArrayList<Account> getAccountDetail() throws SQLException { ArrayList<Account> listAccount = new ArrayList<Account>(); ShowUserDAO showUserDAO = new ShowUserDAO(); listAccount = showUserDAO.getAllUser(); return listAccount; } /** * CheckDulication user * @param account * @return */ public boolean checkDulication(String account) { // TODO Auto-generated method stub return false; } } ===================================================== <%@page import="model.bean.Account"%> <%@page import="java.util.ArrayList"%> <%@ 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> <% ArrayList<Account> accountList = new ArrayList<Account>(); Account accounts = new Account(); String account = request.getParameter("account");
  • 2. String fistName = request.getParameter("fistName"); String lastName = request.getParameter("lastName"); String email = request.getParameter("email"); session.setAttribute("account",account); session.setAttribute("fistName",fistName); session.setAttribute("lastName",lastName); session.setAttribute("email",email); accountList = (ArrayList<Account>) request.getAttribute("accList"); %> <table> <tr> <th>account</th> <th>firstName</th> <th>lastName</th> <th>email</th> </tr> <tr> <td><%=account%></td> <td><%=fistName%></td> <td><%=lastName%></td> <td><%=email%></td> </tr> </table> <br> <table> <tr> </tr> <% <th>account</th> <th>firstName</th> <th>lastName</th> <th>email</th> for (Account accc : accountList) { %> <tr> <td><%=accc.getAccount()%></td> <td><%=accc.getFistName()%></td> <td><%=accc.getLastName()%></td> <td><%=accc.getEmail()%></td> </tr> <% } %> </table> <br> <% String returnPage = "Login.jsp"; %> <input type="button" value="Change" onClick="javascript:window.location='<%=returnPage%>';"> <% String updatePage = "UpdateServlet"; %> <input type="button" value="Save" onClick="javascript:window.location='<%=updatePage%>';"> </body> </html> ============================================================================= <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  • 3. 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> <form action="CheckAccountLoginServlet" method="post"> <H2 >Input your information</H2> <table> <tr> <td>Account</td> <td><Input type="text" id="account" name="account" /></td> </tr> <tr> <td>First name</td> <td><Input type="text" id="firstName" name="fistName" /></td> </tr> <tr> <td>Last name</td> <td><Input type="text" id="lastName" name="lastName" /></td> </tr> <tr> <td>Email</td> <td><Input type="text" id="email" name="email" /></td> </tr> <tr> <td style="text-align:center" colspan="2"> <Input type="submit" value="Submit" /> <Input type="reset" value="Reset" /> </td> </tr> </table> </form> </body> </html> ================================================================================ ======== package model.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class UpdateDAO { public void update(String account, String fistName, String lastName, String email) { Connection con = null; PreparedStatement ps = null; GetConnectionDAO connectionDAO = new GetConnectionDAO(); String query = "update account set fist_name=?,last_name=?,email=? where useraccount =?"; try { con = connectionDAO.getConnection(); ps = con.prepareStatement(query); ps.setString(1, "fist_name"); ps.setString(2, "last_name");
  • 4. ps.setString(3, "email"); ps.setString(4, "useraccount"); ps.executeUpdate(); ps.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { System.out.println("Not Update! "); } } } ================================================================================ ======================== package model.dao; import import import import import java.sql.Connection; java.sql.PreparedStatement; java.sql.ResultSet; java.sql.SQLException; java.util.ArrayList; import com.sun.org.apache.regexp.internal.recompile; import com.sun.xml.internal.ws.api.pipe.NextAction; import model.bean.Account; public class ShowUserDAO { static GetConnectionDAO getConnectionDAO = new GetConnectionDAO(); /** * * @return List Account * @throws SQLException */ public ArrayList<Account> getAllUser() throws SQLException { ArrayList<Account> accounts = new ArrayList<Account>(); String query = "SELECT useraccount,fist_name,last_name,email FROM account"; Connection con = null; PreparedStatement ps = null; ResultSet set = null; try { con = getConnectionDAO.getConnection(); System.out.println(con); ps = con.prepareStatement(query); set = ps.executeQuery(); while (set.next()) { Account account = new Account(); account.setAccount(set.getString("useraccount")); account.setFistName(set.getString("fist_name")); account.setLastName(set.getString("last_name")); account.setEmail(set.getString("email")); accounts.add(account); //TODO Xem Lai--> } ps.close(); set.close(); con.close();
  • 5. } catch (SQLException e) { e.printStackTrace(); } finally { } return accounts; } public boolean duplicateCheck(String account){ Connection con = null; PreparedStatement ps = null; ResultSet set = null; String query ="SELECT useraccount FROM account "; boolean check = false; try { con = getConnectionDAO.getConnection(); ps = con.prepareStatement(query); set = ps.executeQuery(); while (set.next()) { if(set.getString("useraccount").equals(account)){ check = true; break; }else{ check = false; } } set.close(); ps.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } return check; } } ================================================================================ ============= package model.dao; import java.sql.Connection; import java.sql.PreparedStatement; public class InsertDAO { public void insert(String account, String fistName, String lastName, String email) { Connection con = null; PreparedStatement ps = null; String query = "insert into account(useraccount, fist_name,last_name,email) values (?,?,?,?)"; try { GetConnectionDAO connectionDAO = new GetConnectionDAO(); con = connectionDAO.getConnection(); ps = con.prepareStatement(query); ps.setString(1, account); ps.setString(2, fistName); ps.setString(3, lastName); ps.setString(4, email); ps.executeUpdate(); System.out.println("Insert .....");
  • 6. ps.close(); con.close(); } catch (Exception e) { // TODO: handle exception } } } ======================================================================= package model.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class GetConnectionDAO { public Connection getConnection(){ Connection con = null; try{ Class.forName("com.mysql.jdbc.Driver"); if(con == null || con.isClosed()){ String ulr ="jdbc:mysql://localhost:3306/TRANEES"; con = DriverManager.getConnection(ulr,"root","1234"); } }catch(SQLException e){ e.printStackTrace(); } catch(Exception e){ System.out.println("ket noi ko duoc"); e.printStackTrace(); } return con; } } =============================================================================== package model.bean; public class Account { private String account; private String fistName; private String lastName; private String email; public Account() { // TODO Auto-generated constructor stub } public Account(String account,String fistName,String lastName,String email) { this.account = account; this.fistName =fistName; this.lastName =lastName; this.email = email; } } public String getAccount() { return account;
  • 7. public void setAccount(String account) { this.account = account; } } public String getFistName() { return fistName; public void setFistName(String fistName) { this.fistName = fistName; } } public String getLastName() { return lastName; public void setLastName(String lastName) { this.lastName = lastName; } } public String getEmail() { return email; public void setEmail(String email) { this.email = email; } } ================================================================= package controller; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import import import import import javax.servlet.RequestDispatcher; javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; import import import import model.bean.Account; model.bo.CheckLoginBO; model.dao.InsertDAO; model.dao.UpdateDAO; /** * Servlet implementation class UpdateServlet */ public class UpdateServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public UpdateServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response);
  • 8. } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String String String String account = request.getParameter("account"); fistName = request.getParameter("fistName"); lastName = request.getParameter("lastName"); email = request.getParameter("email"); request.setAttribute("account", account); request.setAttribute("fistName", fistName); request.setAttribute("lastName", lastName); request.setAttribute("email", email); System.out.println(account +fistName+lastName+email); UpdateDAO updateDAO = new UpdateDAO(); InsertDAO insertDAO = new InsertDAO(); CheckLoginBO checkLoginBO = new CheckLoginBO(); RequestDispatcher rd = request.getRequestDispatcher("ShowTranees.jsp"); ArrayList<Account> accList = new ArrayList<Account>(); if (checkLoginBO.checkDulication(account)) { //update updateDAO.update(account, fistName, lastName, email); try { accList = checkLoginBO.getAccountDetail(); } catch (SQLException e) { System.out.println("Get Db Fail!"); e.printStackTrace(); } request.setAttribute("accList", accList); rd.forward(request, response); System.out.println("Updated !!!!!!"); } else { //insert insertDAO.insert(account, fistName, lastName, email); try { accList = checkLoginBO.getAccountDetail(); } catch (SQLException e) { System.out.println("Get Db Fail!"); e.printStackTrace(); } request.setAttribute("accList", accList); rd.forward(request, response); System.out.println("Inserted !!!!1"); } } } ============================================================================= package controller;
  • 9. import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import import import import import javax.servlet.RequestDispatcher; javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; import model.bean.Account; import model.bo.CheckLoginBO; /** * Servlet implementation class CheckLoginServlet */ public class CheckAccountLoginServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public CheckAccountLoginServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String account = request.getParameter("account"); String fistName = request.getParameter("fistName"); String lastName = request.getParameter("lastName"); String email = request.getParameter("email"); ArrayList<Account> accList = new ArrayList<Account>(); CheckLoginBO checkLoginBO = new CheckLoginBO(); { if (checkLoginBO.isValidAccount(account, fistName, lastName, email)) try { checkLoginBO.getAccountDetail(); accList = } catch (SQLException e) { System.out.println("Get Db Fail!"); e.printStackTrace(); } request.setAttribute("account", account); request.setAttribute("fistName", fistName); request.setAttribute("lastName", lastName); request.setAttribute("email", email);
  • 10. request.setAttribute("accList", accList); RequestDispatcher rd = request.getRequestDispatcher("ShowTranees.jsp"); rd.forward(request, response); } else { response.sendRedirect("Login.jsp"); } } }