Javaweb实现用户登录并且在数据库中查找匹配的账号密码

1.业务需求:

Javaweb实现用户登录并且在数据库中查找匹配的账号密码

2 后端代码:

三层架构:

(1)Dao层:

package cn.dao;

import java.util.List;

import cn.domain.User;

public interface UserDao {
	List<User> find();
	boolean login(String username, String password);
	
}
package cn.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import DBHelper.DBConnection;
import cn.domain.User;


public class UserDaoImpl implements UserDao {
	private Connection connection = DBConnection.getConnection();
	private PreparedStatement preparedStatement = null;
	private ResultSet resultSet = null;
	private String sql = "";

	@Test
	public void test0() {
		UserDao dao = new UserDaoImpl();
		for(User e: dao.find()) System.out.println(e);
	}
	
	
	public List<User> find() {
		List<User> users = null;
		sql = "SELECT * FROM tb_user";

		try {
			preparedStatement = (PreparedStatement) connection.prepareStatement(sql);
			resultSet = preparedStatement.executeQuery();
			users = new ArrayList<User>();
			User user;
			while (resultSet.next()) {
				user = new User(resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3));
				users.add(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return users;
	}
}

 (2)Service层:

package cn.service;

import java.util.List;

import cn.domain.User;

public interface UserBll {
	
	List<User> find();
	boolean login(String username, String password);
}
package cn.service;

import java.util.List;

import cn.dao.UserDao;
import cn.dao.UserDaoImpl;
import cn.domain.User;

public class UserBllImpl implements UserBll {
	private UserDao dao = new UserDaoImpl();
	public List<User> find() {
		return dao.find();
	}
}

 

(3)UI层:
       实体类User:

package cn.domain;

public class User {

	private int id;
	private String username;
	private String password;

	public User() {
		super();
	}

	public User(int id, String username, String password) {
		super();
		this.id = id;
		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;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
	}

}

UserServlet:

package cn.ui;

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 cn.service.UserBll;
import cn.service.UserBllImpl;


/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UserBll bll = new UserBllImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 接收业务请求-业务分发-调用bll-传递数据-跳转至前端

		// 以下两行解决数据录入乱码问题
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		String op = request.getParameter("op").toString(); // 客户请求数据
		
		/**
		 * 显示用户所有信息
		 */
		if ("find".equals(op)) { // 业务分发
			request.setAttribute("USERS", bll.find());
			request.getRequestDispatcher("user/showUsers.jsp").forward(request, response); // 跳转到前端
		}
		
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doGet(request, response);
	}

}

链接数据库的工具

 (4)DBHelper:

package DBHelper;

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

import org.junit.Test;

import com.mysql.jdbc.PreparedStatement;

public class DBConnection {
	private static Connection connection = null;
	private static String className = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://localhost:3306/ebus?useUnicode=true&characterEncoding=utf-8&useSSL=false";
	private static String user = "root";
	private static String password = "wangjian";

	//连接数据库
	public static Connection getConnection() {
		try {
			Class.forName(className); //加载驱动
			connection = DriverManager.getConnection(url, user, password); //创建连接
		} catch (Exception e) {
			e.printStackTrace();
		}
		return connection;
	}

	//关闭连接
	public static void Close(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {
		try {
			if (resultSet != null)
				resultSet.close();
			if (preparedStatement != null)
				preparedStatement.close();
			if (connection != null)
				connection.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void test() {
		System.out.println(DBConnection.getConnection());
	}
	
}

3 前端JSP代码:

(1)login.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">
 <link type="text/css" rel="stylesheet" href="css/login.css">  
<title>Login</title>
</head>
<body class="login_bj" >
<h1 style="font-size: 2em; text-align: center; margin-top: 30px;">用户登陆</h1>
<div class="zhuce_body">
    <div class="zhuce_kong login_kuang">
  	<div class="zc">
    	<div class="bj_bai">
         <h3>登录</h3>
     	  	  <form action="user/Checklogin.jsp" method="post">
              <label>用户名:</label>
              <input name="username" type="text" class="kuang_txt" placeholder="用户名"><br>
              <label>密码:</label>
              <input name="password" type="password" class="kuang_txt" placeholder="密码"><br><br>
             
              <input  name="登录" type="submit" class="btn_zhuce" value="登录">
              </form>
          </div>
         
      	<div class="bj_right">
          	<p>使用以下账号直接登录</p>
              <a target="_blank" href="http://web2.qq.com/" class="zhuce_qq">QQ注册</a>
              <a target="_blank" href="https://weibo.com/" class="zhuce_wb">微博注册</a>
              <a target="_blank" href="https://wx.qq.com/" class="zhuce_wx">微信注册</a>
              <p>已有账号?<a href="#">立即登录</a></p>
          </div>

      </div>
  </div>
</div>
</body>
</html>

login.css

@charset "utf-8";
/* CSS reset */
*{ font-family:"microsoft yahei",simsun,Tahoma,sans-serif;}
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,blockquote,th,td { margin:0; padding:0; }
fieldset,img {border:0; }
ol,ul {list-style:none; }
h1,h2,h3,h4,h5,h6,button,input,select,textarea {font-size:100%;}
button::-moz-focus-inner,input::-moz-focus-inner{padding:0; border:0;}
table {border-collapse:collapse;border-spacing:0;}
i, cite, em, var, dfn, address {font-style: normal;}
body{ font-size:14px;}
a{color: #313131;text-decoration: none; }
a:hover{text-decoration: underline;}
a:active, a:focus{outline:none}
a[href^="http://tongji.baidu.com"]{display: none;}
.fl{float: left;}
.fr{float: right;}
.clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; font-size:0;}
.clearfix{zoom:1;clear:both;}
.clear{clear:both; height:0; line-height:0; font-size:0;}
.hidden,.none{display: none;}



/*.w1060{ width:1060px; height:auto; margin:0 auto;}*/
.padding_nei{ /*写padding不撑开*/
	-webkit-box-sizing:border-box;
    -moz-box-sizing:border-box;
    -ms-box-sizing:border-box;
    -o-box-sizing:border-box;
	box-sizing:border-box;
}
.main01 .sousuo div{    
	-webkit-border-radius: 17px;
    -moz-border-radius: 17px;
    -ms-border-radius:17px;
    -o-border-radius:17px; 
	border-radius:17px;	
	}
	
.w1100{ width:1100px; height:auto; margin:0 auto;}
.w1096{ width:1096px; height:auto; margin:0 auto;}

/*注册页面*/
.login_bj{ background:url(../images/bj_zhuce.jpg) no-repeat top center;}
.zhuce_body{ float:left; width:100%; height:auto;}
.zhuce_body .logo{ width:114px; height:54px; margin:53px 0 0 65px;}
.zhuce_body .zhuce_kong{ position:absolute; top:50%; left:50%; width:600px; height:478px; margin-left:-300px; margin-top:-239px;}
.zhuce_body .zhuce_kong .zc{width:600px; height:408px;}
.zhuce_body .zhuce_kong .zc .bj_bai{ float:left; width:314px; height:408px; padding-left:50px; background:#FFF;}
.zhuce_body .zhuce_kong .zc .bj_bai h3{ font:16px/70px "微软雅黑", "黑体"; color:#333333; width:270px; text-align:center;}
.zhuce_body .zhuce_kong .zc .bj_right{ float:left;width:185px; height:408px; padding-left:51px; background:#f8f8f8;}
.zhuce_kong > p{font:16px/70px "微软雅黑", "黑体"; text-align:center; color:#fff;}
.zhuce_body .zhuce_kong .zc .bj_bai .kuang_txt{ width:236px; height:32px; border:1px solid #dddddd; line-height:32px; padding-left:32px; color:#b1a9a9;  margin-bottom:10px; }
.zhuce_body .zhuce_kong .zc .bj_bai .btn_zhuce{ width:270px; height:33px; background:#37b5f9; font-size:14px; line-height:33px; text-align:center; border:0px; color:#fff; border-radius:3px; cursor:pointer;}

.zhuce_body .zhuce_kong .zc .bj_bai .phone{background:url(../images/zc_06.jpg) no-repeat 10px 10px;}
.zhuce_body .zhuce_kong .zc .bj_bai .email{background:url(../images/zc_12.jpg) no-repeat 10px 10px;}
.zhuce_body .zhuce_kong .zc .bj_bai .possword{background:url(../images/zc_16.jpg) no-repeat 10px 10px;}
.zhuce_body .zhuce_kong .zc .bj_bai .yanzm{background:url(../images/zc_19.jpg) no-repeat 10px 10px; margin-bottom:0px;}

.zhuce_body .zhuce_kong .zc .bj_bai .hui_kuang{ float:left; width:97px; height:31px; border:1px solid #dddddd;}
.zhuce_body .zhuce_kong .zc .bj_bai .shuaxin{ float:left; margin:0px 0 0 150px; width:14px; height:14px;}
.zhuce_body .zhuce_kong .zc .bj_bai div{ float:left; width:100%; line-height:43px;}
.zhuce_body .zhuce_kong .zc .bj_bai div input{ float:left; margin-top:15px;}
.zhuce_body .zhuce_kong .zc .bj_bai div span{ padding-left:5px;}
.zhuce_body .zhuce_kong .zc .bj_bai div .lan{ color:#19aaf8; padding-left:0px;}


.zhuce_body .zhuce_kong .zc .bj_right P { width:135px; font:12px/60px ""; color:#999999;}
.zhuce_body .zhuce_kong .zc .bj_right P a{ color:#37b5f9;}
.zhuce_body .zhuce_kong .zc .bj_right > a{ float:left; width:82px; height:28px; padding-left:51px; line-height:28px; margin-bottom:12px; border-radius:3px; }
.zhuce_body .zhuce_kong .zc .bj_right .zhuce_qq{ border:1px solid #37b5f9; color:#37b5f9; background:url(../images/zc_03.jpg) no-repeat 28px 7px #fff;}
.zhuce_body .zhuce_kong .zc .bj_right .zhuce_wb{ border:1px solid #f26d7e; color:#f26d7e; background:url(../images/zc_10.jpg) no-repeat 28px 7px #fff;}
.zhuce_body .zhuce_kong .zc .bj_right .zhuce_wx{ border:1px solid #00c800; color:#00c800; background:url(../images/zc_15.jpg) no-repeat 28px 7px #fff;}

/*登录页面*/
.zhuce_body .login_kuang{ position:absolute; top:50%; left:50%; width:512px; height:325px; margin-left:-256px; margin-top:-162px;}
.zhuce_body .login_kuang .zc{ width:512px; height:auto;}
.zhuce_body .login_kuang .zc .bj_bai{ float:left; width:261px; height:256px; padding-left:38px; background:#FFF;}
.zhuce_body .login_kuang .zc .bj_bai h3{ font:16px/70px "微软雅黑", "黑体"; color:#37b5f9; width:270px; text-align:left;}
.zhuce_body .login_kuang .zc .bj_right{ float:left;width:173px; height:256px; padding-left:37px; background:#f8f8f8;}
.zhuce_body .login_kuang .zc .bj_bai .kuang_txt{ width:220px; height:32px; border:1px solid #dddddd; background:#faffbd; line-height:32px; padding-left:4px; color:#b1a9a9;  margin-bottom:10px; }
.zhuce_body .login_kuang .zc .bj_bai a{ color:#37b5f9; float:right; margin-right:35px;}
.zhuce_body .login_kuang .zc .bj_bai .btn_zhuce{ width:227px; height:33px; background:#37b5f9; font-size:14px; line-height:33px; text-align:center; border:0px; color:#fff; border-radius:3px; cursor:pointer;}
.zhuce_body .login_kuang .zc .bj_bai .btn_zhuce:hover,.login_qita_kuang .zc .left .btn_zhuce:hover{ background:#0065d0;}
#participant{
	width: 60px;
	margin-left: -120px;
}
#organizer{
	width: 60px;
}

(2)Checklogin.jsp从数据库里核实用户与密码是否正确:

<%@page import="java.sql.PreparedStatement"%>
<%@ 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>
z
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%@ page import="DBHelper.DBConnection, java.sql.SQLException,
	java.sql.Connection,java.sql.ResultSet,java.sql.PreparedStatement "%>
<%
		String username = request.getParameter("username").toString();
		String password = request.getParameter("password").toString();
		Connection connection = DBConnection.getConnection();
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		String sql = "";

		try {
			if (connection != null) {
				sql = "select * from tb_user where username='" + username + "' and password='" + password + "'";
				preparedStatement = (PreparedStatement) connection.prepareStatement(sql);
				resultSet = preparedStatement.executeQuery(sql);
				if (resultSet.next()) {
					response.sendRedirect(request.getContextPath() + "/UserServlet?op=find");
				} else {
					
					out.print("<script type='text/javascript'>alert('您输入的用户名或者密码有错误,请核实后重新输入!');</script>");
					out.print("<script type='text/javascript'>location.href='../login.jsp'</script>");
					/* 重定向 */
					/* response.sendRedirect("../login.jsp"); */
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
%>

</body>
</html>

(3)showUsers.jsp显示数据库里所有用户信息:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Users</title>
</head>
<body>
	<table cellpadding="0" , cellspacing="0" , border="1"
		, bordercolor="red">
		<tr>
			<td>id</td>
			<td>username</td>
			<td>password</td>
		</tr>
		<c:forEach items="${USERS}" var="user" varStatus="index">
			<tr>
				<td>${user.id}</td>
				<td>${user.username}</td>
				<td>${user.password}</td>
			</tr>
		</c:forEach>
	</table>
</body>
</html>

最后一起来看一下效果图:

登录界面:

Javaweb实现用户登录并且在数据库中查找匹配的账号密码

显示数据库里所有用户信息: 

Javaweb实现用户登录并且在数据库中查找匹配的账号密码