上一期我們已經說了如何通過maven新建一個后端程式,(全程配圖超清晰的JAVA后臺控制(maven+Tomcat+JDBC)第一期.)并寫出了一個簡單的Servlet程式然后通過IDEA和Tomcat創建出來了一個簡單的網頁,這回我們就說說怎么真正的鏈接資料庫,(這里用的是Mysql資料庫)并寫出一個表單驗證網頁來實踐一下我們的鏈接是否有問題
如何在IDEA上新建Maven后端并鏈接資料庫
- 匯入各種包以及組態檔
- 編輯maven中pom.xml檔案
- 匯入Druid組態檔
- 撰寫JAVA程式
- 撰寫html檔案
- 撰寫JDBCUtils工具類
- 撰寫Servlet程式
匯入各種包以及組態檔
編輯maven中pom.xml檔案
- 首先我們要做的就是進入maven官網來匯入包maven包庫網站,然后我們需要輸入servlet,mysql-connecter,druid,template進行搜索,來獲取這些包,而且需要匯入相對應的版本,確保版本對應性,一點要注意這一點,我曾經被這個版本問題坑得很慘,在這里我就直接給出相應的配置代碼,直接復制即可,版本上肯定不會有問題,不過要先說明一下我這里的mysql是5.7版本的,
- 直接在dependencies中添加下面代碼
<dependencies>
..........
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alexkasko.springjdbc/springjdbc-iterable -->
<dependency>
<groupId>com.alexkasko.springjdbc</groupId>
<artifactId>springjdbc-iterable</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.0</version>
</dependency>
</dependencies>
- 添加完成之后點擊這個小M就能吧包匯入了,不過時間可能要略長,請耐心等待,

匯入Druid組態檔
- 在這個src-main-resources中添加Druid1.properties檔案,一定要在這個resources中創建,然后在里面添加這些資料,添加完成后就配置好了,
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root #資料庫用戶名
password=123 #資料庫密碼
# 初始化連接數量
initialSize=5
# 最大連接數
maxActive=10
# 最大超時時間
maxWait=3000
撰寫JAVA程式
撰寫html檔案
- 在這個web(webapp)下創建index.html檔案,然后在檔案中寫入這些代碼,這是一個簡單的表單登錄,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h2>Hello World!</h2>
<form method="get">
用戶名:<input type="account" name="account" placeholder="請輸入用戶名" autofocus autocomplete><br/></br>
密碼:<input type="password" name="password" placeholder="請輸入密碼"></br></br>
<input type="submit" value="登錄" formaction="demo1"/>
</form>
</body>
</html>
撰寫JDBCUtils工具類
- 然后在這個java目錄下創建util目錄,在這個util目錄下創建一個JDBCutils工具類,在這個類里面會寫一些用Druid鏈接資料庫的操作,比如獲取鏈接,還有關閉資料庫鏈接什么的,一般我們在撰寫后端程式的時候都會把一些代碼封裝起來,然后再以后使用的時候可以方便快捷的使用它們,具體代碼如下
package util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* JDBC工具類,使用Druid連接池
*/
public class JBDCUtils {
private static DataSource ds;
static{
//1.加載組態檔
Properties pro = new Properties();
try {
//用ClassLoader來加載組態檔,獲取位元組輸入流,鍵值對集合
pro.load(JBDCUtils.class.getClassLoader().getResourceAsStream("Druid1.properties"));
//初始化連接池物件,回傳DataSource資源
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取Connection物件
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
/**
* 關閉資源的方法
* @param rs
* @param stmt
* @param conn
*/
public static void close(ResultSet rs, Statement stmt, Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn != null){
try {
conn.close(); //歸還鏈接
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close1( Statement stmt, Connection conn){
close(null,stmt,conn);
}
/**
* 獲取連接池物件
* @return DataSource資源
*/
public static DataSource getdatasourse() {
return ds;
}
}
- 當然在獲取了資料庫內容的時候,我們也要按照慣例把他們都封裝成一個一個的類物件,因為這樣的話我們就可以快捷的訪問他們了,所以我們要新建一個domain包在java目錄下,然后在里面創建Users類,在里面封裝一些屬性以及相應的get,set方法,具體代碼如下
package doMain;
public class Users {
private Integer userid;
private String userPhone;
private String author;
private Integer count;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
@Override
public String toString() {
return "doMain{" +
"userid=" + userid +
", userPhone='" + userPhone + '\'' +
", author='" + author + '\'' +
", count=" + count +
'}';
}
}
- 資料庫內容,我的資料庫是一個叫做usres的資料庫然后這里面有兩個int型別的資料,分別是userid和count兩列,還有兩個varchar型別的資料,分別叫做userPhone和author,里面的值如下,當然這只是我自己的資料,這個資料可以隨便改成你喜歡的資料,

撰寫Servlet程式
- 那么現在,萬事俱備,只欠Servlst代碼,我們要在java目錄下創建com包,在里面創建ServletDemo1程式,然后在里面寫出這些代碼當然代碼中不僅僅有資料庫鏈接的東西還有一些獲取表單和表頭的操作,在這里就不再贅述,簡言之就是使用一些request的固定方法,來獲取了表單資料,然后緊接著就用了request的getHeaderNames()的方法回傳了一個字串的列舉型別,然后遍歷一下這個集合就能出來相應的表頭資料,這些資料我們在以后的學習中大部分都要用到,列印出來就更加的清晰明了,有利于我們以后的學習,
package com;
import doMain.Users;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import util.JBDCUtils;
import javax.servlet.RequestDispatcher;
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.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;
/**
* 登陸案例,使用JDBCTemplate技術
*/
@WebServlet("/demo1")
public class ServletDemo1 extends HttpServlet {
private final JdbcTemplate template = new JdbcTemplate(JBDCUtils.getdatasourse());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet成功運行");
String account = req.getParameter("account"); // 從 request 中獲取名為 account 的引數的值
String password = req.getParameter("password"); // 從 request 中獲取名為 password 的引數的值
System.out.println("account:" + account + "\npassword:" + password); // 列印出來看一看
/**
* 連接資料庫,進行登陸操作
*/
String result = "資料庫讀取例外!";
if (account.isEmpty()){
result = "用戶名為空!";
}else if (password.isEmpty()){
result = "密碼為空!";
}else{
String sql12 = "select * from users";
List<Users> list = template.query(sql12, new BeanPropertyRowMapper<Users>(Users.class));
for (Users users : list) {
System.out.println(users.getAuthor()+" "+users.getCount());
if(users.getAuthor().equals(account)&&users.getUserPhone().equals(password)){
result = "已經連接資料庫,并且匹配資料成功";
break;
}
result = "輸入用戶賬號密碼不正確,請重試";
}
}
resp.setContentType("text/html;charset=utf-8"); // 設定回應報文的編碼格式
PrintWriter pw = resp.getWriter(); // 獲取 response 的輸出流
pw.println(result); // 通過輸出流把業務邏輯的結果輸出
pw.flush();
/**
* 使用一個一個函式獲取表單資訊和資料,主要獲取表單資料
*/
resp.setContentType("text/html;charset=UTF-8");
String name = req.getParameter("account");
PrintWriter out = resp.getWriter();
String title = "使用 GET 方法讀取表單資料";
// 處理中文
String docType = "<!DOCTYPE html> \n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>用戶名</b>:"
+ name + "\n" +
" <li><b>密碼</b>:"
+ req.getParameter("password") + "\n" +
" <li><b>請求方法</b>:"
+ req.getMethod()+ "\n" +
" <li><b>Servlet路徑</b>:"
+ req.getServletPath()+ "\n" +
" <li><b>URI路徑</b>:"
+ req.getRequestURI() + "\n" +
" <li><b>URL路徑</b>:"
+ req.getRequestURL() + "\n" +
" <li><b>URL實作協議和版本</b>:"
+ req.getProtocol() + "\n" +
" <li><b>客戶機的IP地址</b>:"
+ req.getRemoteAddr() + "\n" +
"</ul>\n" +
"</body></html>");
/**
* 使用req.getHeaderNames方法來獲取表頭資料和資訊
*/
Enumeration<String> headerNames = req.getHeaderNames();
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out1 = resp.getWriter();
String title1 = "使用 GET 方法讀取表頭資料";
String docType1 = "<!DOCTYPE html> \n";
out1.println(docType1 +
"<html>\n" +
"<head><title>" + title1 + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title1 + "</h1>\n" +
"<ul>\n"+
" <li><b>用戶名</b>:"
+ req.getParameter("account") + "\n" +
" <li><b>密碼</b>:"
+ req.getParameter("password") + "\n"
);
while (headerNames.hasMoreElements()) { //回傳了一個列舉型別,然后用類似迭代器的方法輸出
out1.println(
" <li><b>"+headerNames.nextElement()+"</b>:"
+ req.getHeader(headerNames.nextElement()) + "\n"
);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
撰寫完這個Servlet代碼之后,直接啟動IDEA上面那個綠三角,啟動這個服務器,然后就會出現一個表單登錄網站,在輸入相應資料之后就好了,再點擊登錄,
這時候我們就能看到如下的這個界面,如果賬號或者密碼輸入錯誤就會出現密碼或賬號錯誤的字樣,我這里給的插圖是否登陸成功的提示是顯示在中間,不過代碼寫出來的結果可能是在網頁的一開頭,
這樣的話就我們就能夠有效的鏈接資料庫了,不過在最后要強調一點就是說這里一定要打開資料庫進行操作,要不然就會報錯,無法連接資料庫,

那么到這里我們就能夠制作出簡單的表單登錄的操作了,下期我們再來說一說如何自制一個能夠點擊變更的驗證碼,還有一些有關資料庫鏈接和使用的優化操作,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/277638.html
標籤:java
