JavaWeb使用德鲁伊(略)实现登录、激活码注册(发送激活码到邮箱,点击激活链接后,才能正常登陆)、注册界面

德鲁伊连接池:

https://blog.csdn.net/qq_39773004/article/details/108654255?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522160049868219195188354758%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=160049868219195188354758&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~blog~first_rank_v2~rank_blog_default-2-108654255.pc_v2_rank_blog_default&utm_term=%E5%BE%B7%E9%B2%81%E4%BC%8A&spm=1018.2118.3001.4187

1.1login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登录界面</title>
</head>
<body>
    <form method="post" action="usersController?method=login">
        <div class="right fr">您还不是我们的用户?<a href="${pageContext.request.contextPath}/register.jsp" target="_self">立即注册</a></div>
        <input type="text" name="username" id="username"  placeholder="请输入你的用户名"/>
        <input type="text" name="password" id="password"  placeholder="请输入你的密码"/>
        <input type="submit" value="提交">
    </form>

    <span style="color:red">${msg}</span>
</body>
</html>

1.2registerSuccess.jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link href="css/bootstrap.min.css" rel="stylesheet">
		<script type="text/javascript" src="js/jquery.min.js"></script>
<title>注册成功</title>
</head>
<body>
<form method="post" action="">
	<h1>激活链接</h1>
	<a class="btn btn-danger" href="http://www.hao123.com/mail" target="_blank">立刻激活</a>
</form>
</body>
</html>

1.3message.jsp接收各种信息的jsp

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link href="css/bootstrap.min.css" rel="stylesheet">
		<script type="text/javascript" src="js/jquery.min.js"></script>
		
<link rel="stylesheet" type="text/css" href="css/login.css">

<title>注册成功</title>
</head>
<body>
	<p class="text-info" style="font-size: 20px;">${msg }</p>
	<a class="btn btn-default" href="${pageContext.request.contextPath }/index.jsp" target="_blank">返回主页</a>
</body>
</html>

1.4regiter.jsp

<%--
  Created by IntelliJ IDEA.
  User: 49841
  Date: 2020/9/18
  Time: 11:49
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册页面</title>
</head>
<body>
    <form method="post" action="usersController?method=register">
        <input type="text" name="uname" placeholder="请输入你的用户名"/>
        <input type="text" name="upassword" placeholder="请输入你的密码"/>
        <input type="text" name="uemail" placeholder="请输入你的邮箱"/>
        <input type="text" name="usex" placeholder="请输入你的性别"/>
        <input type="submit" value="提交"/>
    </form>
<%--    <span style="color:red">${msg}</span>--%>
</body>
</html>

2.UsersController(servlet)

public class UserDaoImpl implements UserDao {
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
    //得到叫username的user
    @Override
    public User findUser(String username) throws SQLException {
        String sql = "select u_id as uid,u_name as uname,u_password as upassword,u_email as uemail,u_sex as usex," +
                "u_status as ustatus,u_code as ucode,u_role as urole from user where u_name=?";
        /*User user = qr.query(sql, new BeanHandler<>(User.class), username);
        boolean flag = false;
        if(user!=null&&user.getUpassword().equals(password)){
            flag = true;
        }*/
        return qr.query(sql, new BeanHandler<>(User.class), username);
    }

    //添加注册的数据
    @Override
    public int inserUser(User user) throws SQLException {
        String sql = "insert into user(u_name,u_password,u_sex,u_status,u_email,u_role,u_code) value(?,?,?,?,?,?,?)";
        int i = qr.update(sql, user.getUname(), user.getUpassword(), user.getUsex(), user.getUstatus(), user.getUemail(), user.getUrole(), user.getUcode());
        return i;
    }


    //修改激活码和状态码
    @Override
    public int updataCode(String code) throws SQLException {
        String sql = "update user set u_status=1,u_code=null where u_code=?";
        int i = qr.update(sql, code);
        return i;
    }

    //根据激活码查询状态
    @Override
    public int findStatusByCode(String code) throws SQLException {
        String sql = "select u_status from user where u_code=?";
        Object o = qr.query(sql, new ScalarHandler(), code);
        if(o==null){
            return -1;
        }
        return (Integer)o;
    }


}

2.1UerDao接口

public interface UserDao {
    public User findUser(String username) throws SQLException;
    public int inserUser(User user) throws SQLException;
    public int updataCode(String code) throws SQLException;
    public int findStatusByCode(String code) throws SQLException;
}

2.2UserDaoImpl接口实现类

public class UserDaoImpl implements UserDao {
    QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
    //得到叫username的user
    @Override
    public User findUser(String username) throws SQLException {
        String sql = "select u_id as uid,u_name as uname,u_password as upassword,u_email as uemail,u_sex as usex," +
                "u_status as ustatus,u_code as ucode,u_role as urole from user where u_name=?";
        /*User user = qr.query(sql, new BeanHandler<>(User.class), username);
        boolean flag = false;
        if(user!=null&&user.getUpassword().equals(password)){
            flag = true;
        }*/
        return qr.query(sql, new BeanHandler<>(User.class), username);
    }

    //添加注册的数据
    @Override
    public int inserUser(User user) throws SQLException {
        String sql = "insert into user(u_name,u_password,u_sex,u_status,u_email,u_role,u_code) value(?,?,?,?,?,?,?)";
        int i = qr.update(sql, user.getUname(), user.getUpassword(), user.getUsex(), user.getUstatus(), user.getUemail(), user.getUrole(), user.getUcode());
        return i;
    }


    //修改激活码和状态码
    @Override
    public int updataCode(String code) throws SQLException {
        String sql = "update user set u_status=1,u_code=null where u_code=?";
        int i = qr.update(sql, code);
        return i;
    }

    //根据激活码查询状态
    @Override
    public int findStatusByCode(String code) throws SQLException {
        String sql = "select u_status from user where u_code=?";
        Object o = qr.query(sql, new ScalarHandler(), code);
        if(o==null){
            return -1;
        }
        return (Integer)o;
    }


}

2.3UserService接口

public interface UserService {
    //邮件发送地址
    String url = null;
    public String getUrl();
    public boolean login(String username,String password) throws SQLException;
    public int register(User user) throws SQLException;
    //激活邮件中的激活码
    public int activate(String code) throws SQLException;

}

2.4UserService接口实现类

public class UserServiceImpl implements UserService {
    String url;
    UserDao userDao = new UserDaoImpl();

    @Override
    public String getUrl() {
        return url;
    }

    //判断是否登录成功
    @Override
    public boolean login(String username, String password) throws SQLException {
        User user = userDao.findUser(username);
        boolean flag = false;
        if(user!=null&&user.getUpassword().equals(password)){
            flag = true;
        }
        return flag;
    }

    //添加到数据库-->将激活码发送到邮箱,点击邮箱里面的激活链接:~---->在emailActivate中激活
    @Override
    public int register(User user) throws SQLException {
        //1.添加到数据库
        int i = userDao.inserUser(user);
        try {
            if(i > 0){
                //2.将激活码发送到邮箱,点击邮箱里面的激活链接,激活用户
                String title = "激活邮件发送~~~~~~~";
                String ip = Inet4Address.getLocalHost().getHostAddress();
                String c = Base64Utils.encode(user.getUcode());
                url = "http://"+ip+":8080/usersController?method=emailActivate&c="+c;
                String content = user.getUname()+":<br>您好,<a href='"+url+"'>请点击连接激活账户</a>";
                EmailUtils.sendEmail(title, content, user.getUemail());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i;
    }

    //判断拥有该验证码的用户是否激活成功
    // findStatusByCode找到-->updataCode删除激活码,改变激活状态
    @Override
    public int activate(String code) throws SQLException {
        int status = userDao.findStatusByCode(code);
        if(status == SysConstant.Status.NOT_ACTIVE.getCode()){//status=0 未激活
            int i = userDao.updataCode(code); //status=1  激活并删除code
            return i;
        }
        return 0;
    }


}

2.5实体类

public class User {
    private int uid;
    private String uname;
    private String upassword;
    private String uemail;
    private String usex;
    private int ustatus;
    private String ucode;
    private int urole;

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", uname='" + uname + '\'' +
                ", upassword='" + upassword + '\'' +
                ", uemail='" + uemail + '\'' +
                ", usex='" + usex + '\'' +
                ", ustatus=" + ustatus +
                ", ucode='" + ucode + '\'' +
                ", urole=" + urole +
                '}';
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getUpassword() {
        return upassword;
    }

    public void setUpassword(String upassword) {
        this.upassword = upassword;
    }

    public String getUemail() {
        return uemail;
    }

    public void setUemail(String uemail) {
        this.uemail = uemail;
    }

    public String getUsex() {
        return usex;
    }

    public void setUsex(String usex) {
        this.usex = usex;
    }

    public int getUstatus() {
        return ustatus;
    }

    public void setUstatus(int ustatus) {
        this.ustatus = ustatus;
    }

    public String getUcode() {
        return ucode;
    }

    public void setUcode(String ucode) {
        this.ucode = ucode;
    }

    public int getUrole() {
        return urole;
    }

    public void setUrole(int urole) {
        this.urole = urole;
    }
}

2.6电子有点发送工具类

public class EmailUtils {
	public static void sendEmail(String title,String content,String receiveAccount){
		String myAccount = "498414698@qq.com";
		//发件人 邮箱的 SMTP 服务器地址
		//String SMTPHost = "smtp.163.com";//163
		String SMTPHost = "smtp.qq.com";//qq
		//组成 properties
		Properties prop = new Properties();
		prop.setProperty("mail.transport.protocol", "smtp");//设置协议类型
		prop.setProperty("mail.smtp.host", SMTPHost);//定义发件人的邮箱服务器地址
		prop.setProperty("mail.smtp.auth", "true");//设置请求验证
		//1.Session对象 创建会话 用于和邮箱服务器进行交互
		Session session = Session.getDefaultInstance(prop);
		//设置debug模式 可以查看详细发送信息 可略
		session.setDebug(true);
		
		//2.创建方法 用来组成一封完整的邮件
		//参数 session(参数配置), myAccount 发送方 , user.getEmail() 接收方
		//使用session对象 获取待发送的邮件信息
		MimeMessage message = new MimeMessage(session);
		//3.设置发件人 收件人 标题 邮件内容 附件 发送时间等等
		try {
			//3.1发件人 from
			message.setFrom(new InternetAddress(myAccount, "小米", "utf-8"));
			//3.2收件人 to 支持可以添加多个收件人 | 抄送 | 密送 如果想要发送给多个人 可以重复下面代码多次
			/*
			 * MimeMessage.RecipientType.TO 发送
			 * MimeMessage.RecipientType.CC 抄送
			 * MimeMessage.RecipientType.BCC 密送
			 * */
			message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveAccount,  "utf-8"));
			//3.3生成邮件主题
			message.setSubject(title,"utf-8");
			String ip = Inet4Address.getLocalHost().getHostAddress();//本机ip地址
			//www.xiaomi.com
			//String url = "http://"+ip+":8080/activate?c=");

			//message.setText(content);  普通文本
			//设置邮件正文 setContent 可以使用html标签
			message.setContent(content,"text/html;charset=utf-8");
			//设置邮件的发送时间 是立即发送
			//message.setSentDate(new Date());
			//保存设置
			message.saveChanges();
			//4.利用Transport 发送邮件
			Transport tran = session.getTransport();
			//连接服务器 确认发送方 是否授权
			tran.connect(myAccount,"papawrgiguwdbjaj" );
			//发送邮件 将message 对象 传给 Transport 对象 将邮件发送出去
			//参数1 要发的内容 参数2 要给哪些人发
			//message.getAllRecipients() 获取到所有的收件人 | 抄送 | 密送
			tran.sendMessage(message, message.getAllRecipients());
			//关闭连接
			tran.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	public  static  void  main(String[]args) throws  Exception{
//		 sendEmail("哈喽","你好","498414698@qq.com");
		System.out.println(Inet4Address.getLocalHost().getHostAddress());


	}


}

2.7参数的工具类

public class SysConstant {

    public  enum  Status{
         NOT_ACTIVE(0),ACTIVE(1);
         int code ;
         Status(int code){
            this.code = code;
         }

        public int  getCode(){
             return  code;
        }

    }


    public  static final int NOT_ACTIVE=0;
    public  static final  int CUSTOMER=0;


    public  static final String FORWARD="forward";
    public  static final String REDIRECT="redirect";
    public  static final String FLAG=":";

    //订单状态 0 未付款,1已经付款未发货 2发货待收货 3 收货待评价 4订单完成 5 退货状态
}

3.BaseController(Servlet)

public class BaseController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //得到method(controller对应的方法名)
        String method = request.getParameter("method");
        if(method==null){
            //转去首页
            response.sendRedirect("/login.jsp");
        }

        try {
            //得到对象
            Class class1 = this.getClass();
            Object o = class1.newInstance();
            //得到要处理业务的方法:比如说:login
            Method loginMethod = class1.getMethod(method,HttpServletRequest.class,HttpServletResponse.class);

            //设置 Content-type实体报头。
            //一般在Servlet中,习惯性的会首先设置请求以及响应的内容类型以及编码方式:
            if (loginMethod.isAnnotationPresent(ContentType.class)){
                ContentType contentType = loginMethod.getAnnotation(ContentType.class);
                String type = contentType.value();//image/jpeg  application/json;charset=utf-8
                response.setContentType(type);
            }else{
                response.setContentType("text/html;charset=utf-8");
            }
            //调用方法
            Object invoke = loginMethod.invoke(o, request, response);
            //如果有返回值如  return  "forward:index.jsp"
            if(invoke!=null){
                //返回值是String类型---->跳转页面(转发、重定向)
                if(invoke.getClass().getSimpleName().equalsIgnoreCase("String")){
                    String s = (String) invoke;
                    //得到页面的字符串
                    String substring = s.substring(s.indexOf(":") + 1);
                    if(s.startsWith(SysConstant.FORWARD)){
                        request.getRequestDispatcher(substring).forward(request, response);
//                        request.getRequestDispatcher("/test001.jsp").forward(request, response);
                    }else{
                        response.sendRedirect(substring);
                    }
                }else{
                    //需要转json数据
                    String s = new Gson().toJson(invoke);
                    response.getWriter().print(s);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

4.1运行流程一:

1.登陆–>
在这里插入图片描述
1.登陆–>2.主页
在这里插入图片描述

4.2运行流程二:

1.注册–>
在这里插入图片描述
1.注册–>2.注册页面
在这里插入图片描述
1.注册–>2.注册页面–>3.(注册完点击提交到)激活界面
在这里插入图片描述
在这里插入图片描述
1.注册–>2.注册页面–>3.(注册完点击提交到)激活界面–>点击激活链接可以到邮箱界面,从接收到的邮件里面点击立即激活 / 或者自己打开邮箱,从接收到的邮件里面点击立即激活

在写邮件工具类的时候,里面会有一个授权码,这个授权码需要在自己邮箱里面得到,每条1分钱
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值