java web之登录注册

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


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


1.实现效果如下:

1.1登录:

java web之登录注册_第1张图片
登录.png

1.2注册:

java web之登录注册_第2张图片
注册.png

2.Eclipse 项目结构:

java web之登录注册_第3张图片
项目结构.png

3.具体实现:

3.1 数据库建表(user_info):

java web之登录注册_第4张图片
表名为: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&®ister.jsp)

  • login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
%>




登录






    
${msg}
邮箱:
密码:
验证码: ![](VerifyCodeServlet)
  • register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
%>




Register



    
${msg}
UserName:
Email:
Password:
ConfirmPassword:
  • welcome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Welcome


Welcome ${userName}


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



  Blog_Demo
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  


*说明:

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


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

你可能感兴趣的:(java web之登录注册)