此程序用到了jsp+JavaBean+JDBC+servlet+Dao
jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="../dl_5" method="post">
用户名:<input type="text" name="username"><br>
用户密码:<input type="password" name="pass"><br>
<input type="submit" value="登陆">
</form>
</body>
</html>
javbean:
package bean;
public class A {
private String name;
private String pw;
public A(String name, String pw) {
this.name = name;
this.pw = pw;
}
public A() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPw() {
return pw;
}
public void setPw(String pw) {
this.pw = pw;
}
}
package bean;
import java.sql.*;
public class B {
public Connection getConn() throws Exception {
String driverName="com.mysql.jdbc.Driver";
String dbName="user";
String url1="jdbc:mysql://localhost:3306/"+dbName;
String url2="?user=root&password=root";
String url3="&useUnicode=true&characterEncoding=GB2312";
String url=url1+url2+url3;
Class.forName(driverName);
Connection conn=DriverManager.getConnection(url);
return conn;
}
public void free(ResultSet rs,PreparedStatement pstmt,Connection conn) throws SQLException {
if(rs!=null) rs.close();
if(pstmt!=null) pstmt.close();
if(conn!=null) conn.close();
}
}
Dao:
package bean;
import java.sql.*;
public class DAO {
protected String sql="select*from user where(name=?and pw=?)";
public String create(A a) throws Exception {
B b = new B();
Connection conn = b.getConn();
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, a.getName());
pstmt.setString(2, a.getPw());
ResultSet rs = pstmt.executeQuery();
String show=null;
if(rs.next()) show="root:登陆成功!";
else show="root:登陆失败!";
b.free(rs, pstmt, conn);
return show;
}
}
servlet:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("username");
String pw=request.getParameter("pass");
A a = new A(name, pw);
DAO dao = new DAO();
try {
request.setAttribute("shows", dao.create(a));
RequestDispatcher rd;
rd=request.getRequestDispatcher("jsp+javabean+servlet+jdbc+dao/e5.jsp");
rd.forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
显示的jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%= request.getAttribute("shows") %>
</body>
</html>
在已建好的数据库user中,建一个表user,存储用户的用户名和密码。
建立两个JavaBean类,一个存放用户数据,一个用于数据库连接
Dao中写sql语句搜索用名与密码,如匹配则成功否则不成功,没有则要注册
servlet中调用Dao中的方法,并跳转到show.jsp
show.jsp中保存