JSP实现登录注册并链接数据库页面

        在学习了页面跳转及部分知识后做了登录注册界面,并经过本博主调试bug后完善的更进一步,大家有什么问题也可以留言,本博主以更广泛学习讨论为目的。

        内容介绍:实现页面的跳转;注册登录时实现读取数据库,并对数据库实现插入(insert)和查询(select)功能。

        几点注意:sqljdbc.jar包的导入和环境变量;数据库的登录读取,可以参考数据库的测试。

登录注册界面的代码实现

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Feilong_index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  <body>
    <center>
    <font face = "宋体" size = "6" color = "#000">欢迎使用飞龙科技</font><hr>
    <div>
        <img alt="" width = "600" height = "400" src="D:\我的图片\QImages\小人团队.jpg">
    </div>
    <table width = "200" border ="1" bordercolor = "#00F">
        <tr>
          <td><input type = "button" value = "登      陆" onclick = "window.location.href('login.jsp')"></td>
          <td><input type = "button" value = "注      册" onclick = "window.open('register.jsp')"></td>
        </tr> 
    </table>
  </center>
  </body>
</html>

login.jsp  //登录界面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Feilong_login.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  <body>
    <center>
  	<font face="楷体" size="6" color="#000" >登录界面</font>
  	<%  
    String flag = request.getParameter("errNo");  
    try{
         if(flag!=null)
            out.println("用户名不存在或密码错误");
    }catch(Exception e){
        e.printStackTrace();
    }
   %>
  	<form action = "loginCh.jsp" method="post">
      <table width="300" height = "180" border="5" bordercolor="#A0A0A0"> 
 		<tr>
 		  <th>账  户:</th>
 		  <td><input type="text" name="name"  value = "请输入用户名" maxlength = "16" onfocus = "if(this.value == '请输入用户名') this.value =''"></td>
 	    </tr>
 	    <tr>
 		  <th>密  码:</th>
 		  <td><input type="password" name="pwd" maxlength = "20"></td>
 	    </tr>
 	    <tr>
 	      <td colspan = "2" align = "center">
 		    <input type="submit" name="submit" value="登       录">
 		    <input type="button" value="返       回"
 			  οnclick="window.location.href('/webText')">
 	      </td>
 	    </tr>
 	  </table>
 	</form>
  </center>
  </body>
</html>
loginCh.jsp  //登录检验
<%@ page language="java" import="java.util.*,java.sql.*,java.net.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Feilong_loginCh.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  <body>
    <%      //接收用户名和密码  
            String user = new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");  
            String pwd = request.getParameter("pwd");

            String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
            String url = "jdbc:sqlserver://localhost:1433; DatabaseName = db_01";
            String username = "sa";
            String password = "123";
            Class.forName(driverClass);//加载驱动 
            Connection conn = DriverManager.getConnection(url,username,password);//得到连接
            PreparedStatement pStmt = conn.prepareStatement("select * from tb_user where UName = '" + user + "' and Pwd = '" + pwd + "'");
              ResultSet rs = pStmt.executeQuery();
                if(rs.next()){
                    response.sendRedirect("success.jsp?username="+URLEncoder.encode(user)); //解决乱码 
                }else{
                    response.sendRedirect("login.jsp?errNo");//密码不对返回到登陆  
                }
     rs.close();
     pStmt.close();
     conn.close();
     %>
  </body>
</html>
success.jsp  //登录成功界面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>Feilong_登录成功</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  <body>
    <center>
    <%
     String name = new String(request.getParameter("username").getBytes("8859_1"));
     out.println("欢迎你:" + name);
    %><br>
    <a href="login.jsp">重新登陆</a>
    </center>
  </body>
</html>

register.jsp  //注册界面

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'Feilong_register.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
    <script>
		function addCheck(){
			var username=document.getElementById("username").value;
			var password=document.getElementById("password").value;
			var newword=document.getElementById("newword").value;
			if(username==""){
				alert("用户名不能为空!");
				document.getElementById("username").focus();  
				return false;
                }
			if(password==""){
				alert("密码不能为空!");
				 document.getElementById("password").focus();
				 return false;
				 }
			if(password != newword){
				alert("两次输入密码不相同!");
				 document.getElementById("newword").focus();
				 return false;
				 }
		}
		function validate(){
		    var flag = addCheck();
		    if(flag == false)
		        return false;
		    return true;
	    }
	</script>
  <body>
    <center>
	<font face="楷体" size="6" color="#000">注册界面</font>
	<form action = "checkRegister.jsp" method = "post" onsubmit = "return validate()">
  	<table width="300" height = "180" border="5" bordercolor="#A0A0A0">
  	  <tr>
		<th>用户名:</th>
		<td><input type="text" name="username" value="输入16个字符以内" maxlength = "16" onfocus = "if(this.value == '输入16个字符以内') this.value =''"></td>
 	  </tr>
 	  <tr>
 		<th>输入密码:</th>
 		<td><input type="text" name="password" value="输入20个字符以内" maxlength = "20" onfocus = "if(this.value == '输入20个字符以内') this.value =''"></td>
 	  </tr>
 	  <tr>
 		<th>确认密码:</th>
 		<td><input type="text" name="newword" value="重新输入密码" maxlength = "20" onfocus = "if(this.value == '重新输入密码') this.value =''"></td>
 	  </tr>
	  <tr>
 		<td colspan = "2" align = "center">
 		  <input type="submit" value="注  册">    
 		  <input type="reset" value="重  置">
 		</td>
	  </tr>
	</table>
    </form>
    </center>
  </body>
</html>

checkRegister.jsp //验证注册用户并导入数据库

<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Feilong_chechRegister.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  <body>
    <%      
            String user = new String(request.getParameter("username").getBytes("ISO-8859-1"),"UTF-8");  
            String pwd = request.getParameter("password");

            String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
            String url = "jdbc:sqlserver://localhost:1433; DatabaseName = db_01";
            String username = "sa";
            String password = "123";
            Class.forName(driverClass);//加载驱动 
            Connection conn = DriverManager.getConnection(url,username,password);//得到连接
            PreparedStatement pStmt = conn.prepareStatement("select * from tb_user where UName = '" + user + "'");
              ResultSet rs = pStmt.executeQuery();
                if(rs.next()){
                    out.println("<script language='javascript'>alert('该用户已存在,请重新注册!');window.location.href='register.jsp';</script>");
                }else{
                    PreparedStatement tmt = conn.prepareStatement("Insert into tb_user values('" + user + "','" + pwd + "')");
                        int rst = tmt.executeUpdate();
                        if (rst != 0){
                              out.println("<script language='javascript'>alert('用户注册成功!');window.location.href='index.jsp';</script>");  
                        }else{
                           out.println("<script language='javascript'>alert('用户注册失败!');window.location.href='register.jsp';</script>");  
                        }
                }
     %>
  </body>
</html>

以上代码若有问题,首先执行下面数据库的测试代码:

执行下面代码前,首先在数据库中创建名为‘db_01’的数据库,在表中创建名为‘user’的表

login1.jsp

<%@ page language="java" import="java.util.*,java.sql.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Feilong_login.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  <body>
    <%
    String driverClass = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
    String url = "jdbc:sqlserver://localhost:1433; DatabaseName = db_01";
    String username = "sa";
    String password = "123";
    Class.forName(driverClass);//这步错可能是因为.jar包导入问题
    Connection conn = DriverManager.getConnection(url,username,password);//这步错可能是因为数据库属性安全中的名、密码不对或SQL的IP端口不是‘1433’
    PreparedStatement pStmt = conn.prepareStatement("select * from tb_user");
           ResultSet rs = pStmt.executeQuery();
                while(rs.next()){
                      out.println("用户名: " + rs.getString(1) 
                             + " 密码: " + rs.getString(2));
                }
     rs.close();
     pStmt.close();
     conn.close();
     %>
  </body>
</html>

小人团队.jpg

以上代码都是经过本博主细心敲打修改并实现的。转载请注明本博客的地址。

  • 94
    点赞
  • 676
    收藏
    觉得还不错? 一键收藏
  • 46
    评论
好的,我可以提供一个简单的 JSP 登录页面示例,并演示如何与数据库进行链接和验证用户登录信息。 首先,我们需要创建一个包含以下表单元素的 JSP 页面: ```html <html> <head> <title>Login Page</title> </head> <body> <h1>Login</h1> <form method="post" action="login.jsp"> <label>Username:</label> <input type="text" name="username" required><br> <label>Password:</label> <input type="password" name="password" required><br> <input type="submit" value="Submit"> </form> </body> </html> ``` 在这个表单中,我们使用了 `post` 方法提交数据到 `login.jsp` 页面。表单中包含了用户名和密码两个输入框。 接下来,我们需要在 `login.jsp` 页面中处理表单提交的数据,并验证用户登录信息。我们可以使用 JDBC 来链接数据库并进行查询操作。以下是一个简单的 JSP 页面示例: ```jsp <%@ page import="java.sql.*" %> <% // 获取表单提交的数据 String username = request.getParameter("username"); String password = request.getParameter("password"); // 链接数据库 String url = "jdbc:mysql://localhost:3306/mydatabase"; String user = "root"; String dbpassword = "password"; Connection conn = DriverManager.getConnection(url, user, dbpassword); // 查询用户信息 String query = "SELECT * FROM users WHERE username = ? AND password = ?"; PreparedStatement stmt = conn.prepareStatement(query); stmt.setString(1, username); stmt.setString(2, password); ResultSet rs = stmt.executeQuery(); // 验证用户信息 if (rs.next()) { out.println("Login successful!"); } else { out.println("Invalid username or password!"); } // 关闭数据库链接 rs.close(); stmt.close(); conn.close(); %> ``` 在这个 JSP 页面中,我们首先获取表单提交的用户名和密码,并链接数据库。然后,我们使用 `PreparedStatement` 执行查询操作,并验证用户信息。最后,我们关闭数据库链接。 这是一个简单的 JSP 登录页面示例,并演示了如何链接数据库和验证用户登录信息。请注意,这只是一个示例,实际应用中需要更加完善和安全的处理用户输入和数据库操作。
评论 46
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值