设计注册页面,并对输入的值进行一个简单的初步判断。
<%-- Created by IntelliJ IDEA. User: 龚涵彬 Date: 2024/2/2 Time: 19:52 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>账号注册</title> </head> <body> <h1>注册</h1> <div style="text-align: center"> <form method="post" id="register" action="register-servlet"> 用户名:<input type="text" name="nameid" id="nameid"><br><br>  密码:<input type="password" name="pwd1" id="pwd1"><br><br> 再输入一次密码:<input type="password" name="pwd2" id="pwd2">    <br><br> <span id="msg" style="font-size: 12px;color:red">${msg}</span><br><br> <button type="button" id="btm">注册</button> </form> <script> document.getElementById("btm").addEventListener("click",function () { var nameid=document.getElementById("nameid").value; var pwd1=document.getElementById("pwd1").value; var pwd2=document.getElementById("pwd2").value; if(!is(nameid)) { document.getElementById('msg').innerHTML="您要注册的用户名不能为空"; return; } if(!is(pwd1)) { document.getElementById('msg').innerHTML="您的密码不能为空"; return; } if(!is(pwd2)) { document.getElementById('msg').innerHTML="您第二次密码输入的不能为空"; return; } if(pwd1!==pwd2) { document.getElementById('msg').innerHTML="您两次密码输入不一致"; return; } var a=confirm("确认注册嘛?"); if(!a) { return; } else document.getElementById("register").submit(); }) function is(s) { if (s.length==0||s.trim()=="") return false; else return true; } </script> </div> </body> </html>
然后在servlet里进行数据库操作,并返回一个消息到我们的登录界面。
package com.example.demo; import bean.Base_InformationBean; import bean.InfoDAO; 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 java.io.IOException; import java.io.PrintWriter; @WebServlet(value="/register-servlet") public class registerServlet extends HttpServlet { private String code; private String password; private Base_InformationBean hhh; public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { code=request.getParameter("nameid"); password=request.getParameter("pwd1"); hhh=new Base_InformationBean(); hhh.setCode(code); hhh.setPassword(password); new InfoDAO().register(hhh); request.setAttribute("msg","注册完成"); try { request.getRequestDispatcher("index.jsp").forward(request,response); } catch (ServletException e) { throw new RuntimeException(e); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentType("text/html"); doGet(request,response); } }
这样我们就完成了用户的注册操作。
标签:01,return,22,request,2024,getElementById,import,document,servlet From: https://www.cnblogs.com/zhenaifen/p/17980763