最近工作室考核,需要我们做一个简单的登录注册功能
项目要求连接数据库(以Mysql数据库为例子)
1.连接数据库
package com.gl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
//这个类用来获取与数据库的连接
public class Butil {
public static Connection getcoonection() {
Connection conn = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysqldata?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai","root","gl010924");
//mysqldata是你自己的库名
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
}
2.设置编码为UTF-8,防止乱码
package com.gl;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
//这个类用来对编码形式进行规范 :UTF-8
@WebFilter("/*")
public class EncodingFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
filterChain.doFilter(servletRequest, servletResponse);
}
}
3.编写数据库的一些操作(增删改查)
package com.person;
import com.gl.Butil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Student {
//数据库添加
public static void add(String name, String password){
Connection con = Butil.getcoonection();
PreparedStatement pstmt;
int number = 1;
try {
pstmt = con.prepareStatement("select * from data "); //获取数据库表单的信息
ResultSet resultSet = pstmt.executeQuery();
while (resultSet.next()){
number++; //如果数据库还有信息就加1,间接获得数据库表单的数量
}
String id =""+number;
pstmt = con.prepareStatement("insert into data (id,name,password) values ('"+id.trim()+"','"+name.trim()+"','"+password.trim()+"')");
//在数据库添加新的信息
pstmt.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
//数据库修改
public static void Update(String psd, String username){
Connection con = Butil.getcoonection();
PreparedStatement pstmt;
try {
pstmt = con.prepareStatement("update data set password = '"+ psd.trim()+"'where name ='"+username.trim()+"' ");
//对数据库进行修改操作
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
4.首页的jsp页面(页面中的背景图片大家自己可以随便找找)
<%--
Created by IntelliJ IDEA.
User: 86187
Date: 2020/6/23
Time: 23:42
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
登录界面
5.登录功能的实现
package com.gl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username"); //获取登录页面输入的用户名
String password = req.getParameter("password"); //获取登录页面输入的密码
// String sql = "select * from data where username = '"+username + "'"; //不安全,容易被扒 防sql注入
PrintWriter writer = resp.getWriter();
try {
Connection coon = Butil.getcoonection(); //获得数据库连接
PreparedStatement stmt = coon.prepareStatement("select * from projectdata where username = ?"); //sql语句,获取数据库数据
stmt.setString(1,username);
ResultSet resultSet = stmt.executeQuery();
if (!resultSet.next()){
req.getRequestDispatcher("/NotExist").forward(req,resp); //如果用户不存在,跳转到用户不存在界面
return;
}
String pwd = resultSet.getString("password"); //获得数据库的密码
if(password.equals(pwd)){
writer.print("登录成功");
HttpSession session = req.getSession();
session.setAttribute("user",username); //保存用户名信息
session.setMaxInactiveInterval(1000);
req.getRequestDispatcher("/home").forward(req,resp); //跳转到HomeServletjava程序
}
else{
System.out.println("密码错误"); //密码错误
req.getRequestDispatcher("/PsdError").forward(req,resp); //跳转到密码错误界面
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
6.注册的jsp页面(页面中的背景图片大家自己可以随便找找)
<%--
Created by IntelliJ IDEA.
User: 86187
Date: 2020/6/26
Time: 20:54
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
注册
7.注册功能的实现
package com.gl;
import com.person.Student;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/register")
public class Register extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username"); //获取注册输入的用户名
String psd = req.getParameter("password"); //获取注册输入的密码
Student.add(username,psd); //调用Student的Add()方法,添加到数据库
resp.sendRedirect(req.getContextPath() + "/login.jsp");
//重定向,这时如果用转换,浏览器的地址是register程序,如果刷新,会重新再执行一次register程序,数据库会添加相同的数据
//重定向就很好的解决了这一问题,浏览器的地址会变为登陆界面的jsp形式!防止刷新再次执行servlet程序!
}
}
8.登录成功的jsp页面
如果未登录直接访问会跳转到登录界面
<%--
Created by IntelliJ IDEA.
User: 86187
Date: 2020/6/24
Time: 15:11
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
神的网站
您的账号未登录!
请您先登录
<%
response.setHeader("refresh", "1 ;url=login.jsp"); //在当前页面停顿1秒,然后跳转到登录界面
%>
<%-- ${username}
--%>
欢迎来到${sessionScope.user}的世界!
您已登录成功!
9.登录成功的Sevlet程序
package com.gl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet("/home")
public class HomeServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = (String)req.getSession().getAttribute("user"); //获取在登录界面输入的username,在LoginServlet有保存
req.setAttribute("username",username);
req.getRequestDispatcher("home.jsp").forward(req,resp); //跳转到HomeServlet程序
}
}
10.登录时用户不存在的jsp页面
<%--
Created by IntelliJ IDEA.
User: 86187
Date: 2020/6/26
Time: 15:28
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
用户不存在
输入的用户不存在
<%
response.setHeader("refresh", "1 ;url=login.jsp"); //在当前页面停顿1秒,然后跳转到登录界面
%>
11.用户不存在的Sevlet程序
package com.gl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/NotExist")
public class NotExistServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("NotExist.jsp").forward(req,resp); //用户不存在跳转到用户不存在界面
}
}
12.登录时密码错误的jsp页面
<%--
Created by IntelliJ IDEA.
User: 86187
Date: 2020/6/26
Time: 15:33
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>密码错误</title>
<style>
h1{
text-align: center;
margin-top: 100px;
color: bisque;
}
.x1{
background-color:lightskyblue;
border-radius: 20%;
width: 200px;
height: 30px;
margin-left: 650px;
font-size: 18px;
}
body{
background-size: 1540px 720px;
}
</style>
</head>
<body background="Image/x2.jpg">
<h1>你输入的密码错误</h1>
<%
response.setHeader("refresh", "1 ;url=login.jsp"); //在当前页面停顿1秒,然后跳转到登录界面
%>
<from >
<input class="x1" type="submit" name="Submit" value="返回登录界面" onclick=window.open("http://localhost:8080/Servlet_war_exploded/login.jsp")>
</from>
</body>
</html>
13.密码错误的Sevlet程序
package com.gl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/PsdError")
public class PadErrorServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("PsdError.jsp").forward(req,resp); //密码错误跳转到密码错误界面!
}
}
登录成功后有修改密码的功能
14.修改密码的Servlet程序
package com.gl;
import com.person.Student;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
@WebServlet("/modifymessage")
public class ModifyMessage extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String psd = req.getParameter("password"); //获取用户修改的用户密码
String username =(String)req.getSession().getAttribute("user"); //获取用户名
Student.Update(psd,username);
resp.sendRedirect(req.getContextPath() + "/login.jsp");
//重定向,这时如果用转换,浏览器的地址是modifymessage程序,如果刷新,会重新再执行一次modifymessage程序,数据库会添加相同的数据
//重定向就很好的解决了这一问题,浏览器的地址会变为登陆界面的jsp形式!防止刷新再次执行servlet程序!
}
}
15.修改密码的jsp页面
<%--
Created by IntelliJ IDEA.
User: 86187
Date: 2020/6/26
Time: 19:35
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
修改密码
这就完成了一个简单的登录和注册的功能!