JavaWeb:实验二JSP表单开发及访问数据库
完整代码下载:https://www.123684.com/s/SaYRVv-qiRg3
实现注册与登录功能:
1. 创建一个数据库,在数据库建立用户表。
2.制作一个注册表单,可以输入账户和密码并提交(在数据提交之前用JS对表单数据进行有效性验证),将表单提交的数据写入数据库。
3.制作一个登录表单,输入账号和密码,通过数据库进行验证,如果账号、密码验证通过,则显示“登录成功”,否则显示“登录失败”。
4.从数据库中读取所有的用户数据,并在页面中显示。
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./登录注册.css">
</head>
<body>
<div class="box">
<h2>Login</h2>
<form action="login_result.jsp" method="post" name="loginForm"
onsubmit="return check()">
<div class="input-box">
<label>账号</label> <input type="text" name="username"
placeholder="请输入用户名">
</div>
<div class="input-box">
<label>密码</label> <input type="password" name="password"
placeholder="请输入密码">
</div>
<div class="btn-box">
<div>
<button>登录</button>
</div>
</div>
</form>
</div>
</body>
</html>
login_result.jsp
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
String username = request.getParameter("username");
String password = request.getParameter("password");
//1.导入包
//将jar包粘贴到WEB_INF中的lib文件夹下
//2.加载驱动
String driver = "com.mysql.cj.jdbc.Driver";
Class.forName(driver);
//3.创建链接Connection
String url = "jdbc:mysql://localhost:3306/javaweb?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
Connection conn = DriverManager.getConnection(url, "root", "g1234");
Statement stat = conn.createStatement();
String sql = "SELECT * FROM s WHERE stuname=? and password=?";
PreparedStatement pstat = conn.prepareStatement(sql);
pstat.setString(1,username);
pstat.setString(2,password);
ResultSet rs = pstat.executeQuery();
if(rs.next()){
out.print("登录成功,欢迎您:");
out.println(username);
}else{
out.print("登录失败!!!");
}
stat.close();
pstat.close();
conn.close();
%>
</body>
</html>
本文来自博客园,作者:Cloudservice,转载请注明原文链接:https://www.cnblogs.com/whwh/p/18490163,只要学不死,就往死里学!