java web利用servlet+JDBC实现用户登录

Java Web 专栏收录该内容
4 篇文章 0 订阅

1、登录的一般流程为在后台获取前台传来的登录名和密码
2、利用select语句遍历用户信息表,查找是否存与前台页面传来的用户名和密码相等的值,若存在则登录成功,否则给出提示信息。
我使用的编程环境为:数据库:MySQL5.5、服务器:Tomcat8.5,、编程环境eclipse Mars
首先建立一张用户信息表,一共八个字段

CREATE TABLE `db_user` (
  `id` int(20) NOT NULL AUTO_INCREMENT,
  `userName` varchar(50) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  `sex` varchar(6) DEFAULT NULL,
  `birthday` varchar(20) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `phone` varchar(20) DEFAULT NULL,
  `address` varchar(200) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8

接下来建立一个Java web工程,
在这里插入图片描述
实体类的代码

package cn.dry.entity;

public class User {
   private int id;//用户编号
   private String userName;//用户名
   private String password;//密码
   private String sex;//性别
   private String birthday;//出生日期
   private String email;//邮箱
   private String phone;//电话
   private String address;//地址
   
   public User(){
	   super();
   }
   public User (String userName,String password){
	   super();
	   this.userName = userName;
	   this.password = password;
   }
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		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 getSex() {
			return sex;
		}
		public void setSex(String sex) {
			this.sex = sex;
		}
		
		public String getBirthday() {
			return birthday;
		}
		public void setBirthday(String birthday) {
			this.birthday = birthday;
		}
		public String getEmail() {
			return email;
		}
		public void setEmail(String email) {
			this.email = email;
		}
		public String getPhone() {
			return phone;
		}
		public void setPhone(String phone) {
			this.phone = phone;
		}
		public String getAddress() {
			return address;
		}
		public void setAddress(String address) {
			this.address = address;
		}
   
   
}

数据库连接工具类代码

package cn.dry.util;

import java.sql.Connection;
import java.sql.DriverManager;

public class DbUtil {

	private String dbUrl="jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=UTF-8";
	private String dbUserName="root";
	private String dbPassword="你的数据库连接密码";
	private String jdbcName="com.mysql.jdbc.Driver";
	
	/**
	 * 获取数据库连接
	 * @return
	 * @throws Exception
	 */
	public Connection getCon() throws Exception{
		Class.forName(jdbcName);
		Connection con=DriverManager.getConnection(dbUrl,dbUserName,dbPassword);
		return con;
	}
	
	/**
	 * 关闭数据库连接
	 * @param con
	 * @throws Exception
	 */
	public void closeCon(Connection con) throws Exception{
		if(con!=null){
			con.close();
		}
	}
	
	public static void main(String[] args) {
		DbUtil dbUtil=new DbUtil();
		try {
			dbUtil.getCon();
			System.out.println("数据库连接成功");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

字符串验证工具类代码

package cn.dry.util;

public class StringUtil {

	public static boolean isEmpty(String str){
		if("".equals(str)|| str==null){
			return true;
		}else{
			return false;
		}
	}
	
	public static boolean isNotEmpty(String str){
		if(!"".equals(str)&&str!=null){
			return true;
		}else{
			return false;
		}
	}
}

登录的DAO代码,就一个登录的方法,从数据库里查询用户名和密码

package cn.dry.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import cn.dry.entity.User;
import cn.dry.util.DbUtil;

public class UserDao {

	/**
	 * 登录验证
	 * @param con
	 * @param user
	 * @return
	 * @throws Exception
	 */
	public User login(Connection con,User user) throws Exception{
		User resultUser=null;
		String sql="select * from db_user where userName=? and password=?";
		PreparedStatement pstmt=con.prepareStatement(sql);
		pstmt.setString(1, user.getUserName());
		pstmt.setString(2, user.getPassword());
		ResultSet rs=pstmt.executeQuery();
		if(rs.next()){
			resultUser=new User();
			resultUser.setUserName(rs.getString("userName"));
			resultUser.setPassword(rs.getString("password"));
		}
		return resultUser;
	}
}

登录的servlet类代码

package cn.dry.web;

import java.io.IOException;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.dry.entity.Message;
import cn.dry.entity.User;
import cn.dry.model.UserDao;
import cn.dry.util.DbUtil;
import cn.dry.util.StringUtil;

/**
 * Servlet implementation class AddMessageServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	DbUtil dbUtil=new DbUtil();
	UserDao userDao=new UserDao();
       
    /**
     * @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 {
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String userName = request.getParameter("userName");//获取用户名
		String password = request.getParameter("password");//获取密码
		//将集合对象保存到应用上下文中
		request.setAttribute("userName", userName);
		request.setAttribute("password", password);
		//判断用户名和密码是否为空
		if(StringUtil.isEmpty(userName)||StringUtil.isEmpty(password)){
			request.setAttribute("error", "用户名或密码为空!");
			//如果用户名和密码为空则重定向到登录页面
			request.getRequestDispatcher("login.jsp").forward(request, response);
			return;
		}
		//实例化user类
		User user  = new User(userName,password);
		Connection con = null;
		
		try {
			
			con = dbUtil.getCon();
			 User currentUser = userDao.login(con, user);
			//判断用户名、
			if(currentUser==null){
				request.setAttribute("error", "用户名或密码错误!");
				//服务器端跳转
				request.getRequestDispatcher("login.jsp").forward(request, response);
				
			}else{
				//获取session对象
				HttpSession session  = request.getSession();
				session.setAttribute("currentUser", currentUser);
				//客户端跳转
				response.sendRedirect("index.jsp");
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				dbUtil.closeCon(con);
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		
	}

}

前台登录页面代码,不是专业的美工,页面做的不是很美观。

<%@ 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>用户登录</title>
<style type="text/css">
  #userlogin{ 
    height:200px;
   border-top:60px;
   border-bottom: 20px;
    
  } 
</style>
</head>
<body>
  <div id="userlogin" align="center" >
  <h2>用户登录</h2>
   <form action="LoginServlet" method="post">
     <table border="0" cellpadding="0" cellspacing="0" background="images/userlogin.jpg" width="300"  >
       <tr>
        <td>用户名:</td>
        <td><input type="text" name="userName" id="userName" value="${userName }"> </td>
       </tr>
       <tr>
        <td>&nbsp;码:</td>
        <td><input type="password" name="password" id="password" value="${password }"> </td>
       </tr>
       <tr>
        <td height="10"></td>
       </tr>
       <tr>
         <td></td>
         <td colspan="2" align="center">
           <input type="submit" value="登录">
           <input type="reset" value="重置">
         </td>
       </tr>
       <tr>
         <td></td>
         <td colspan="2" align="center"><a href="register.jsp">注册</a> </td>
       </tr>
       <tr height="20">
		 <td width="30%"></td>
		 <td colspan="2">
			<font color="red">${error }</font>**//这里是显示用户登录错误的提示信息,利用EL表达式从后台传值,实现在前台显示。**
		</td>
		</tr>
			<tr >
				<td></td>
			</tr>       
     </table>
   </form>
  </div>
</body>
</html>

用servlet实现登录时必须配置相应的web.xml文件,只有路径置正确才能正确访问。
在这里插入图片描述
最后是前台的登录效果
在这里插入图片描述
花了一个晚上搞出来的,前台界面不是很美观,可以自己微调,希望能帮到大家,有问题欢迎留言。

©️2022 CSDN 皮肤主题:创作都市 设计师:CSDN官方博客 返回首页

打赏作者

Echo......

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值