How to quickly realize mailbox registration (project case)

Speaking of Web projects, anyone who has learned Java must have done a lot. Today, I will introduce a commonly used function-mailbox registration.

This function is mainly aimed at some online systems for the general public. For example, when we usually register some websites, we need to provide an email address first, and then the system will automatically send an email to the registered email address, which can only be used after the activation verification is passed.

Project Introduction

We first set up the project, the framework and database are free, the demonstration system uses Servlet, and the database uses Mysql.

The project structure diagram is as follows:

Insert picture description here

Mysql database

Insert picture description here
Demo operation

Insert picture description here

Implementation

In order to simplify the operation, the project only has a registration function. Right-click run as on the register page, fill in the registration information after startup, jump to login after successful registration, and jump to msg if it fails. The specific details of the operation are in the Servlet, which we will introduce in detail below.

Create a Form on the Jsp page and fill in the registration information:

<div class="col-md-12" style="width:100%;background:url('${pageContext.request.contextPath}/images/regist_bg.jpg');">
			<div class="col-md-2"></div>
			<div class="col-md-8" style="background:#fff;padding:40px 80px;margin:30px 30px 20px 45px ;border:7px solid #ccc;width:70%">
				<font>会员注册</font>USER REGISTER
				<form class="form-horizontal" name="f_reg" style="margin-top:5px;" method="post" action="${pageContext.request.contextPath}/register" onsubmit="return checkFrom()">
					 <div class="form-group">
					    <label for="username" class="col-sm-2 control-label">用户名</label>
					    <div class="col-sm-6">
					      <input type="text" class="form-control" id="username" placeholder="请输入用户名  字母开头后跟数字或下划线" name="username">
					    </div>
					  </div>
					   <div class="form-group">
					    <label for="inputPassword3" class="col-sm-2 control-label">密码</label>
					    <div class="col-sm-6">
					      <input type="password" class="form-control" id="inputPassword3" placeholder="请输入密码,至少6位" name="password">
					    </div>
					  </div>
					   <div class="form-group">
					    <label for="confirmpwd" class="col-sm-2 control-label">确认密码</label>
					    <div class="col-sm-6">
					      <input type="password" class="form-control" id="confirmpwd" placeholder="请输入确认密码" name="password2">
					    </div>
					  </div>
					  <div class="form-group">
					    <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
					    <div class="col-sm-6">
					      <input type="email" class="form-control" id="inputEmail3" placeholder="Email  如 [email protected]" name="email">
					    </div>
					  </div>
					 <div class="form-group">
					    <label for="usercaption" class="col-sm-2 control-label">姓名</label>
					    <div class="col-sm-6">
					      <input type="text" class="form-control" id="usercaption" placeholder="请输入姓名" name="realname">
					    </div>
					  </div>
					  <div class="form-group opt">  
					  <label for="inlineRadio1" class="col-sm-2 control-label">性别</label>  
					  <div class="col-sm-6">
					    <label class="radio-inline">
					  <input type="radio" name="sex" id="inlineRadio1" value="男" checked></label>
					<label class="radio-inline">
					  <input type="radio" name="sex" id="inlineRadio2" value="女"></label>
					</div>
					  </div>		
					  <div class="form-group">
					    <label for="date" class="col-sm-2 control-label">出生日期</label>
					    <div class="col-sm-6">
					      <input type="date" class="form-control" placeholder="请输入日期" onclick="laydate()"  name="birthday">		      
					    </div>
					  </div>
					  <div class="form-group">
					    <div class="col-sm-offset-2 col-sm-10">
					      <input type="submit"  width="100" value="注册" name="submit" border="0"
						    style="background: url('${pageContext.request.contextPath}/images/register.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0);
						    height:35px;width:100px;color:white;">
					    </div>
					  </div>
				</form>
			</div>

In Servlet, we need to use the 163 mailbox as the sender, and configure the personal mailbox and password in it. The code:

@SuppressWarnings("serial")
public class RegisterServlet extends HttpServlet {
    
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    		
		String email = request.getParameter("email");
		Map<String, String[]> map = request.getParameterMap();
		//2、封装成User对象
		User u = new User();
		MyBeanUtils.populate(u, map);
		//3、调用Service层完成功能
		UserService us = new UserServiceImpl();
		boolean b = us.insertUser(u);
		try {
    
     
			String from = "你的邮箱"; // 获取发件人 
			String to = email; // 获取收件人 
			String subject = "恭喜你,注册成功"; // 获取邮件主题 
			String messageText = "欢迎你注册本网站,你现在已经注册成功,请返回到登录界面登录,更多优惠,更多精彩!"; // 获取邮件内容 
			String ddd = "邮箱密码"; // 获取发件人邮箱密码 
			String mailserver = "smtp.163.com"; // 指定SMTP服务器的主机名 
			// 建立邮件会话 
			Properties props = new Properties(); 
			props.put("http.proxySet","true");//设置代理主机参数  
			props.put("http.proxyHost","172.17.18.80");  
			props.put("http.proxyPort","8080");  
			props.put("mail.smtp.host", mailserver); // 指定SMTP协议 
			props.put("mail.smtp.auth", "true"); // 指定需要向服务器端提交身份认证 
			Session sess = Session.getInstance(props); // 获取session 
			sess.setDebug(true); // 设置调试标志 
			MimeMessage message = new MimeMessage(sess); // 新建一个消息对象 
			// 设置发件人 
			InternetAddress from_mail = new InternetAddress(from); 
			message.setFrom(from_mail); 
			// 设置收件人 
			InternetAddress to_mail = new InternetAddress(to); 
			message.setRecipient(Message.RecipientType.TO, to_mail); 
			// 设置主题 
			message.setSubject(subject); 
			// 设置内容 
			message.setText(messageText); 
			// 设置发送时间 
			message.setSentDate(new Date()); 
			// 发送邮件 
			message.saveChanges(); // 保证报头域同会话内容保持一致 
			Transport transport = sess.getTransport("smtp"); 
			transport.connect(mailserver, from, ddd); // 建立与邮件服务器之间的连接 
			transport.sendMessage(message, message.getAllRecipients()); // 发送邮件 
			transport.close(); // 关闭与邮件服务器之间的连接 
			//4、响应注册的结果		
			if(b){
    
    				
				request.setAttribute("msg","请到邮箱验证是否注册成功!");
				us.updatestatus(u);
				request.getRequestDispatcher("/jsp/msg.jsp").forward(request, response);
			}else{
    
    
				request.setAttribute("msg","对不起,注册失败,请联系管理员!");
				request.getRequestDispatcher("/jsp/msg.jsp").forward(request, response);
			}
			} catch (Exception e) {
    
     
				request.setAttribute("msg","对不起,注册失败,请检查 邮箱是否正确!");
				request.getRequestDispatcher("/jsp/msg.jsp").forward(request, response);
			} 
	}

If the registration is successful, write it to the database:

public class UserDaoImpl implements UserDao {
    
    
	//DBUtils的核心类,用于执行sql语句的核心对象
	private QueryRunner runner = new  QueryRunner();
	//1、注册用户的方法
	public int insertUser(User u) {
    
    
		//1、编写sql
		String sql = "insert into user values(null,?,?,?,?,?,?,?,null)";
		//2、准备参数与结果集,参数为数组,结果集为int类型的结果
		Object[] parm = {
    
    u.getUsername(),u.getPassword(),u.getRealname(),u.getEmail(),u.getSex(),u.getBirthday(),0};
		int i=0;
		try {
    
    
			//3、获取连接对象,使用QueryRunner对象执行sql语句
			i=runner.update(JDBCUtils.getConnection(), sql, parm);
		} catch (SQLException e) {
    
    
			e.printStackTrace();
		}
		return i;
	}
	
	
	public int updatestatus(User u) {
    
    
		//1、编写sql
		QueryRunner qr= new QueryRunner();
		String sql = "update user set status = ? where username = ?";
		try {
    
    
			qr.update(JDBCUtils.getConnection(), sql, 1,u.getUsername());
		} catch (SQLException e) {
    
    
			e.printStackTrace();
		}
		return 1;
	}
	
}

The above is the specific implementation process. If you have any questions, welcome private messages and we will discuss together.

Guess you like

Origin blog.csdn.net/mtyedu/article/details/112767667