HTML+Servlet + MVC + JDBC + MySQL的簡單登入
阿新 • • 發佈:2019-01-10
1.建立login.html頁面
為了簡單這裡只有id和pwd
<lable>ID:</lable><input type="text" id="id" name="id"><br/>
<label>密碼:</label><input type="password" id="pwd" name="pwd"><br/>
<button type="button" id="btn_submit" >登入</button>
2.建立後臺LoginServlet.java
doPost中的關鍵程式碼:
int id = Integer.parseInt(request.getParameter("id")); String pwd = (String)request.getParameter("pwd"); loginService = new LoginServiceImp(); Student stu = loginService.checkUserExist(id, pwd); PrintWriter out = response.getWriter(); if(stu != null){ out.write("success"); }else{ out.write("id or pwd is false"); }
這裡獲取頁面中傳遞的id和pwd,再呼叫service層進行驗證,並將驗證結果返回個前端頁面。
3.建立Ajax連結servlet
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#btn_submit").click(function (){
//檢測id是否是數字,如果是,則向後端傳送請求
if($("#id").val().match(/^[0-9]+$/)){
$.post(
"servlet/LoginServlet",
{
id:$("#id").val(),
pwd:$("#pwd").val()
},
function(data){
alert("back: " + data)
}
)
}else{
alert("id只能是數字型別")
}
})
})
</script>
這裡對id進行數字型別驗證,傳送post請求給後端servlet。使用了jQuery的post方法。
4.建立ILoginService.java和LoginServiceImp.java
5.建立ILoginDAO.java和 LoginDAOImp.java
6.建立DButil連結mysql資料庫
public class DButil {
private String driver = "com.mysql.jdbc.Driver";
private String url = "jdbc:mysql://localhost:3306/test";
private String username = "root";
private String pwd = "root";
private Connection conn;
public void getConn(){
try {
Class.forName(driver); //載入驅動
conn = DriverManager.getConnection(url,username, pwd); //獲取連結
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet excuteQuery(String sql){
ResultSet res = null;
getConn();
try {
Statement statement = conn.createStatement();
res = statement.executeQuery(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return res;
}
@Test
public void testDB(){
String sql = "select name, pwd from student where id = 1";
ResultSet excuteQuery = excuteQuery(sql);
try {
if(excuteQuery.next()){
System.out.println("name:" + excuteQuery.getString("name"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注:如果出現“Access denied for user 'root'@'localhost' (using password: YES)”
(1)開啟MySQL目錄下的my.ini檔案,在檔案的最後新增一行“skip-grant-tables”,儲存並關閉檔案。
(2)重啟MySQL服務。
原始碼位置:
連結:http://pan.baidu.com/s/1nvHUcvJ 密碼:ol6e