java web之登录注册

作者: 猫不爱吃鱼 | 来源:发表于2017-08-11 20:24 被阅读254次

本文实现一个简单的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.直接粘贴复制,若出现中文变为乱码的情况,请转换项目字符格式或手动更改即可。


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

相关文章

网友评论

  • 夜晚雨:有想学习java编程的,可以咨询我微信2683002850
  • 夜晚雨:有想学习java编程的,可以咨询我微信2683002850
  • 摆渡人_0c3b:很好,请问,都需要哪些jar包?
    猫不爱吃鱼:mysql-connector-java-5.1.43-bin.jar这个是链接数据库用的。这个功能比较简单,只用到了这一个。(不好意思,之前没有看到,希望对你有所帮助)
  • usiantein:谢谢了最近正好需要用到这些
    猫不爱吃鱼: @檀箫风笙 有用就好,不足之处还请多多指教
  • c434967c2219:很棒呀
    猫不爱吃鱼: @纪信 哇,感谢!

本文标题:java web之登录注册

本文链接:https://www.haomeiwen.com/subject/tbsrrxtx.html