0312 注册,发送邮件
通过观察users表中的数据发现了state字段和code字段,我们一开始注册的时候先将state字段存入0,封装code字段是36位不重复的字母数字组合,存入到数据中,当用户注册的时候获取用户的邮箱地址,并将用户的code值通过以邮件的方式发送给用户的邮箱中,客户通过点击邮箱中内容点击链接去激活(就是通过code值将state值改为1),再登录的时候验证一下state值是否为1,为1才能登录成功
邮件发送我们用到了 mail.jar文件还有MailUtils工具类
MailUtils.java
public class MailUtils { //授权密码: //QLFNLREIXDATBGKM public static void sendMail(String email, String emailMsg) throws AddressException, MessagingException { // 1.创建一个程序与邮件服务器会话对象 Session Properties props = new Properties(); props.setProperty("mail.transport.protocol", "SMTP"); props.setProperty("mail.host", "smtp.126.com"); props.setProperty("mail.smtp.auth", "true");// 指定验证为true // 创建验证器 Authenticator auth = new Authenticator() { public PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("gongxue1127", "QLFNLREIXDATBGKM"); } }; Session session = Session.getInstance(props, auth); // 2.创建一个Message,它相当于是邮件内容 Message message = new MimeMessage(session); message.setFrom(new InternetAddress("gongxue1127@126.com")); // 设置发送者 message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者 message.setSubject("用户激活"); // message.setText("这是一封激活邮件,请<a href='#'>点击</a>"); message.setContent(emailMsg, "text/html;charset=utf-8"); // 3.创建 Transport用于将邮件发送 Transport.send(message); } }
MailUtils工具类中封装了发送者的邮箱地址,封装了一个sendMail方法 通过传入目的邮箱地址和邮箱内容去发送。
注册页面 register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head></head> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>会员注册</title> <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" /> <script src="js/jquery-1.11.3.min.js" type="text/javascript"></script> <script src="js/bootstrap.min.js" type="text/javascript"></script> <!-- 引入自定义css文件 style.css --> <link rel="stylesheet" href="css/style.css" type="text/css" /> <style> body { margin-top: 20px; margin: 0 auto; } .carousel-inner .item img { width: 100%; height: 300px; } font { color: #3164af; font-size: 18px; font-weight: normal; padding: 0 10px; } .error{ color:red; } </style> <script type="text/javascript" src="/Market/js/jquery.validate.min.js"></script> <script type="text/javascript"> $(function(){ $(".form-horizontal").validate( { rules:{ "username":{required:true}, "password":{required:true,rangelength:[6,10]}, "repassword":{ required:true, rangelength:[6,10], equalTo:"#password" }, "email":{required:true,email:true}, "name":{required:true}, "sex":{required:true}, "birthday":{required:true} }, messages:{ "username":{required:"用户名不能为空!"}, "password":{required:"密码不能为空!",rangelength:"密码为6~10位"}, "repassword":{ required:"密码不能为空!", rangelength:"密码为6~10位", equalTo:"两次密码不一致!" }, "email":{required:"邮箱地址不能为空!",email:"邮箱格式不正确"}, "name":{required:"姓名不能为空!"}, "sex":{required:"性别不能为空!"}, "birthday":{required:"日期不能为空!"} } } ); }) </script> </head> <body> <!-- 引入header.jsp --> <jsp:include page="/header.jsp"></jsp:include> <div class="container" style="width: 100%; background: url('image/regist_bg.jpg');"> <div class="row"> <div class="col-md-2"></div> <div class="col-md-8" style="background: #fff; padding: 40px 80px; margin: 30px; border: 7px solid #ccc;"> <font>会员注册</font>USER REGISTER <form class="form-horizontal" style="margin-top: 5px;" action="/Market/RegisterServlet" method="post"> <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="password" placeholder="请输入密码" 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="repassword"> </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" 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="name"> </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="sex1" value="male"> 男 </label> <label class="radio-inline"> <input type="radio" name="sex" id="sex2" value="female"> 女 </label> <label for="sex" generated="true" class="error" style="display:none">性别不能为空!</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" name="birthday"> </div> </div> <div class="form-group"> <label for="date" class="col-sm-2 control-label">验证码</label> <div class="col-sm-3"> <input type="text" class="form-control" name="checkCode"> </div> <div class="col-sm-2"> <img src="/Market/CheckImgServlet" onclick="check(this)" /> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" width="100" value="注册" name="submit" style="background: url('./images/register.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0); height: 35px; width: 100px; color: white;"> </div> </div> </form> </div> <div class="col-md-2"></div> </div> </div> <!-- 引入footer.jsp --> <jsp:include page="/footer.jsp"></jsp:include> </body> <script type="text/javascript"> function check(obj){ obj.src="/Market/CheckImgServlet?timer="+new Date().getTime(); } </script> </html>
登录页面login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>会员登录</title> <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" /> <script src="js/jquery-1.11.3.min.js" type="text/javascript"></script> <script src="js/bootstrap.min.js" type="text/javascript"></script> <!-- 引入自定义css文件 style.css --> <link rel="stylesheet" href="css/style.css" type="text/css" /> <style> body { margin-top: 20px; margin: 0 auto; } .carousel-inner .item img { width: 100%; height: 300px; } .container .row div { /* position:relative; float:left; */ } font { color: #666; font-size: 22px; font-weight: normal; padding-right: 17px; } </style> </head> <body> <!-- 引入header.jsp --> <jsp:include page="/header.jsp"></jsp:include> <div class="container" style="width: 100%; height: 460px; background: #FF2C4C url('images/loginbg.jpg') no-repeat;"> <div class="row"> <div class="col-md-7"> <!--<img src="./image/login.jpg" width="500" height="330" alt="会员登录" title="会员登录">--> </div> <div class="col-md-5"> <div style="width: 440px; border: 1px solid #E7E7E7; padding: 20px 0 20px 30px; border-radius: 5px; margin-top: 60px; background: #fff;"> <font>会员登录</font>USER LOGIN <div> </div> <form class="form-horizontal" action="/Market/LoginServlet" method="post"> <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" name="username" placeholder="请输入用户名"> </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" name="password" placeholder="请输入密码"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">验证码</label> <div class="col-sm-3"> <input type="text" class="form-control" id="inputPassword3" placeholder="请输入验证码"> </div> <div class="col-sm-3"> <img src="/Market/CheckImgServlet" onclick="check(this)"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <div class="checkbox"> <label> <input type="checkbox"> 自动登录 </label> <label> <input type="checkbox"> 记住用户名 </label> </div> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <input type="submit" width="100" value="登录" name="submit" style="background: url('./images/login.gif') no-repeat scroll 0 0 rgba(0, 0, 0, 0); height: 35px; width: 100px; color: white;"> </div> </div> </form> </div> </div> </div> </div> <!-- 引入footer.jsp --> <jsp:include page="/footer.jsp"></jsp:include> </body> <script type="text/javascript"> function check(obj){ obj.src="/Market/CheckImgServlet?timer="+new Date().getTime(); } </script> </html>
注册regiterServlet.java
public class RegisterServlet extends HttpServlet { private UsersService usersService=new UsersService(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决请求乱码 request.setCharacterEncoding("UTF-8"); //获取请求参数的map集合 Map<String, String[]> map=request.getParameterMap(); Users users=new Users(); //日期转换类 DateConverter converter=new DateConverter(); //设置转化规则 字符串-->转日期规则 converter.setPattern("yyyy-MM-dd"); //转化 ConvertUtils.register(converter, Date.class); //beanutils 的populate方法 将集合中map中key和user对象中属性一一对应,进行封装 try { BeanUtils.populate(users, map); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } //封装uid(36位字母数字组合 不重复) users.setUid(UUID.randomUUID().toString()); //封装状态和状态码 users.setState(0); String code=UUID.randomUUID().toString(); users.setCode(code); int row=usersService.register(users); if(row>0){ //发送激活邮件给用户 String msg="恭喜你注册成功!请点击下方链接激活账户!<a href='http://localhost:8080/Market/ActiveServlet?code="+code+"'>http://localhost:8080/Market/ActiveServlet?code="+code+"</a>"; //发送邮件 try { MailUtils.sendMail(users.getEmail(), msg); } catch (AddressException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessagingException e) { // TODO Auto-generated catch block e.printStackTrace(); } //注册成功跳转到登录 response.sendRedirect(request.getContextPath()+"/login.jsp"); }else{ response.sendRedirect(request.getContextPath()+"/register.jsp"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
登录 loginServlet.java
public class LoginServlet extends HttpServlet { private UsersService usersService=new UsersService(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决请求乱码 request.setCharacterEncoding("UTF-8"); //获取表单信息 String username=request.getParameter("username"); String password=request.getParameter("password"); int count=usersService.login(username, password); if(count>0){ int state=usersService.checkstate(username, password); if(state==1){ response.sendRedirect(request.getContextPath()+"/index.jsp"); }else{ response.sendRedirect(request.getContextPath()+"/login.jsp"); } }else{ response.sendRedirect(request.getContextPath()+"/login.jsp"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
激活ActiveServlet.java
public class ActiveServlet extends HttpServlet { private UsersService usersService=new UsersService(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //解决请求乱码 request.setCharacterEncoding("UTF-8"); //获取激活码信息 String code=request.getParameter("code"); int row=usersService.updateState(code); if(row>0){ response.sendRedirect(request.getContextPath()+"/login.jsp"); }else{ response.sendRedirect(request.getContextPath()+"/register.jsp"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
Service层
public class UsersService { private UsersDao usersDao=new UsersDao(); public int register(Users users){ int row=0; try { row=usersDao.register(users); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return row; } //登录 public int login(String username,String password){ int count=0; try { count=usersDao.login(username, password); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return count; } //激活 public int updateState(String code){ int row=0; try { row=usersDao.updateState(code); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return row; } //判定是否激活 public int checkstate(String username,String password){ int state=0; try { state=usersDao.checkstate(username, password); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return state; } }
usersDao.java
public class UsersDao { //注册 public int register(Users users) throws SQLException{ //获取链接对象 Connection conn=JDBCUtils.getConn(); //获取sql语句 String sql="insert into users(uid,username,password,name,email,birthday,sex,state,code) values(?,?,?,?,?,?,?,?,?)"; PreparedStatement pst=conn.prepareStatement(sql); //赋值 pst.setString(1, users.getUid()); pst.setString(2, users.getUsername()); pst.setString(3, users.getPassword()); pst.setString(4, users.getName()); pst.setString(5, users.getEmail()); pst.setDate(6, new Date(users.getBirthday().getTime())); pst.setString(7, users.getSex()); pst.setInt(8, users.getState()); pst.setString(9, users.getCode()); int row=pst.executeUpdate(); //释放资源 JDBCUtils.close(conn, pst); return row; } //登录 public int login(String username,String password) throws SQLException{ //获取链接对象 Connection conn=JDBCUtils.getConn(); //获取sql语句 String sql="select count(*) from users where username=? and password=?"; PreparedStatement pst=conn.prepareStatement(sql); pst.setString(1, username); pst.setString(2, password); ResultSet rs=pst.executeQuery(); int count=0; while(rs.next()){ count=rs.getInt(1); } JDBCUtils.close(conn, pst, rs); return count; } //激活 public int updateState(String code) throws SQLException{ //获取链接对象 Connection conn=JDBCUtils.getConn(); //获取sql语句 String sql="update users set state=1 where code=?"; PreparedStatement pst=conn.prepareStatement(sql); pst.setString(1, code); int row=pst.executeUpdate(); JDBCUtils.close(conn, pst); return row; } //判定是否激活 public int checkstate(String username,String password) throws SQLException{ //获取链接对象 Connection conn=JDBCUtils.getConn(); //获取sql语句 String sql="select state from users where username=? and password=?"; PreparedStatement pst=conn.prepareStatement(sql); pst.setString(1, username); pst.setString(2, password); ResultSet rs=pst.executeQuery(); int state=0; while(rs.next()){ state=rs.getInt(1); } JDBCUtils.close(conn, pst, rs); return state; } }
注册流程,当用户在注册页面中输入信息,点击提交,会将信息提交到registerServlet-->Service -->dao层中走注册流程,注册成功会将该用户的注册信息的code值通过邮件的方式发送到用户注册时的邮箱中,用户通过点击邮箱内容中的链接跳转到 ActiveServlet中,通过获取到code值,又走Service -->dao层流程将该code值所对应的state值改为1,然后就跳转到login.jsp登录界面,当用户输入用户名和密码,点击登录就会将数据提交到loginServlet中通过获取用户名和密码 然后走Service -->dao层流程查到所对应的state值判定是否是1,如果不是就不能登录,如果是就登陆成功跳转到主页index.jsp(当然在注册时没有做重名用户注册问题,还有在登录的时候还要先判定用户名和密码是否存在)
在用户注册页面中,需要用户输入自己的注册信息,那我们需要对这么内容有一个规则判定 这里我们运用到了jquery插件,首先我们需要将jquery.validate.js导入到项目中编写js代码对表单进行验证
格式:
首先要确定是对哪个表单进行验证
$("form表单的选择器").validate(json数据格式);
json数据格式:
rules:{
表单项name值:校验规则,
表单项name值:校验规则... ...
},
messages:{
表单项name值:错误提示信息,
表单项name值:错误提示信息... ...
}
}
常用属性
如果所显示的错误信息不在你想显示的位置 jquery验证插件会自动帮助我们控制它的显示与隐藏
例:<lable for="html元素name值" class="error" style="display:none">错误信息</lable>
代码展示
<script type="text/javascript" src="/Market/js/jquery.validate.min.js"></script> <script type="text/javascript"> $(function(){ $(".form-horizontal").validate( { rules:{ "username":{required:true}, "password":{required:true,rangelength:[6,10]}, "repassword":{ required:true, rangelength:[6,10], equalTo:"#password" }, "email":{required:true,email:true}, "name":{required:true}, "sex":{required:true}, "birthday":{required:true} }, messages:{ "username":{required:"用户名不能为空!"}, "password":{required:"密码不能为空!",rangelength:"密码为6~10位"}, "repassword":{ required:"密码不能为空!", rangelength:"密码为6~10位", equalTo:"两次密码不一致!" }, "email":{required:"邮箱地址不能为空!",email:"邮箱格式不正确"}, "name":{required:"姓名不能为空!"}, "sex":{required:"性别不能为空!"}, "birthday":{required:"日期不能为空!"} } } ); })