首先,我们先来了解一下注册,注册便是申请账户。也就是对数据库的账号库进行新增数据,同时进行验证,验证可以通过js或serlvet来进行实现,下面是我们的以及一个简单注册实例,没有对账号密码格式进行限制作为学习了解
jsp文件
<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="GB18030"%> <!DOCTYPE html> <html> <head> <meta charset="GB18030"> <title>Insert title here</title> </head> <body> <body background="image\td.jpg"> <audio src="image\若把你.mp3" controls> </body> </audio> <form action="login1" method="get" > <font size="5" align="center">注册界面</font><br> 用户名:<input type="text" name="username" ><br> 密 码:<input type="text" name="password"><br> <input type="submit" value="注册"> <input type="reset"value="重置"> </form> </body> </html>
serlvet
package Servlet; import java.io.IOException; import java.sql.SQLException; import org.apache.catalina.tribes.ChannelSender; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import com.Dao.zhuce; import com.Bean.deng; /** * Servlet implementation class dengji */ @WebServlet("/login1")//对应html中的action表单 public class login1 extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public login1() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); //设置相应的文本类型 response.setContentType("text/html;charset=utf-8");//设置响应类型,并防止中文乱码 zhuce A =new zhuce(); int i = 0; String username=request.getParameter("username"); String password = request.getParameter("password"); deng B = new deng(); B.setUsername(username); B.setPassword(password); System.out.println(username); System.out.println(password); try { i=A.dl(B); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(i==1) { response.getWriter().append("注册成功!2s后返回登录页面"); response.setHeader("refresh","2;URL=denglu.html");} else response.getWriter().append("注册失败!"); } }
bean文件
package com.Bean; public class deng { private String username; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } }
package com.Dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import com.Bean.deng; import com.Util.utils; public class zhuce{ // TODO Auto-generated method stub public int dl(deng A) throws Exception { Connection connection = utils.getConnection(); String sql = "insert into login values(?,?)"; //修改你的表格名称 int i=0; try { //创建语句传输对象 PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, A.getUsername()); preparedStatement.setString(2, A.getPassword()); preparedStatement.executeUpdate(); i=1; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { } return i; } }
dao文件下的zhuce.java
Util下的工具包
package com.Util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * JDBC快速入门 */ public class utils { public static Connection getConnection() throws Exception { Connection connection = null;//连接数据库 PreparedStatement ps = null;//Statement 对象用于将 SQL 语句发送到数据库中。 ResultSet rs = null; //1. 导入驱动jar包 //2.注册驱动 // Class.forName("com.mysql.cj.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/zjr?serverTimezone=UTC","root", "Zhaowenzhe1007");//修改你的数据库名称以及密码 return connection; } public static void close(Connection connection ) { try { if (connection != null) { connection.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void close(PreparedStatement preparedStatement ) { try { if (preparedStatement != null) { preparedStatement.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void close(ResultSet resultSet ) { try { if (resultSet != null) { resultSet.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
注册就是一个简单的添加sql语句的执行,同理我们可以想得到登录就是一个查询的sql语句,本次我们先学习单用户登录,通过查询用户名,如果存在便返回密码参数与输入的密码值进行匹配,如果一致输出登录成功并返回登陆后页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>登录</title> </head> <body background="image\td.jpg"> <audio src="image\若把你.mp3" controls> </body> </audio> <h1>登录界面</h1> <form action="login" method="post"> <input type="hidden" name="action" value="regist"> <input type="text" name="username" placeholder="请输入您的用户名"><br> <input type="password" name="password" placeholder="密码"><br> <input type="submit" value="登录"> <input type="text" id="vcode" placeholder="验证码" value="验证码" onfocus="this.value=''" onblur="if(this.value=='')this.value='验证码'" /><span id="code" title="看不清,换一张"></span> <div id="search_pass_link"> </div> </form> <a style="color:blue" href='zc.jsp?' onclick="del()">没有账号?注册一个!</a> <center> <p>${message}</p> </center> </body> </html>
login的serlvet文件
package Servlet; import java.io.IOException; import java.sql.SQLException; import com.Bean.deng; import com.Dao.UserDB; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpSession; @WebServlet("/login") public class login extends HttpServlet{ private static final long serialVersionUID=1L; String message=""; public login() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String url="denglu.jsp"; try { url=LoginUser(request,response); } catch (ClassNotFoundException | SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } request.setAttribute("message", message); //forward函数把原页面的req和res传入新界面 这时新旧页面拥有相同的req和res,request.getParameter可得相应值 getServletContext().getRequestDispatcher(url).forward(request,response); } private String LoginUser(HttpServletRequest request, HttpServletResponse response) throws Exception { String username=request.getParameter("username"); String password=request.getParameter("password"); deng user=new deng(); user.setUsername(username); user.setPassword(password); String url="/denglu.jsp"; if(!UserDB.UserExists(username)){//判断用户名是否存在 message="用户名不存在!"; return url; } deng user2=UserDB.Password(username);//从数据库中获取该用户名的密码 if(user2.getPassword().equals(password)) {//判断密码是否正确 url="/zhu.jsp"; return url; } else { message="密码错误!"; return url; } } }
bean文件数据库连接工具包和注册一致,下面是dao文件userdb
package com.Dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.Util.utils; import com.Bean.deng; public class UserDB { public static boolean UserExists(String username) throws Exception{ Connection connection = utils.getConnection(); PreparedStatement ps=null; ResultSet rs=null; String xm="select username from login"+" where username=?"; try { ps=connection.prepareStatement(xm); ps.setString(1,username); rs=ps.executeQuery(); return rs.next(); }catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return false; } finally { utils.close(rs); utils.close(ps); utils.close(connection); } } public static deng Password(String username) throws Exception{ Connection conn=utils.getConnection(); PreparedStatement ps=null; ResultSet rs=null; String xm="select * from login"+" where username=?"; try { ps=conn.prepareStatement(xm); ps.setString(1,username); rs=ps.executeQuery(); deng user=new deng(); if(rs.next()) { user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); } return user; }catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } finally { utils.close(rs); utils.close(ps); utils.close(conn); } }}
我们这里用到了message来传递具体错误信息,如账号不存在密码错误
deng user=new deng(); if(rs.next()) { user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); } return user;
dao文件下获取账号密码信息来传递给serlvet进行匹配
try {
url=LoginUser(request,response);
}
serlvet将接收的数据传入LoginUser类中
deng user=new deng();
user.setUsername(username);
user.setPassword(password);接收数据库值
String username=request.getParameter("username");
String password=request.getParameter("password");接收jsp中输入值
if(!UserDB.UserExists(username)){//判断用户名是否存在
message="用户名不存在!";
return url;
}
deng user2=UserDB.Password(username);//从数据库中获取该用户名的密码
if(user2.getPassword().equals(password)) {//判断密码是否正确
url="/zhu.jsp";
return url;
}
else {
message="密码错误!";
return url;
}进行匹配密码是否相同同时选择登录成功后的返回页面