java web之登录注册

本文实现一个简单的java web项目功能---登录注册,目的是对前一段做的学习做个总结,以后有需要的话也可以直接拿来改改就能用,仅此。


版权声明:欢迎转载,转载请注明出处,谢谢!(如有侵权之处,也请联系修改或删除!)


1.实现效果如下:

1.1登录:

登录.png

1.2注册:

注册.png

2.Eclipse 项目结构:

项目结构.png

3.具体实现:

3.1 数据库建表(user_info):

表名为:user_info

3.2 链接到数据库(JDBCUtil.java)


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCUtil {
    static String username = "yourusername";
    static String password = "yourpassword";
    static String driver = "com.mysql.jdbc.Driver";
    static String url = "jdbc:mysql://localhost:3306/yoursqluame?useSSL=false";
    //获取链接
    public static Connection getConn(){
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url,username, password);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }
    //释放链接
    public static void release(Statement stmt,Connection conn){
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    //重载释放链接
    public static void release(ResultSet rs ,Statement stmt,Connection conn){
        if(rs != null){
            try {
                rs.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(stmt != null){
            try {
                stmt.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

3.3 用户类(UserBean.java)

  • login.jsp
package com.Bean;

public class UserBean {
    private String userName;
    private String password;
    private String userEmail;
    
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getUserEmail() {
        return userEmail;
    }
    public void setUserEmail(String userEmail) {
        this.userEmail = userEmail;
    }
    
    public UserBean(){
    }
    
    public UserBean(String userName,String password,String userEmail){
        this.userName = userName;
        this.password = password;
        this.userEmail = userEmail;
    }
    
}

3.4 Login与Register的jsp编写(login.jsp&&register.jsp)

  • login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录</title>

<script type="text/javascript">
function login(){
    var th = document.form1;
    if(th.email.value==""){
        alert("Email Can't Be Bull");
        th.email.focus();
        return;
    }
    if(th.password.value==""){
        alert("Password Can't Be Null");
        th.password.focus();
        return;
    }
    th.action="<%=path%>/LoginServlet";
        th.submit();
    }
</script>
<script type="text/javascript">
    function change() {
        var img = document.getElementById("verify");
        img.src = "VerifyCodeServlet?a=" + new Date().getTime();
    }
</script>

</head>
<body>
    <div align="center">
        <form name="form1" action="" method="post">
            <table>
                <tr>
                    <td>邮箱:</td>
                    <td><input name="email"></td>
                </tr>
                <tr>
                    <td>密码:</td>
                    <td><input name="password" type="password"></td>
                </tr>
                <tr>
                    <td>验证码:</td>
                    <td><input type="text" name="verifycode"></td>
                    <td><a href="javascript:change()">![](VerifyCodeServlet)</a></td>
                </tr>
                <tr>
                    <td><input type="button" value="登录" onclick="login()"></td>
                    <td><input type="button" value="注册" onclick="javascript:location.href='register.jsp'">
                </tr>
                <tr>${msg}</tr>

            </table>
        </form>
    </div>
</body>
</html>
  • register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Register</title>
<script type="text/javascript">
function register(){
    var th = document.form1;
    if(th.userName.value==""){
        alert("UserName Can't Be Null");
        th.userName.focus();
        return;
    }
    if(th.email.value==""){
        alert("Email Can't Be Null");
        th.email.focus();
        return;
    }
    if(th.password.value==""){
        alert("Password Can't Be Null");
        th.password.focus();
        return;
    }
    if(th.password.value != th.psw.value){
        alert("The Two Passwords Don't Match!");
        th.psw.focus();
        return;
    }
    th.action="<%=path%>/RegisterServlet";
    th.submit();
}
</script>
</head>
<body>
    <div align="center">
        <form name="form1" action="" method="post">
            <table>
                <tr>
                    <td>UserName:</td>
                    <td><input name="userName"></td>
                </tr>
                <tr>
                    <td>Email:</td>
                    <td><input name="email"></td>
                </tr>
                <tr>
                    <td>Password:</td>
                    <td><input type="password" name="password"></td>
                </tr>
                <tr>
                    <td>ConfirmPassword:</td>
                    <td><input type="password" name="psw"></td>
                </tr>
                <tr>
                    <td><input type="button" value="注册" onclick="register()"></td>
                    <td><input type="button" value="返回"
                        onclick="javascript:location.href='login.jsp'">
                </tr>
                <tr>${msg}</tr>
            </table>
        </form>
    </div>
</body>
</html>
  • welcome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome</title>
</head>
<body>
Welcome ${userName}
</body>
</html>

3.5 Servlet以及Dao层的实现

-LoginServlet.java

package com.Servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Dao.UserDao;


/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        String verifyc  = request.getParameter("verifycode");
        String svc =(String) request.getSession().getAttribute("sessionverify");
        
        if(!svc.equalsIgnoreCase(verifyc)){
            request.setAttribute("msg", "验证码错误!");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }
        
        String userName = new UserDao().login(email,password);
        
        if(userName == null){
            request.setAttribute("msg", "用户名或密码错误!");
            request.getRequestDispatcher("/login.jsp").forward(request, response);
            return;
        }else{
            request.setAttribute("userName", userName);
            request.getRequestDispatcher("/welcome.jsp").forward(request, response);
            return;
        }
        
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

-RegisterServlet.java

package com.Servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Bean.UserBean;
import com.Dao.UserDao;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        
        String userName = request.getParameter("userName");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        
        boolean flag = new UserDao().checkEmail(email);
        
        if(flag){
            request.setAttribute("msg", "此邮箱已被注册!");
            request.getRequestDispatcher("register.jsp").forward(request, response);
            return;
        }else{
            new UserDao().register(userName,email,password);
            request.setAttribute("msg", "欢迎您"+userName+",注册成功!");
            request.getRequestDispatcher("login.jsp").forward(request, response);
            return;
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
  • UserDao.java
package com.Dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.Bean.UserBean;
import com.JDBCUtil.JDBCUtil;

public class UserDao {
//登录检测
    public String login(String email, String password) {
        // TODO Auto-generated method stub
        String username = null;
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn =JDBCUtil.getConn();
            String sql = "select user_name from user_info where user_email=? and user_password=?;";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, email);
            pstmt.setString(2, password);
            rs = pstmt.executeQuery();
            
            while(rs.next()){
                username = rs.getString("user_name");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            JDBCUtil.release(rs, pstmt, conn);
        }
        
        return username;
    }
//检测邮箱是否已使用
    public boolean checkEmail(String email) {
        // TODO Auto-generated method stub
        boolean flag = false;
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        
        try {
            conn = JDBCUtil.getConn();
            String sql = "select * from user_info where user_email =?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1, email);
            rs = pstmt.executeQuery();
            
            while(rs.next()){
                flag = true; 
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            JDBCUtil.release(rs, pstmt, conn);
        }
        
        return flag;
    }
//注册用户
    public void register(String userName,String email,String password) {
        // TODO Auto-generated method stub
        Connection conn = null;
        PreparedStatement pstmt = null;
        
        
        try {
            conn = JDBCUtil.getConn();
            String sql = "insert into user_info values("+userName+","+email+","+password+");";
            pstmt = conn.prepareStatement(sql);
            pstmt.executeUpdate(sql);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            JDBCUtil.release(pstmt, conn);
        }
        
        
    }

}
  • VerifyCodeServlet.java
package com.Servlet;

import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.Dao.VerifyCode;

/**
 * Servlet implementation class VerifyCodeServlet
 */
@WebServlet("/VerifyCodeServlet")
public class VerifyCodeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public VerifyCodeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        VerifyCode vc = new VerifyCode();  
        BufferedImage image = vc.getImage(85,23); 
        request.getSession().setAttribute("sessionverify", vc.getText());
        VerifyCode.output(image, response.getOutputStream()); 
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
  • VerifyCode.java
package com.Dao;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;

public class VerifyCode {

    public static final char[] CHARS = { '2', '3', '4', '5', '6', '7', '8',  
            '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',  
            'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };  
  
    public static Random random = new Random();  
  
    public String getRandomString() {  
        StringBuffer buffer = new StringBuffer();  
        for (int i = 0; i < 4; i++) {  
            buffer.append(CHARS[random.nextInt(CHARS.length)]);  
        }  
        return buffer.toString();  
    }  
  
    public  Color getRandomColor() {  
        return new Color(random.nextInt(255), random.nextInt(255), random  
                .nextInt(255));  
    }  
  
    public  Color getReverseColor(Color c) {  
        return new Color(255 - c.getRed(), 255 - c.getGreen(), 255 - c  
                .getBlue());  
    }  
    String text = getRandomString();  
    public String getText() {  
        return text;  
    }  
  
    public BufferedImage getImage(int width,int height ){  
        Color color = getRandomColor();  
        Color reverse = getReverseColor(color);  
  
        BufferedImage bi = new BufferedImage(width, height,  
                BufferedImage.TYPE_INT_RGB);  
        Graphics2D g = bi.createGraphics();  
        g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));  
        g.setColor(color);  
        g.fillRect(0, 0, width, height);  
        g.setColor(reverse);  
        g.drawString(text, 10, 22);  
        for (int i = 0, n = random.nextInt(80); i < n; i++) {  
            g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);  
        }  
        return bi;  
          
    }  
    public static void output(BufferedImage image, OutputStream out) throws IOException{  
        ImageIO.write(image, "JPEG", out);  
    }
}

3.6 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Blog_Demo</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

*说明:

1.数据库链接需要导入对应的jar包--mysql-connector-java-5.1.43-bin.jar。
2.直接粘贴复制,若出现中文变为乱码的情况,请转换项目字符格式或手动更改即可。


(* 第一次写文章,排版有可能不是很好理解,有什么建议欢迎指出!谢谢!)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 206,378评论 6 481
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 88,356评论 2 382
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 152,702评论 0 342
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 55,259评论 1 279
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 64,263评论 5 371
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,036评论 1 285
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,349评论 3 400
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,979评论 0 259
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 43,469评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,938评论 2 323
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,059评论 1 333
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,703评论 4 323
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,257评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,262评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,485评论 1 262
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,501评论 2 354
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,792评论 2 345

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,599评论 18 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,581评论 18 399
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,748评论 6 342
  • 夜深人静了,终于有时间做上周五的一个活动了,拿出纸笔打开手机,看到第一条是这样写的:闭上眼睛,静静地回忆...
    happyMia阅读 662评论 0 1
  • 当红女主持人中,谢娜一度是内地综艺节目主持人“一姐”,其身价也是最高。只是《快乐大本营》由于近年来受到真人秀节目的...
    绫筱初夏阅读 504评论 0 2