JSP+JavaBean+JDBC 案例——基于数据库的登录验证

JSP+JavaBean+JDBC 案例——基于数据库的登录验证

【实现】

(1)建立ConnectDbase  JavaBean,在该JavaBean 中有方法 Connection getConnect() 得到一个连接对象,其代码如下:

package ch07_5;
import java.sql.*;

public class ConnectDbase {
	private String diverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";	//驱动程序名
	private String userName = "sa";		//用户名
	private	String userPwd = "125113jie@";		//密码
	public String getDiverName(){return diverName;}
	public void setDiverName(String diverName){this.diverName = diverName;}
	public String getUserName(){return userName;}
	public void setUserName(String userName){this.userName = userName;}
	public String getUserPwd(){return userPwd;}
	public void setUserPwd(String userPwd){this.userPwd = userPwd;}
	//实现数据库连接的方法
	public Connection getConnect() throws SQLException,ClassNotFoundException{
		String url1 = "jdbc:sqlserver://localhost:1433;DatabaseName=MOYE";
		Class.forName(diverName);
		Connection conn = DriverManager.getConnection(url1,userName,userPwd);
		return conn;
	}
}

(2)建立 User JavaBean。在该 JavaBean 中有两个属性,即 xm、mm,且有一个实现验证的方法 boolean yanzheng_user(String xm2,String mm2),其代码如下:

package ch07_5;
import java.sql.*;

public class User {
	private String xm=null;
	private String mm=null;
	public String getXm(){return xm;}
	public void setXm(String xm){this.xm=xm;}
	public String getMm(){return mm;}
	public void setMm(String mm){this.mm=mm;}
	public User(){}						//缺省的构造方法
	public User(String a,String b){		//带参数的构造方法
		xm=a;
		mm=b;
		}
	public boolean yanzheng_user(String xm2,String mm2)		//判定当输入信息正确,返回true
			throws SQLException,ClassNotFoundException{
		boolean f=false;
		ConnectDbase cdb = new ConnectDbase();
		Connection conn = cdb.getConnect();
		String sql="select* from moye_user where(uno=? and upwd=?)";	//sql语句
		PreparedStatement pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, xm2);
		pstmt.setString(2, mm2);
		ResultSet rs = pstmt.executeQuery();  	//输出结果集
		if(rs.next()) f=true;
		else f=false;
		if(rs!=null)rs.close();
	  	if(pstmt!=null)pstmt.close(); 
	  	if(conn!=null)conn.close();
		return f;
	}
}

(3)设计提交页面(ch07_5_tijiao.jsp)提交登录信息,其代码如下:

<%@ page language="java" pageEncoding="GB2312" %>

<html>
  <head>
    <title>用户登录提交页面</title>
  </head>
  <body>
  	<form action="ch07_5_show.jsp" method="post">
  		用 户 名:<input type="text" name="xm"><br><br>
  		用户密码:<input type="password" name="mm"><br><br>
  		<input type="submit" value="登录">
  		</form>
  </body>
</html>

(4)设计验证页面(ch07_5_show.jsp),其代码如下:

<%@ page language="java" pageEncoding="UTF-8" %>

<html>
  <head>
 	 <meta charset="UTF-8">
    <title>登入验证页面</title>
  </head>
  <body>
  	<% request.setCharacterEncoding("GB2312"); %>
  	<jsp:useBean id="uu" class="ch07_5.User"/>
  	<jsp:setProperty name="uu" property="*" />
  	<% if(uu.yanzheng_user(uu.getXm(),uu.getMm())){%>
  		<%=uu.getXm() %>:登录成功!<br>
  	<%}else{ %>
  		<%=uu.getXm() %>:登录失败!<br>
  		<%} %>
  </body>
</html>

运行截图:

展开阅读全文

没有更多推荐了,返回首页