jsp+servlet实现最基本的注册登陆功能

时间:2021-11-02 16:07:50

源码和数据库下载地址:http://download.csdn.net/detail/biexiansheng/9759722

1:首先需要设计好数据库和数据表,这里简单截图说明我创建的字段和类型。

jsp+servlet实现最基本的注册登陆功能

2:进入正题,开始开发前台和后台代码。首先创建一个动态web工程,然后先创建一个实体类。

 package com.bie.po;
/**
* @author BieHongLi
* @version 创建时间:2017年2月21日 上午9:59:03
* 用户的实体类
*/
public class User { private Integer id;
private String name;
private String password;
private String email;
private String phone;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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;
} //重写toString 方法
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", password=" + password + ", email=" + email + ", phone=" + phone
+ "]";
} }

3:然后创建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">
<title>用户登陆页面</title>
<style type="text/css">
h1{text-align:left;}
h4{text-align:left;color:red;}
body{background:url(images/1.png)}
a{text-decoration:none;font-size:20px;color:black;}
a:hover{text-decoration:underline;font-size:24px;color:red;}
</style> </head>
<body>
<form action="user/userlogin" method="post">
<h1>用户登陆页面</h1>
<h4>装饰中......</h4>
<hr/>
<table align="left">
<tr>
<td>账号:</td>
<td><input type="text" name="name" id="name"></td>
</tr>
<tr>
<td>密码:</td>
<td><input type="password" name="password" id="password"></td>
</tr>
<tr>
<td colspan="1">
</td>
<td>
<input type="submit" value="登陆"/>
<input type="reset" value="重置"/>
<a href="register.jsp" target="_blank">注册</a>
</td>
</tr>
</table>
</form>
</body>
</html>

4:再创建注册页面register.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>注册的页面</title>
<style type="text/css">
h1{text-align:center;}
h4{text-align:right;color:red;}
body{background:url(images/2.png)}
</style> <script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//alert("测试jQuery是否能用");
$("#form1").submit(function(){
var name=$("#name").val();//获取提交的值
if(name.length==0){//进行判断,如果获取的值为0那么提示账号不能为空
//alert("aa");//测试使用
$("#nameError").html("账号不能为空");
return false;
} //密码进行验证不能为空
var password=$("#password").val();//获取提交的密码的值
if(password.length==0){
$("#passwordError").html("密码不能为空");
return false;
} //确认密码进行验证
var relpassword=$("#relpassword").val();//获取提交的确认密码的值
if(relpassword.length==0){
$("#relpasswordError").html("确认密码不能为空哦");
return false;
} if(password!=relpassword){
$("#relpasswordError").html("确认密码输入不正确,请重新输入");
return false;
}
}); });
</script>
</head>
<body>
<form action="user/userregister" method="post" id="form1">
<h1>用户注册页面</h1>
<h4>装饰中......</h4>
<hr/>
<table align="center">
<tr>
<td>账&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号:</td>
<td>
<input type="text" name="name" id="name"/>
<div id="nameError" style="display:inline;color:red;"></div>
</td>
</tr>
<tr>
<td>密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码:</td>
<td>
<input type="password" name="password" id="password">
<div id="passwordError" style="display:inline;color:red;"></div>
</td>
</tr>
<tr>
<td>确认密码:</td>
<td>
<input type="password" name="relpassword" id="relpassword">
<div id="relpasswordError" style="display:inline;color:red;"></div>
</td>
</tr>
<tr>
<td>电话号码:</td>
<td><input type="text" name="phone" id="phone"></td>
</tr>
<tr>
<td>电子邮件:</td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td colspan="1">
</td>
<td>
<input type="submit" value="注册"/>
<input type="reset" value="重置"/>
<a href="login.jsp" target="_blank">登陆</a>
</td>
</tr>
</table>
</form>
</body>
</html>

5:再创建utils层,公共的工具层BaseDao.java;

 package com.bie.utils;

 import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle; /**
* @author BieHongLi
* @version 创建时间:2017年2月21日 上午10:01:14
* 数据交互层dao层
*/
public class BaseDao { private static String driver;//数据库驱动
private static String url;//数据库路径,找到对应的数据库
private static String user;//数据库账号
private static String password;//数据库密码 static{
driver=ResourceBundle.getBundle("db").getString("driver");
url=ResourceBundle.getBundle("db").getString("url");
user=ResourceBundle.getBundle("db").getString("user");
password=ResourceBundle.getBundle("db").getString("password");
}
/*private static String driver="com.mysql.jdbc.Driver";
private static String url="jdbc:mysql:///test";
private static String user="root";
private static String password="123456";*/ /***
* 连接数据库的方法
* @return
* @throws ClassNotFoundException
* @throws SQLException
*/
public static Connection getCon() throws ClassNotFoundException, SQLException{
Class.forName(driver);//加载数据库驱动
System.out.println("测试加载数据库成功");
Connection con=DriverManager.getConnection(url, user, password);
System.out.println("测试数据库链接成功");
return con;
} /***
* 关闭数据库的方法
* @param con
* @param ps
* @param rs
*/
public static void close(Connection con,PreparedStatement ps,ResultSet rs){
if(rs!=null){//关闭资源,避免出现异常
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(ps!=null){
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} /***
* 同意增删改的方法
* @param sql
* @param arr
* @return
*/
public static boolean addUpdateDelete(String sql,Object[] arr){
Connection con=null;
PreparedStatement ps=null;
try {
con=BaseDao.getCon();//第一步 :连接数据库的操作
ps=con.prepareStatement(sql);//第二步:预编译
//第三步:设置值
if(arr!=null && arr.length!=0){
for(int i=0;i<arr.length;i++){
ps.setObject(i+1, arr[i]);
}
}
int count=ps.executeUpdate();//第四步:执行sql语句
if(count>0){
return true;
}else{
return false;
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
} /*public static void main(String[] args) {
try {
BaseDao.getCon();
System.out.println("测试数据库链接成功");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/ }

6:然后创建dao层数据交互层的接口和实现类

 package com.bie.dao;

 import com.bie.po.User;

 /**
* @author BieHongLi
* @version 创建时间:2017年2月21日 上午10:38:40
* 创建一个接口用于声明用户登陆注册的方法
*/
public interface UserDao { /***
* 用户登陆的方法声明
* @param user
* @return
*/
public User login(User user); /***
* 用户注册的方法声明
* @param user
* @return
*/
public boolean register(User user);
}
 package com.bie.dao.impl;

 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 com.bie.dao.UserDao;
import com.bie.po.User;
import com.bie.utils.BaseDao; /**
* @author BieHongLi
* @version 创建时间:2017年2月21日 上午10:38:56
*
*/
public class UserDaoImpl implements UserDao{ @Override
public User login(User user) {
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
con=BaseDao.getCon();//1:获取数据库的连接
//2:书写sql语句
String sql="select * from user where name=? and password=? ";
ps=con.prepareStatement(sql);//3:预编译
//4:设置值
ps.setString(1, user.getName());
ps.setString(2, user.getPassword());
rs=ps.executeQuery();//5:执行sql语句
User users=null;
if(rs.next()){
users=new User();
//从数据库中获取值设置到实体类的setter方法中
users.setId(rs.getInt("id"));
users.setName(rs.getString("name"));
users.setPassword(rs.getString("password"));
users.setEmail(rs.getString("email"));
users.setPhone(rs.getString("phone")); return user;
}else{
return null;
} } catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} /***
* 插入的方法,即注册
*/
@Override
public boolean register(User user) {
String sql="insert into user values(0,?,?,?,?) ";
List<Object> list=new ArrayList<Object>();
list.add(user.getName());
list.add(user.getPassword());
list.add(user.getEmail());
list.add(user.getPhone()); boolean flag=BaseDao.addUpdateDelete(sql,list.toArray());
if(flag){
return true;
}else{
return false;
}
} }

7:再创建servlet层进行登陆的业务逻辑处理(由于省去了service层,所以在servlet层进行业务逻辑处理了)

 package com.bie.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.bie.dao.UserDao;
import com.bie.dao.impl.UserDaoImpl;
import com.bie.po.User; /**
* @author BieHongLi
* @version 创建时间:2017年2月21日 上午10:49:44
*
*/
@WebServlet("/user/userlogin")
public class UserLoginServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
User user=new User();
//获取login.jsp页面提交的账号和密码
String name=request.getParameter("name");
String password=request.getParameter("password");
//测试数据
System.out.println(name+" "+password);
//获取login.jsp页面提交的账号和密码设置到实体类User中
user.setName(name);
user.setPassword(password); //引入数据交互层
UserDao dao=new UserDaoImpl();
User us=dao.login(user);
//测试返回的值
System.out.println(us);
if(us!=null){
request.setAttribute("info", "登陆成功");
}else{
request.setAttribute("info", "登录失败");
} request.getRequestDispatcher("/index/info.jsp").forward(request, response);
} }

8:再创建servlet层进行注册的业务逻辑处理(由于省去了service层,所以在servlet层进行业务逻辑处理了)

 package com.bie.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.bie.dao.UserDao;
import com.bie.dao.impl.UserDaoImpl;
import com.bie.po.User; /**
* @author BieHongLi
* @version 创建时间:2017年2月21日 下午1:34:17
* 注册的servlet
*/
@WebServlet("/user/userregister")
public class UserRegisterServlet extends HttpServlet{ private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
} @Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
User user=new User();
//获取login.jsp页面提交的账号和密码
String name=request.getParameter("name");
String password=request.getParameter("password");
String email=request.getParameter("email");
String phone=request.getParameter("phone"); //获取register.jsp页面提交的账号和密码设置到实体类User中
user.setName(name);
user.setPassword(password);
user.setEmail(email);
user.setPhone(phone); //引入数据交互层
UserDao dao=new UserDaoImpl();
boolean flag=dao.register(user);
if(flag){
request.setAttribute("info", "注册成功");
}else{
request.setAttribute("info", "注册失败");
} request.getRequestDispatcher("/index/info.jsp").forward(request, response);
} }

9:为了避免乱码,使用过滤器进行过滤。

 package com.bie.utils;

 import java.io.IOException;

 import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest; /**
* @author BieHongLi
* @version 创建时间:2017年2月21日 上午11:08:49
*
*/
@WebFilter("/*")
public class UTFFilter implements Filter{ @Override
public void destroy() {
// TODO Auto-generated method stub } @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain)throws IOException, ServletException {
//将servletRequest转发为HttpServletRequest
HttpServletRequest request=(HttpServletRequest)servletRequest;
request.setCharacterEncoding("utf-8");
filterChain.doFilter(servletRequest, servletResponse);
} @Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub } }

效果如下所示:

jsp+servlet实现最基本的注册登陆功能