将前一篇文章(JAVA学习笔记028)纯jsp的代码,改为使用调用JavaBean的代码。
这样做的好处:更高的复用性和更易维护。
三个文件:login2.jsp; check2.jsp; LoginDao.java
再src文件夹下创建包org.login.dao,在包下创建LoginDao的Java类。
以下为LoginDao.java代码:
package org.login.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class LoginDao {
public int login(String name,String pwd) //1:登录成功,0:登录失败(用户名密码错误);-1:出现异常
{
String URL="jdbc:mysql://localhost:3306/lds?serverTimezone=UTC";
String USERNAME="root";
String PWD="prolific";
Connection connection = null;
PreparedStatement pstmt =null;
ResultSet rs=null;
try {
// a.导入驱动,加载具体的驱动类
Class.forName("com.mysql.cj.jdbc.Driver");//加载具体的驱动类
// b.与数据库建立连接
connection = DriverManager.getConnection(URL,USERNAME,PWD);
//c.发送sql,执行(增、删、改、查)
String sql="select count(*)from login where uname=? and upwd=?";
pstmt=connection.prepareStatement(sql);
//String name=request.getParameter("uname");
//String pwd=request.getParameter("upwd");
pstmt.setString(1,name);
pstmt.setString(2,pwd);
//String sql="select count(*)from login where uname='"+name+"' and upwd='"+pwd+"'";
rs=pstmt.executeQuery();
int count =-1;
if(rs.next()) {
count=rs.getInt(1);
}
return count;
} catch (ClassNotFoundException e) {
e.printStackTrace();
return -1;
} catch (SQLException e) {
e.printStackTrace();
return -1;
}catch(Exception e){
e.printStackTrace();
}
finally{
try {
if(rs!=null) rs.close();
if (pstmt!=null) pstmt.close(); //对象.方法
if (connection!=null) connection.close();
}catch(SQLException e) {
e.printStackTrace();
return -1;
}
}
return 0;
}
}
Check2.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*"%>
<%@ page import="org.login.dao.LoginDao" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>检验界面</title>
</head>
<body>
<%
String name=request.getParameter("uname");
String pwd=request.getParameter("upwd");
LoginDao dao=new LoginDao();
int result=dao.login(name,pwd);
if (result>0) {
out.println("登录成功!");
}
else if (result==0){
out.println("用户名或密码有误!");
}else{
out.println("系统异常!");
}
%>
</body>
</html>
login2.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录界面</title>
</head>
<body>
<form action="check2.jsp" method="post">
用户名:<input type="text" name="uname" /> <br/>
密码:<input type="password" name="upwd" /><br/>
<input type="submit" value="登录"/><br/>
</form>
</body>
</html>