一、代碼的分層
1、概述
????????一個好的層次劃分不僅可以能使代碼結(jié)構(gòu)更加清楚,還可以使項(xiàng)目分工更加明確,可讀性大大提升,跟回家有利于后期的維護(hù)和升級。從另一個角度來看,好的代碼分層架構(gòu),應(yīng)該使可以很好的匹配上單一職責(zé)原則的。這樣就可以降低層與層之間的依賴,還能最大承兌的復(fù)用各層的邏輯。
2、分層的好處
- 高內(nèi)聚:分層的設(shè)計可以簡化系統(tǒng)設(shè)計,讓不同的層專注做某一模塊的事
- 低耦合:層與層之間通過接口或API來交互,依賴方不用知道被依賴方的細(xì)節(jié)
- 復(fù)用:分層之后可以做到很高的復(fù)用
- 擴(kuò)展性:分層架構(gòu)可以讓我們更容易做橫向擴(kuò)展
?如果系統(tǒng)沒有分層,當(dāng)業(yè)務(wù)規(guī)模增加或流量增大時我們只能針對整體系統(tǒng)來做擴(kuò)展。分層之后可以很方便的把一些模塊抽離出來,獨(dú)立成一個系統(tǒng)。
3、建包
我們需要建三個包,分別是:bean、dao、util
????????dao層(數(shù)據(jù)訪問層)這里與數(shù)據(jù)庫進(jìn)行數(shù)據(jù)的訪問,service則是業(yè)務(wù)邏輯層,與數(shù)據(jù)訪問層進(jìn)行數(shù)據(jù)的交互,而controller則是控制層對前端的請求進(jìn)行處理和響應(yīng)。
? ? ? ?bean包(實(shí)體類)里面都是實(shí)體類,更加方便的對數(shù)據(jù)進(jìn)行操作。
????????uitl包(工具包)則是對經(jīng)常用到的方法 進(jìn)行封裝。
二、首頁的編寫
在web項(xiàng)目下建一個index.jsp項(xiàng)目,用來編寫首頁
index.jsp位置所如下圖所示:
?
我在首頁設(shè)置兩個超鏈接實(shí)現(xiàn)頁面跳轉(zhuǎn),分別指向登錄頁面和注冊頁面。
如圖下所示:
?實(shí)現(xiàn)代碼如下:
<html>
<head>
<title>Java Web</title>
</head>
<body>
<a href="Login.jsp"><h2>去登錄</h2></a>
<a href="Enroll.jsp"><h2>去注冊</h2></a>
</body>
</html>
三、前端登錄頁面的編寫
在登錄頁面中我們需要用到JDBC連接數(shù)據(jù)庫進(jìn)行數(shù)據(jù)查詢操作(判斷用戶輸入的賬號密碼是否正確)
首先我們在web項(xiàng)目下建一個Login.jsp項(xiàng)目,用來編寫登錄頁面。
Login.jsp位置如下圖所示:
?登錄頁面的展示:
?實(shí)現(xiàn)登錄頁面代碼如下:
<html>
<head>
<title>登錄</title>
</head>
<style type="text/css">
.login-card {
width: 300px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
background-color: #e8e8e8;
box-shadow: 2px 2px 10px #ccc;
}
.card-header {
text-align: center;
margin-bottom: 20px
}
.card-header .log {
margin: 0;
font-size: 24px;
color: black;
}
.form-group {
margin-bottom: 15px;
}
label {
font-size: 18px;
margin-bottom: 5px;
}
input[type="text"], input[type="password"] {
width: 100%;
padding: 12px 20px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
transition: 0.5s;
}
input[type="submit"] {
width: 100%;
background-color: #333;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #ccc;
color: black;
}
</style>
<body>
<div class="login-card">
<div class="card-header">
<div class="log">登錄</div>
</div>
<form action="login" method="post">
<div class="form-group">
<label for="user">賬號:</label>
<input required="" name="user" id="user" type="text">
</div>
<div class="form-group">
<label for="pwd">密碼:</label>
<input required="" name="pwd" id="pwd" type="password">
</div>
<div class="form-group">
<input value="登錄" type="submit">
<a href="Enroll.jsp">沒有賬號?去注冊</a>
</div>
</form>
</div>
</body>
</html>
四、前端注冊頁面的編寫
在注冊頁面中我們需要用到JDBC連接數(shù)據(jù)庫進(jìn)行數(shù)據(jù)的添加操作(通過servlet獲取瀏覽器發(fā)出請求中的數(shù)據(jù)添加到數(shù)據(jù)庫中)
在實(shí)現(xiàn)添加數(shù)據(jù)之前我們先在web項(xiàng)目下建一個Enroll.jsp項(xiàng)目
Enroll.jsp位置如下圖所示:
?注冊頁面的展示:
?實(shí)現(xiàn)注冊頁面的代碼如下:
<html>
<head>
<title>注冊賬號</title>
</head>
<style type="text/css">
.login-card {
width: 300px;
margin: 0 auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
background-color: #e8e8e8;
box-shadow: 2px 2px 10px #ccc;
}
.card-header {
text-align: center;
margin-bottom: 20px
}
.card-header .log {
margin: 0;
font-size: 24px;
color: black;
}
.form-group {
margin-bottom: 15px;
}
label {
font-size: 18px;
margin-bottom: 5px;
}
input[type="text"], input[type="password"] {
width: 100%;
padding: 12px 20px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
transition: 0.5s;
}
input[type="submit"] {
width: 100%;
background-color: #333;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type="submit"]:hover {
background-color: #ccc;
color: black;
}
</style>
<body>
<div class="login-card">
<div class="card-header">
<div class="log">注冊</div>
</div>
<form action="enroll" method="post">
<div class="form-group">
<label for="zhangh">添加賬號:</label>
<input required="" name="zhangh" id="zhangh" type="text">
</div>
<div class="form-group">
<label for="pwd">設(shè)置密碼:</label>
<input required="" name="pwd" id="pwd" type="password">
</div>
<div class="form-group">
<label for="dell">添加電話:</label>
<input required="" name="dell" id="dell" type="text">
</div>
<div class="form-group">
<label for="address">添加地址:</label>
<input required="" name="address" id="address" type="text">
</div>
<div class="form-group">
<input value="注冊" type="submit">
<a href="Login.jsp">已有賬號?去注冊</a>
</div>
</form>
</div>
</body>
</html>
五、登錄成功首頁的編寫
首先我們在web項(xiàng)目下建一個ShouYe.jsp
ShouYe.jsp位置如圖下所示:
?
登錄成功首頁的展示:
實(shí)現(xiàn)代碼如下:
<html>
<head>
<meta charset="utf-8">
<title>首頁</title>
<style type="text/css">
div{
position: relative;
width: 360px;
height: 511px;
}
img{
border-radius: 5px; /* 設(shè)置圓角 */
}
p{
width: 500px;
height: 300px;
position: absolute;/* 絕對定位 */
left: 0;
top: 0;
background-color: rgba(0 ,0 ,0 , 0.709);
color: white;
padding: 10px;
display: none;/* 隱藏 */
pointer-events: none; /* 不對鼠標(biāo)事件做出反應(yīng)
}
</style>
</head>
<body>
<div id="div_1">
<img src="img/mhl.jpg" alt="">
<p>
<strong>簡介</strong>
<span>
在錢塘開茶鋪的趙盼兒驚聞未婚夫、新科談話歐陽旭要另娶當(dāng)朝高官之女,不甘命運(yùn)的她誓要上京討個公道。在途中她遇到了出自
權(quán)門但生性正直的皇城司指揮顧千帆,并卷入江南一場大案,兩人不打不相識從而結(jié)緣。趙盼兒憑借智慧解救了被騙婚而慘遭虐待的“江南第一琵琶高手”宋印章與被苛刻
家人逼得離家出走的豪爽廚娘孫三娘,三位姐妹從此結(jié)伴而行,終抵東京見識世間繁華。為了不被另攀高枝的歐陽旭從京城趕走,趙盼兒與宋引章、孫三娘一起歷盡艱辛,將小小茶坊一步步發(fā)展最大的酒樓,揭露了
負(fù)心人的真面目,收獲了各自的真摯感情和人生感悟,也為無數(shù)平凡女子推開了一扇平等救贖之門。
</span>
</p>
</div>
<script type="text/javascript">
//獲取div標(biāo)簽
var div_1=document.getElementById("div_1")
//給div_1綁定事件:onmouseover:鼠標(biāo)移入的事件
div_1.onmouseover=function(){
//將p標(biāo)簽顯示出來,故需要將display的值設(shè)置為block
document.querySelector("p").style.display="block"
}
// onmouseout:鼠標(biāo)從元素上移開時觸發(fā)的事件
div_1.onmouseout=function(){
//將p標(biāo)簽隱藏,故需要將display的值設(shè)置為none
document.querySelector("p").style.display="none"
}
//onmousemove:鼠標(biāo)在元素上移動時觸發(fā)的事件
div_1.onmousemove=function(){
document.querySelector("p").style.left=event.offsetX+"px"
document.querySelector("p").style.top=event.offsetY+"px"
}
</script>
</body>
</html>
六、異常頁面的編寫
我們在web項(xiàng)目下建一個Error.jsp
Error.jsp位置如圖下所示:
?出錯頁面的展示:
實(shí)現(xiàn)出錯頁面的代碼如下:
<html>
<head>
<title>404</title>
</head>
<body>
<H2>出錯了</H2>
<a href="Login.jsp">返回登錄界面</a>
</body>
</html>
七、web.xml配置Servlet類
<!--配置Servlet類-->
<servlet>
<!-- 起別名 -->
<servlet-name>login</servlet-name>
<!-- servlet類所在的位置:類的全類名就是 包名.類名 -->
<servlet-class>com.hp.Servlet.Login</servlet-class>
</servlet>
<!-- Servlet類的映射:Servlet用來處理哪個請求 -->
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
八、在bean包下建立一個user實(shí)體類
建立user實(shí)體類的位置:
?user實(shí)體類中的代碼如下:
public class User {
private Integer uid;
private String username;
private String password;
private String phone;
private String address;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"uid=" + uid +
", username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", address='" + address + '\'' +
'}';
}
}
九、在Util包下實(shí)現(xiàn)JDBC連接方法
在Util包下建一個JDBCUtil類
JDBCUtil類位置如下:
?JDBCUtil類中實(shí)現(xiàn) 獲取連接 和 關(guān)閉資源 的代碼如下:
public class JDBCUtil {
private static String driver = "com.mysql.cj.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC";
private static String user = "root";
private static String pwd = "123456";
private static Connection con = null;
//測試
public static void main(String[] args) {
System.out.println(getCon());
}
//獲取數(shù)據(jù)庫連接方法
public static Connection getCon(){
try {
//加載驅(qū)動
Class.forName(driver);
//獲取連接
con = DriverManager.getConnection(url, user, pwd);
} catch (Exception e) {
e.printStackTrace();
}
//返回連接
return con;
}
//關(guān)閉資源方法
public static void loginClose(ResultSet rs, PreparedStatement pstm, Connection con){
try {
if (rs!=null){
rs.close();
}
if (pstm!=null){
pstm.close();
}
if (con!=null){
con.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
十、實(shí)現(xiàn)數(shù)據(jù)庫的操作
首先我們在dao包下建一個UserDao接口類,用來實(shí)現(xiàn)登錄和注冊功能。
UserDao接口類位置如下:
?UserDao接口類中的代碼如下:
public interface UserDao {
//登錄方法
public User login(String username, String password);
//注冊方法
public int enroll(User user);
}
然后我們在dao包先再建一個DaoImpl包,再impl包內(nèi)建一個UserDaoImpl類,用來實(shí)現(xiàn)數(shù)據(jù)庫的操作。
UserDaoImpl類位置如下:
?UserDaoImpl類中的代碼如下:
/**
* 數(shù)據(jù)庫數(shù)據(jù)類
*/
public class UserDaoImpl implements UserDao {
//數(shù)據(jù)庫連接對象
Connection con = null;//連接對象
//預(yù)處理對象
PreparedStatement pstm = null;//與處理對象
//結(jié)果集對象
ResultSet rs = null;//結(jié)果集對象
int row ;//受影響的行數(shù)
//實(shí)例化對象
User register = null;
//數(shù)據(jù)庫登錄操作
public User login (String username,String password){
User login = null;
//下面的代碼完成的事情: 需要用戶名和密碼 返回一個user對象
try {
//調(diào)用util包下的jdbc連接方法
con = JDBCUtil.getCon();
//編寫SQL語句
String sql = "select * from t_user where username = ? and password = ?";
//預(yù)處理SQL語句對象
pstm = con.prepareStatement(sql);
//傳參
pstm.setObject(1,username);
pstm.setObject(2,password);
//獲取結(jié)果集對象 ,獲取結(jié)果
rs = pstm.executeQuery();
if (rs.next()){
//實(shí)例化對象
login = new User();
//獲取結(jié)果及對象 把數(shù)據(jù)傳入User對象中
login.setUsername(rs.getString("username"));
login.setPassword(rs.getString("password"));
}
}catch (Exception e){
e.printStackTrace();
}finally {
//調(diào)用關(guān)閉資源方法
JDBCUtil.loginClose(rs,pstm,con);
}
//返回User結(jié)果
return login;
}
//數(shù)據(jù)庫注冊操作
@Override
public int enroll(User register) {
//下面的代碼完成的事情: 獲取用戶輸入的數(shù)據(jù)添加到數(shù)據(jù)庫中
try {
//調(diào)用util包下的jdbc連接方法
con = JDBCUtil.getCon();
//編寫SQL語句
String sql = "insert into t_user(username,password,phone,address) values(?,?,?,?);";
//預(yù)處理SQL語句對象
pstm = con.prepareStatement(sql);
//傳參
pstm.setObject(1,register.getUsername());
pstm.setObject(2,register.getPassword());
pstm.setObject(3,register.getPhone());
pstm.setObject(4,register.getAddress());
//獲取結(jié)果集對象 ,獲取結(jié)果
row = pstm.executeUpdate();
}catch (Exception e){
e.printStackTrace();
}finally {
//調(diào)用關(guān)閉資源的方法
JDBCUtil.loginClose(null,pstm,con);
}
//返回受影響的行數(shù)
return row;
}
}
十一、登錄的業(yè)務(wù)處理
在Servlet包下建一個Login類用來處理登錄業(yè)務(wù)
Login類位置如圖下所示:
?
Login類內(nèi)的代碼如下:
/**
* 登錄類
*/
public class Login extends HttpServlet {
//數(shù)據(jù)庫連接對象
Connection con = null;
//預(yù)處理對象
PreparedStatement pstm = null;
//結(jié)果集對象
ResultSet rs = null;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Login...get");
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Login...post");
//1.從請求中獲取用戶提交的參數(shù)(數(shù)據(jù))
request.setCharacterEncoding("UTF-8");//設(shè)置請求的編碼格式為中文
String user = request.getParameter("user");//根據(jù)表單的name屬性獲取用戶輸入的值
String pwd = request.getParameter("pwd");//根據(jù)表單的name屬性獲取用戶輸入的值
System.out.println(user);
System.out.println(pwd);
//2.業(yè)務(wù)處理
//調(diào)用數(shù)據(jù)庫類
UserDaoImpl userDao =new UserDaoImpl();
//傳參
User user1 = userDao.login(user,pwd);
//判斷是否有該賬號
if (user1!=null){
//登錄成功跳轉(zhuǎn)登錄首頁
response.sendRedirect("ShouYe.jsp");
}else {
//登錄失敗跳轉(zhuǎn)錯誤頁面
response.sendRedirect("Error.jsp");
}
}
}
十二、注冊的業(yè)務(wù)處理
在Servlet包下建一個Enroll類用來處理登錄業(yè)務(wù)
Enroll類位置如圖下所示:
文章來源:http://www.zghlxwxcb.cn/news/detail-752593.html
?Enroll類內(nèi)的代碼如下:文章來源地址http://www.zghlxwxcb.cn/news/detail-752593.html
/**
* 注冊類
*/
//設(shè)置當(dāng)前類用來處理 /enroll 的請求
@WebServlet("/enroll")
public class Enroll extends HttpServlet {
//數(shù)據(jù)庫連接對象
Connection con = null;
//預(yù)處理對象
PreparedStatement pstm = null;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("enroll...get");
//調(diào)用doPost方法
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("enroll...post");
//設(shè)置請求的編碼格式為UTF-8格式
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
//設(shè)置以文本或網(wǎng)頁的形式響應(yīng)
response.setContentType("text/html;charset=UTF-8");//已什么樣的格式(文本/網(wǎng)頁)響應(yīng)
//從請求中獲取用戶提交的參數(shù)(數(shù)據(jù))
String zhangh = request.getParameter("zhangh");
String pwd = request.getParameter("pwd");
String dell = request.getParameter("dell");
String address = request.getParameter("address");
//實(shí)例化對象
User enroll = new User();
//給實(shí)體類user 賦值
enroll.setUsername(zhangh);
enroll.setPassword(pwd);
enroll.setPhone(dell);
enroll.setAddress(address);
//實(shí)現(xiàn)UserDao接口的UserDaoImpl類
UserDao userDao = new UserDaoImpl();
//調(diào)用子類接口的enroll方法 返回受影響的行數(shù)
int row = userDao.enroll(enroll);
//判斷受影響的行數(shù)大于零注冊成功
if (row>0){
//注冊成功 跳轉(zhuǎn)登錄頁面
response.sendRedirect("Login.jsp");
}else {
//注冊失敗 跳轉(zhuǎn)錯誤頁面
response.sendRedirect("Error.jsp");
}
}
}
到了這里,關(guān)于根據(jù)Java Web 使用Servlet +Mysql 實(shí)現(xiàn)簡易的登錄及注冊功能以及項(xiàng)目間的分層的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!