首页 前端知识 通过Java Script 和Servlet实现简易的登录注册页面

通过Java Script 和Servlet实现简易的登录注册页面

2024-08-07 00:08:05 前端知识 前端哥 563 423 我要收藏

这是一道大学Web开发技术课程中的课程作业:

实现一个简单的企业会员注册和登录功能。具体要求如下: (1)注册页面register.html包括用户名、密码、姓名、性别、邮箱、手机号等信息,要求对所有字段进行非空判断,密码为数字、字母和特殊字符的组合(不少于8位),对邮箱和手机号进行有效性判断,否则弹出对话框进行提示。注册信息处理由映射地址为register.do的RegisterServlet.java进行处理,将所有用户注册的登录名、密码、姓名、性别、邮箱、手机号等信息按行保存到userinfo.txt中,每个字段用“|”分隔,要求将密码以SHA256加密(可用JDK自带的java.security.MessageDigest实现)后写入文件,userinfo.txt文件格式如下: 如果当前注册的用户名不与已注册的用户名冲突,则提示“注册成功”,5秒后自动跳转或有超链接至登录页面,否则提示“你的用户名已被注册,请返回重新注册”。

(2)登录页面login.html。用户登录页面需判断用户名或密码是否为空,登录成功与否由映射地址为login.do的LoginServlet.java处理,该Servlet从userinfo.txt查询判断用户名与密码是否一致,如果一致则跳转至欢迎页面welcome.html提示“登录成功!”,否则跳转至失败页面failed.html提示“用户名或密码错误,请重新登录”,其中“重新登录”为超链接,可以跳转至登录页面login.html。

userinfo.txt的格式:

 登录界面:注册界面:

 以下是基于本题的代码,html主题模块不提供注释,Java Script和Servlet提供注释:

        //登录界面
<html>
	<head>
		<meta charset="UTF-8">
		<title>51job的会员登陆界面</title>
		<script language="JavaScript" type="text/javascript">
			function custCheck() {
			   var userName = document.getElementById("userName");
			   var password = document.getElementById("password");
        //用户名判空
			   if (userName.value == "" || userName.value == "请输入用户名") {
				  alert("用户名不能为空!");
				  return false;
        //密码判空
			   } else if (password.value == "" || password.value == "请输入密码") {
				  alert("密码不能为空!");
				  return false;
			   }
			   return true;
			}
		</script>
	</head>
	<style>
		.div1{
			position: fixed;
			width: 200px;
			height: 150px;
			top:30%;
			left: 43%;
			/*margin-top: -75px;*/
			/*margin-left:-100px ;*/
		}
	</style>
	<body>
		<div class="div1">
			<form action="login.do" method="post" onsubmit="return custCheck()">
				<table style="border: 1px solid #0000FF;" rules=none cellspacing=0  width=340 align=center >
					<tr height=40>
						<td colspan=2>
							<h2 align=center>
								<font color=blue>企业会员登录</font>
							</h2>
						</td>
					</tr>
					<tr height=40>
						<td height=40 align=right width=80>用&nbsp;&nbsp;&nbsp;户&nbsp;&nbsp;&nbsp;名</td>
						<td width=240><input style="width: 95%; height: 25px;"
							type="text" value="请输入用户名"
							onFocus="if(value==defaultValue){value='';this.style.color='#000'}"
							onBlur="if(!value){value=defaultValue; this.style.color='#999'}"
							style="color: #999" name="userName" id="userName"></td>
					</tr>
					<tr height=40>
						<td height=40 align=right width=80>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码</td>
						<td width=240><input style="width: 95%; height: 25px;"
							type="text" value="请输入密码"
							onFocus="if(value==defaultValue){value='';this.style.color='#000'}"
							onBlur="if(!value){value=defaultValue; this.style.color='#999'}"
							style="color: #999" name="password" id="password"></td>
					</tr>
					<tr height=40>
						<td height=40 colspan=2 align=center>
							<input type="image" src="login.png" name="img" />
						</td>
					</tr>
					<tr height=40>
						<td height=40 colspan=2 align=right>没有帐号?
							<a href="register.html" style='text-decoration: none;'>
							<font color=red>免费注册&nbsp;&nbsp;&nbsp;</font></a>
						</td>
					</tr>
				</table>
			</form>
		</div>
	</body>
</html>
        //注册界面
<html>
<head>
    <meta charset="UTF-8">
    <title>51job的会员登陆界面</title>
</head>
<script language="JavaScript" type="text/javascript">
    function custCheck() {
        var userName = document.getElementById("userName");
        var password = document.getElementById("password");
        var name=document.getElementById("name");
        var mail=document.getElementById("mail");
        var tel=document.getElementById("tel");
        var sex=document.getElementsByName("sex");
        var pattern=/(^[0-9]{3,4}\-[0-9]{3,8}$)|(^[0-9]{3,8}$)|(^[0−9]3,4[0-9]{3,8}$)|(^0{0,1}13[0-9]{9}$)/; //验证电话号码的正则表达式
        var reg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*?[#?!@$%^&*.-]).{8,}$/;//对于密码格式的正则表达式,需求为数字,大小写字母和特殊字符

        var emailRegExp=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;//验证邮箱的正则表达式
        //判空和手机号、邮箱、密码的合法性判别
        if (userName.value == "" || userName.value == "请输入您的用户名") {
            alert("用户名不能为空!");
            return false;
        } else if (password.value == "" || password.value == "请输入您的密码") {
            alert("密码不能为空!");
            return false;
        }else if (name.value == "" || name.value == "请输入您的姓名"){
            alert("姓名不能为空!");
            return false;
        }else if(mail.value == "" || mail.value == "请输入您的邮箱"){
            alert("邮箱不能为空!");
            return false;
        }else if (tel.value == "" || tel.value == "请输入您的手机号"){
            alert("手机号不能为空!");
            return false;
        }else if(!emailRegExp.test(mail.value)){
            alert("邮箱格式不合法");
            return false;
        }else if(!pattern.test(tel.value.replace(/\s+/g,'').replace(/-/g,'')) ){
            alert("手机号不合法");
            return  false;
        }else if(!reg.test(password.value)){
            alert("密码为数字、大小写字母和特殊字符的组合(不少于8位)");
            return false;
        }
        //试验代码
        // for(var i=0;i<sex.length;i++){
        //     if(sex[i].checked==true){
        //         break;
        //     }
        //     if(i==sex.length-1){
        //         alert("性别不能为空!");
        //         return false;
        //     }
        // }
        if(sex[0].checked != true && sex[1].checked != true){
            alert("性别不能为空!");
            return false;
        }
        return true;
    }
</script>
<style>
    .div1{
        position: fixed;
        width: 200px;
        height: 150px;
        top:30%;
        left: 43%;
    }
</style>
<body>
<div class="div1">
    <form action="register.do" method="post" onsubmit="return custCheck()">
        <table style="border: 1px solid #0000FF;" rules=none cellspacing=0  width=340 align=center >
            <tr height=40>
                <td colspan=2>
                    <h2 align=center>
                        <font color=blue>用户注册</font>
                    </h2>
                </td>
            </tr>
            <tr height=40>
                <td height=40 align=right width=80>用&nbsp;&nbsp;&nbsp;户&nbsp;&nbsp;&nbsp;名</td>
                <td width=240><input style="width: 95%; height: 25px;"
                                     type="text" value="请输入您的用户名"
                                     onFocus="if(value==defaultValue){value='';this.style.color='#000'}"
                                     onBlur="if(!value){value=defaultValue; this.style.color='#999'}"
                                     style="color: #999" name="userName" id="userName"></td>
            </tr>
            <tr height=40>
                <td height=40 align=right width=80>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码</td>
                <td width=240><input style="width: 95%; height: 25px;"
                                     type="text" value="请输入您的密码"
                                     onFocus="if(value==defaultValue){value='';this.style.color='#000'}"
                                     onBlur="if(!value){value=defaultValue; this.style.color='#999'}"
                                     style="color: #999" name="password" id="password"></td>
            </tr>
            <tr height=40>
                <td height=40 align=right width=80>姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名</td>
                <td width=240><input style="width: 95%; height: 25px;"
                                     type="text" value="请输入您的姓名"
                                     onFocus="if(value==defaultValue){value='';this.style.color='#000'}"
                                     onBlur="if(!value){value=defaultValue; this.style.color='#999'}"
                                     style="color: #999" name="name" id="name"></td>
            </tr>
            <tr height=40>
                <td height=40 align=right width=80>性&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;别</td>
                <td>
                    <div>
                        <input type="radio" name="sex" value="男" >男
                        <input type="radio" name="sex" value="女" >女
                    </div>
                </td>
            </tr>
            <tr height=40>
                <td height=40 align=right width=80>邮&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;箱</td>
                <td width=240><input style="width: 95%; height: 25px;"
                                     type="text" value="请输入您的邮箱"
                                     onFocus="if(value==defaultValue){value='';this.style.color='#000'}"
                                     onBlur="if(!value){value=defaultValue; this.style.color='#999'}"
                                     style="color: #999" name="mail" id="mail"></td>
            </tr>
            <tr height=40>
                <td height=40 align=right width=80>手&nbsp;&nbsp;&nbsp;机&nbsp;&nbsp;&nbsp;号</td>
                <td width=240><input style="width: 95%; height: 25px;"
                                     type="text" value="请输入您的手机号"
                                     onFocus="if(value==defaultValue){value='';this.style.color='#000'}"
                                     onBlur="if(!value){value=defaultValue; this.style.color='#999'}"
                                     style="color: #999" name="tel" id="tel"></td>
            </tr>
            <tr height=40>
                <td height=40 colspan=2 align=center>
                    <input type="image" src="login.png" name="img" />
                </td>
            </tr>
        </table>
    </form>
</div>
</body>
</html>

以下是两个主体的Servlet,具体跳转界面不提供:

RegisterServlet:

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;
import org.apache.commons.codec.binary.Hex;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String userName=request.getParameter("userName");
        String password=request.getParameter("password");
        String name=request.getParameter("name");
        String mail=request.getParameter("mail");
        String tel=request.getParameter("tel");
        String[] sex=request.getParameterValues("sex");

        PrintWriter out=response.getWriter();
        out.println("<html><head>");
        out.println("<title>注册</title>");
        out.println("</head><body>");
        out.println("<h4>注册中……</h4>");
        out.println("</body></html>");

        File file = new File("C:/Users/16287/IdeaProjects/登录注册/src/userinfo.txt");
        InputStreamReader isr = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(isr);
        //利用MessageDigest进行的SHA256加密
        String temp;
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");

            byte[] hash = messageDigest.digest(password.getBytes("UTF-8"));
            
            encodeStr = Hex.encodeHexString(hash);//利用了Apache工具包里的Hex进制转换函数
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        boolean judge;
        judge=true;
        while((temp=br.readLine())!=null){
            String s[]=temp.split("\\|");
            if(userName.equals(s[0])){
                judge=false;
                response.setHeader("Refresh","3;URL=regfailed.html");//注册失败跳转
            }
        }
        if(judge){
            BufferedWriter bw= new BufferedWriter(new FileWriter(file, true));
            String content;
            content=userName+"|"+encodeStr+"|"+name+"|"+sex[0]+"|"+mail+"|"+tel;//写入userinfo.txt的字符串
            bw.write(content);
            bw.newLine();
            bw.close();
            response.setHeader("Refresh","3;URL=refresh.html");//注册成功跳转登录页面的中转网站
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

LoginServlet:

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out=response.getWriter();
        out.println("<html><head>");
        out.println("<title>登录</title>");
        out.println("</head><body>");
        out.println("<h4>登录中……</h4>");
        out.println("</body></html>");

        String userName=request.getParameter("userName");
        String password=request.getParameter("password");
        String temp;
        MessageDigest messageDigest;
        String encodeStr = "";
        File file = new File("C:/Users/16287/IdeaProjects/登录注册/src/userinfo.txt");
        InputStreamReader isr = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(isr);
        //通过直接对输入密码加密和userinfo.txt内部的已加密代码的比较判断密码输入是否正确
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");

            byte[] hash = messageDigest.digest(password.getBytes("UTF-8"));

            encodeStr = Hex.encodeHexString(hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        while((temp=br.readLine())!=null){
            String s[]=temp.split("\\|");
            if(userName.equals(s[0])){
                if(encodeStr.equals(s[1])){
                    response.setHeader("Refresh","3,welcome.html");//登录成功,进入welcome界面
                }else{
                    response.setHeader("Refresh","3,failed.html");//登录失败,提示重新登录
                }
            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}

具体实现界面不具备提供,题目的所有要求已经完成,因为使用了web4.0所以不提供非注释映射,web.xml没有进行解释,如有需要可以自行进行。

转载请注明出处或者链接地址:https://www.qianduange.cn//article/14944.html
标签
servlettomcat
评论
发布的文章

前端-axios应用在html文件

2024-08-15 23:08:39

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!