1.实现工具:J2EE、mysql、mysql集成管理软件Navicat for mysql
2.要导入mysql-connector-java-x.x.xx-bin.jar包
1.在MySQL中传建一个数据库,名字自己随便起一个
2.在新建的数据库下新建一张表格
1.在j2EE下先建一个login.jsp的文件
源代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Login Pagetitle>
head>
<body>
<hr><br>Welcome to this <font color="green">Login Pagefont>!<br>
<form action="do_login.jsp" method="get">
<br>
<h1>Please input your message:h1><br>
用户名:<input type="text" name="name"><br>
密码: <input type="password" name="password"><br>
<br><br><br>
<input type="submit" value="登陆"> <input type="reset"><br>
form>
body>
html>
建立do_login.jsp文件
源代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Server Page Depend !title>
head>
<body>
<h3>Which Pae will be depend by the user's message!h3>
<%
String name=request.getParameter("name");//获取name的参数值
String password=request.getParameter("password");//获取password的参数值
%>
<%
Class.forName("com.mysql.jdbc.Driver");//加载mysql驱动
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/test1", "root", "3701211994812sls");//localhost是本机地址,3306是端口号,最后是用户名和密码
Statement stmt=conn.createStatement();//实例化Statement对象
String queryNumberSQL="SELECT * from p_user where username='"+name+"' and password='"+password+"'";
ResultSet rs=stmt.executeQuery(queryNumberSQL);//执行数据库查询操作并获取结果集
boolean flag=false;//初始化flag
if(rs.next()){//判断结果
flag=true;
session.setAttribute("UserName", name);//将name的内容赋值给UserName
}else{
flag=false;
}
%>
<%
if(flag){
%>
<jsp:forward page="login_success.jsp">jsp:forward>//跳转页面
<%
}else{
%>
<jsp:forward page="login_failed.jsp">jsp:forward>//跳转页面
<%
}
//关闭上面的几个对象,注意关闭顺序,最后使用的先关闭
rs.close();
stmt.close();
conn.close();
%>
body>
html>
新建login_success.jsp文件
源代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>User Login Success Page!title>
head>
<body>
<hr><br>
<h1>Login Success!h1><br>
<font color="green">Welcome <%=session.getAttribute("UserName") %>!font>
<h3 align="center">your persional Message is:h3>
<%
out.println("Name:"+session.getAttribute("UserName"));
%>
<font color="red"><a href="login.jsp">Click mea> to log out!font>
body>
html>
新建一个login_failed.jsp文件
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Failed Page!title>
head>
<body>
<hr>
<br>
<h1><font color="red">Sorry,Login Failedfont>h1><br>
<font color="red"><a href="login.jsp">Click mea> to login!font>
body>
html>
运行结果: