JSP 【基础】连接数据库的登录及验证

最基础的

index页面


<center>
  <h1>登录操作</h1>
  <hr>
  /*将表单提交到login_check页面*/
  <form action="login_check.jsp" method="post">
    <table border="1">
      <tr>
        <td colspan="2" align="center">用户登录</td>   
      </tr>
      <tr>
        <td>登录ID</td>
        <td><input type="text" name="id" ></td>
      </tr>
      <tr>
        <td>登录密码:</td>
        <td><input type="password" name="password" ></td>
      </tr>
      <tr>
        <td colspan="2">
          &nbsp;&nbsp;<input type="submit" value="登录">&nbsp;&nbsp;
          <input type="reset" value="重置">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          <input type="checkbox" name="remember" checked>记住我	 
        </td>   
      </tr>
    </table>
  </form>
   <h5>如果尚未注册,请先点击<a href="register.jsp">这里</a>进行注册!</h5>
</center>

login_check页面

思路:

  • 获取到index填写的内容信息,将id和pwd传到check(uid,pwd)方法进行查找
  • check方法:先连接数据库
  • 再 通过ResultSet ,获取到数据
  • 返回uname,若uname不为空则说明找到了。
<%!
String check(String uid, String upassword){
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	String uname = "";
	try{
		//1.加载数据库
		Class.forName("com.mysql.jdbc.Driver");

		//2.连接数据库
		String url = "jdbc:mysql://localhost:3306/db_news2019";
		String user = "root";
		String password = "admin";
		conn = DriverManager.getConnection(url,user,password);
		
		//3.获取数据库元素
		String sql = "select * from t_user where  uid=? and upassword=?";
		PreparedStatement pstm = conn.prepareStatement(sql);
		pstm.setString(1, uid);
		pstm.setString(2, upassword);
		
		rs = pstm.executeQuery();
		
		if(rs.next()){
			uname = rs.getString("uname");
		}
	}catch (ClassNotFoundException e) {
		 System.out.print(e.getMessage());
	 }catch (SQLException e) {
		 System.out.print(e.getMessage());
	 }finally{
		if(rs != null){ 
			try{
			   	rs.close(); 
			}catch(SQLException e){
				System.out.print(e.getMessage());
			}
		}
		if(pstmt != null){ 
			try{
				pstmt.close(); 
			}catch(SQLException e){
				System.out.print(e.getMessage());
			} 
		}
		if(conn != null){ 
			try{
				conn.close(); 
			}catch(SQLException e){
				System.out.print(e.getMessage());
			} 
		}
		return uname;
	}
}
%>

<%
	request.setCharacterEncoding("utf-8");
	String id = request.getParameter("id");
	String pwd = request.getParameter("password");
	String name = null;
	//名字不为空则说明匹配成功了。
	if(!((name=check(id, pwd)).equals(""))){
		session.setAttribute("username", name);
		response.sendRedirect("login_success.jsp");
	}else{
		response.sendRedirect("login_fail.jsp");
	}

%>

然后再写login_success和login_fail页面就可以了。

你可能感兴趣的:(JSP)