当前位置:文档之家› JSP和数据库连接写一个网页登陆注册代码

JSP和数据库连接写一个网页登陆注册代码

文件名称123.jsp
<%@ page language="java" import="java.util.*,java.sql.*"
pageEncoding="GB2312" contentType="text/html"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<script language="javascript">
function on_submit()
{
if(ername.value=="")
{
alert("用户名不能为空,请输入用户名!");
ername.focus();
return false;
}
if(erpassword.value=="")
{
alert("密码不能为空!请输入密码!");
erpassword.focus();
return false;
}
}
</script>
<%
String path = request.getContextPath();
String basePath =
request.getScheme()+"://"+request.getServerName()+":"+request.getServerP ort()+path+"/";
%>
<%!public String codeToString(String str)
{
String s=str;
try{
byte tempB[]=s.getBytes("ISO-8859-1");
s=new String(tempB);
return s;
}
catch(Exception e)
{
return s;
}
} %>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP '123.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>
<form name="form1" action="123.jsp" method="post" onsubmit="return on_submit()">
用户名:
<input type="text" name="username">
密码:
<input type="password" name="userpassword">
<input type="submit" name="submit" value="提交">
</form>
<br>
<%out.println("你输入的账户
为:"+codeToString(request.getParameter("username")));
out.println("你输入的密码为:
"+codeToString(request.getParameter("userpassword"))); %>
<%
Statement statement;
ResultSet rs;
// 加载驱动程序以连接数据库
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/hacker", "root", "root");
System.out.println("连接成功");
statement=connection.createStatement();
rs=statement.executeQuery("select password from user where username="+"'"+request.getParameter("username")+"'");
if(rs.next())
{
String bb = rs.getString("password");
System.out.println("tongguo");
if(request.getParameter("userpassword").equals(bb))
out.println("登陆成功");
}
else
out.println("登陆失败");
connection.close();
}
// 捕获加载驱动程序异常
catch (ClassNotFoundException cnfex) {
System.err.println("装载JDBC/ODBC 驱动程序失败。

");
// cnfex.printStackTrace();
//System.exit(1); // terminate program
}
// 捕获连接数据库异常
catch (SQLException sqlex) {
System.err.println("无法连接数据库");
//sqlex.printStackTrace();
//System.exit(1); // terminate program
%>
</body> </html>。

相关主题