servlet+mysql+jsp简单的登录注册功能。【详解,写得比较细,适合新手看】

 

最新开始学习Java ee了。现在写一个简单的登录注册的小应用。

服务器使用的是tomcat在自己电脑构建的服务器。


在src下面建立三个包,一个dao包处理业务逻辑,一个servlet包处理jsp传输过来的数据,一个util包帮助我们建立与数据库的联系。

下图是数据库表单:




下图是项目结构。



 

    先贴上util里的代码,不懂的可以看看注释。

package util;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

/*这个类就是为我们得到Connection所服务的。

 *后面我们只需要调用静态方法getConnection()就能直接得到一个Connection了,

 *这里我们使用的是单例模式,不懂的可以百度下。

 */

public class DBHelper {

//这个是添加的jar包里面的一个类。可以在referenced Libraries里面找到

public static final String driver="com.mysql.jdbc.Driver";

/*这个是本地数据库中的一个database,名字叫User.localhost表示自己的电脑,

3306是一个端口,表示访问的是数据库。后面?之后的就代表的是编号格式以及使用ssl

协议,想了解的可以百度下。

*/

public static final String url="jdbc:mysql://localhost:3306/User?characterEncoding=utf8&useSSL=true";

public static final String username="root";

public static final String password="root";

public static Connection con=null;

static{

try {

Class.forName(driver);//得到DriverManager,在下面建立连接时使用

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

public static Connection getConnection(){

if(con==null){

try {

con=DriverManager.getConnection(url,username,password);//建立连接,使用的参数就是上面我们所定义的字符串常量。

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

return con;

}

}


下面是dao里的代码(不知道怎么回事,下面的代码没有颜色了。。。注释是我自己加的颜色,看起来有点吃力。。。不过将就看下吧。):

     import util.DBHelper;
/* dao层处理业务逻辑,里面有两个方法,
  一个是检查登录,一个是向数据库注册一个用户*/

public class DAO {


public static Connection con = null;
public static PreparedStatement ps = null;
public static ResultSet rs = null;

public static boolean checkLogin(String username, String password) {//检查登录,这里传入的两个参数分别是从jsp传过来的账号和密码
con = DBHelper.getConnection();//通过DBHelper得到Connection
String sql = "select * from user where username = ?";//查询语句,先把username设置为?,后面在赋值
try {
ps = con.prepareStatement(sql);
ps.setString(1, username);//赋值
rs = ps.executeQuery();//执行查询语句,返回一个ResultSet,这个就是我们数据库里面的user
if (rs.next()) {

String pwd = rs.getString("password");//找到数据类里面user所对应的passwrod
if (pwd.equals(password)) {//把我们从数据库中找出来的password和从jsp中传过来的passwrod比较
return true; //ture代表验证成功
}else{
return false;//false代表验证失败
}
}else{
return false;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {     //这里是一些操作数据库之后的一些关闭操作
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rs = null;
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ps = null;
}
}
return false;
}
public static void registe(String username,String password){//向数据库注册一个新的用户
     con=DBHelper.getConnection();//通过DBHelper得到Connection
     String sql="insert into user values (?,?)";//这个语句是向表单插入一个user,username和password先设置为?,后面赋值
     try {
ps=con.prepareStatement(sql);
ps.setString(1, username);//给username赋值
ps.setString(2, password);//给password赋值
            int b=ps.executeUpdate();//执行插入语句,并返回一个int值,大于0表示添加成功,小于0表示添加失败.
            if(b>0){
            System.out.println("数据添加成功");
            }else{
            System.out.println("数据添加失败");
            }
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {   //这里是一些操作数据库之后的一些关闭操作
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rs = null;
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ps = null;
}
}
}
}


下面是servlet,一个是登录的,一个是注册的:


先来登录的:


package 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 dao.DAO;

/*

登录界面是从登录界面获得username和password,再通过dao层中的checkLogin()来判断是否登录

*/
@WebServlet("/login.do")
public class LoginServlet extends HttpServlet {
@Override

         //doGet方法自动跳转到doPost()方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

this.doPost(req, resp);
}


@Override

        //doGet方法判断从jsp传过来的username和password是否和数据库中的对应,如果对应,则跳转到欢迎界面,如果不对应,则返回登录界面
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");//设置编码格式为utf-8
String username = req.getParameter("username");//从jsp中获取usernmae
String password = req.getParameter("password");//从jsp中获取password
if (DAO.checkLogin(username, password)) {      //dao层中判断,如果为true,跳转到欢迎界面
 req.setAttribute("username", username);
              req.getRequestDispatcher("/WEB-INF/success.jsp").forward(req, resp);
}else{                                        //如果为false,跳转到登录界面,并返回错误信息.
req.setAttribute("inf", "你的账号或密码错误,请重新登录");
req.getRequestDispatcher("login.jsp").forward(req, resp);
}


}
}


下面是注册:


package 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;
/*

注册是从注册界面得到username和password,再通过dao层中registe()来向数据库添加一条用户

*/

import dao.DAO;
@WebServlet("/registe.do")
public class RegisteServlet extends HttpServlet{
@Override

             //doGet方法自动跳转到doPost()方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
   @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  req.setCharacterEncoding("utf-8");//设置编码格式为utf-8
  String username=req.getParameter("username");//从注册界面获得username
  String password=req.getParameter("password");//从注册界面获得password
  DAO.registe(username, password);            //dao层中向数据库添加数据
  req.getRequestDispatcher("login.jsp").forward(req, resp); //重新跳转到登录界面
}
}



最后,给大家看一下登录的jsp和注册的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>Insert title here</title>

</head>

<body>

<form action="registe.do" method="post">

  <table  border="1">

  <tr>

  <td><label for="username">用户:</label></td>

  <td><input type="text" name="username" id="username"/></td>

  </tr>

   <tr>

  <td><label for="password">密码:</label></td>

  <td><input type="password" name="password" id="password"/></td>

  </tr>

  <tr>

  <td colspan="2" align="center">

   <input type="submit" value="注册"/>

   <input type="reset" value="重置"/>

  </td>

  </tr>

  </table>

  </form>

</body>

</html>



注册的:

<%@ 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>Insert title here</title>

<script type="text/javascript">

  function registe(){

  window.open("registe.jsp","_self");

  }

</script>


</head>

<body>

<form action="login.do" method="post">

  <table  border="1">

  <tr>

  <td><label for="username">用户:</label></td>

  <td><input type="text" name="username" id="username"/></td>

  </tr>

   <tr>

  <td><label for="password">密码:</label></td>

  <td><input type="password" name="password" id="password"/></td>

  </tr>

  <tr>

  <td colspan="2" align="center">

   <input type="submit" value="登录"/>

   <input type="button" value="注册" onclick=registe() />

  </td>

  </tr>

  </table>

  </form>

  <c:if test="${requestScope.inf!=null}">

      <span color="red"> ${requestScope.inf} </span>

  </c:if>

</body>

</html>


登录成功的

<%@ 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>Insert title here</title>

</head>

<body>

<h1>登录成功</h1>

欢迎${requestScope.username}!

</body>

</html>



注意一下,因为是要和数据库关联,所以需要导入数据库连接的jar包。jar包百度找到后直接导入项目就好了。



终于写完了,第一次写这么多的东西。希望对初学者有用,以后有时间也会继续写其他的东西,希望和大家一起进步吧。加油!











  • 38
    点赞
  • 197
    收藏
    觉得还不错? 一键收藏
  • 39
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 39
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值