一个简单可执行的MVC+Dao模式的登陆注册功能

对于javaweb的初学者来说,想做出一个项目,增删改查绝对是第一步,下面我们就以网上订餐系统为例子,这篇文章主要讲解实现登陆注册功能。

功能介绍:实现用户的登陆注册功能,实现后台商品的增删改查功能。

界面截图:

数据库我使用的是SQLServer2008,初学者应该都会以这个数据库为例子吧,反正我当初学的时候是这样。hhh~毕竟我开学才大三,写文章仅为了方便互相交流,互相进步。

下面是数据库的代码:

create database table_reservation
--用户

create table users(
id int primary key not null,
pwd varchar(20),
name varchar(20),
tel varchar(20) not null,
address varchar(50),
)

接下来就是重头戏啦~~~实现注册功能。先看下整个项目的结构吧。

这里我要做下各个包的功能介绍啦,

dao包:接口类

dbc包:数据库连接类

factory包:工厂类

impl包:接口实现类

servlet包:控制器类

vo包:实体类

这里要注意下,读者千万要记得加入jdbc,否则数据库不会连接成功,就不能实现功能啦!

1、vo包

package vo;

public class Users {
private int id;
private String pwd;
private String name;
private String tel;
private String address;

}

记得自己调用get set方法哟~

2、注册界面

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Register.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>
   
   <form action="RegisterServlet" method="post">
   
   <table align="center" width=500 background="Images/img6.jpg">
   <tr >
   <td colspan="2">
   <h2 align="center">网上订餐系统注册</h2>
   </td>
   </tr>
<tr>
<td align="center">
  账号:
</td>
<td>
  <input type="text" name="id" id="id" size=40>
  </td>
 </tr>

<tr>
<td align="center">
   密码:
 </td>
 <td>
   <input type="password" name="pwd" id="pwd" size=39>
   </td>
</tr>
<tr>
<td align="center">
  姓名:
 </td>
 <td>
  <input type="text" name="name" id="name" size=40>
  </td>
 </tr> 
<tr>
<td align="center">
  电话:
</td>
  <td>
  <input type="text" name="tel" id="tel" size=40>
  </td>
</tr>

<tr>
<td align="center">
  地址:
</td>
<td>
  <input type="text" name="address" id="address" size=40>
  </td>
 </tr>
<tr>
<td  colspan="2">
  <input type="submit" value="注册" style="width: 462px; ">
</td>
</tr>
  </table>
   </form>
  </body>
</html>

3、登陆界面

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'Login.jsp' starting page</title>
    
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->

  </head>
  
  <body>

  <form action="LoginServlet" method="post" background="Images/img2.jpg">
  
  <table align="center" width=500 background="Images/img6.jpg">
  <tr>
  <td colspan="2">
   <h1 align="center" >网上订餐系统</h1> 
   </td>
   </tr>
  <tr>
  <td align="center">
  账号:
  </td>
  <td>
  <input type="text" id="id" name="id" size=40>
  </td>
  </tr>
  <tr>
  <td align="center">
 密码:
 </td>
 <td>
 <input type="password" id="pwd" name="pwd" size=39>
 </td>
 </tr>
 <tr>
 <td >
 <input type="submit" value="登陆" style="width: 190px; ">
 </td>

 <td align="center">
 <a href='Register.jsp'>还没有账号?</a>
     &nbsp;    &nbsp;    &nbsp;    &nbsp;    &nbsp;
 <a href='shop_login.jsp'>店铺</a>
 </td>

  </table>
  </form>
  </body>
</html>

 

4、dao包

package dao;

 

import vo.Users;

public interface UsersDao {
    //登陆功能
     public boolean findLogin(Users users) throws Exception;
        //注册
    public boolean doInsert(Users user) throws Exception;
}


5、dbc包:

package dbc;
import java.sql.*;
public class DBConnection {
    /*Mysql数据库连接字符串*/
    /*
    private static final String driver="com.mysql.jdbc.Driver";
    private static final String url = "jdbc:mysql://localhost:3306/BMSWeb";
    private static  final String userName = "root";
    private static  final String password = "root";
    private  Connection conn = null;
    boolean flag = false;
    //*/
    /*SQLServer连接字符串*/

    
    /** 
     * @功能 创建数据库连接 
     * @返回值 connection型值 
     */

    private static final String driver
    ="com.microsoft.sqlserver.jdbc.SQLServerDriver";
    private static final String url = "jdbc:sqlserver://127.0.0.1:1433; DatabaseName= table_reservation";
    private static  final String userName = "sa";
    private static  final String password = "123456";//此处为自己的数据库密码
    private  Connection conn = null;
    boolean flag = false;
    
    /** 
     * @功能 创建数据库连接 
     * @返回值 connection型值 
     */
    public Connection getConnection() {
        try {
            Class.forName(driver); 
            conn = DriverManager.getConnection(url, userName, password);
        } catch (Exception e) {
           e.printStackTrace();
           System.out.println("获取数据库连接失败!");
        }
        return conn;
    }
    
     /** 
     * @功能 关闭数据库连接
     */
    public void closed() {
        if(conn!=null)
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
                System.out.println("关闭con对象失败!");
            }
    }
  
}

6、factory包

package factory

import dao.UsersDao;


public class DaoFactory {
    public static UsersDao getUserDaoInstance(){
        return new UsersDaoImpl();
    }

}

7、impl包

package impl;

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

import vo.Users;
import dao.UsersDao;
import dbc.DBConnection;

public class UsersDaoImpl implements UsersDao{
    boolean flag = false;
    //private Connection conn = null;
    private PreparedStatement pstmt = null;
    private ResultSet rs = null;
    DBConnection dbc  = new DBConnection();
    private Connection conn = dbc.getConnection();
    @Override
    public boolean findLogin(Users users) throws Exception {
        try{
            conn = dbc.getConnection();
            String sql = " select* from Users where id=? and pwd=?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, users.getId());
            pstmt.setString(2, users.getPwd());
            rs=pstmt.executeQuery();
            if(rs.next()){
                flag = true;
                //获取数据库的值
                users.setId(rs.getInt("id"));
                users.setPwd(rs.getString("pwd"));
                users.setName(rs.getString("name"));
                users.setTel(rs.getString("tel"));
                users.setAddress(rs.getString("address"));
            }
            rs.close();
            pstmt.close();
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            dbc.closed();
        }
        return flag;                                                                                                                                                                                                                                     
    }
    @Override
    public boolean doInsert(Users user) throws Exception {
        try{
            String sql = "INSERT INTO users(id,pwd,name,tel,address) VALUES (?,?,?,?,?)";
            pstmt = conn.prepareStatement(sql);
            //传值
            pstmt.setInt(1, user.getId());
            pstmt.setString(2, user.getPwd());
            pstmt.setString(3, user.getName());
            pstmt.setString(4, user.getTel());
            pstmt.setString(5, user.getAddress());
            //执行
            int a = pstmt.executeUpdate();
            if(a>0){
                flag=true;
            }
            pstmt.close();
        }catch(Exception e){
            e.printStackTrace();
            dbc.closed();
        }
        return flag;
    }


}

8、servlet包

注册:

package servlet;

import java.io.IOException;
import java.io.PrintWriter;

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


import vo.Users;
import factory.DaoFactory;

public class RegisterServlet extends HttpServlet {

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        this.doPost(request, response);
    
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=gb2312");
        request.setCharacterEncoding("gb2312");
        
        Users user = new Users();
        Integer id = Integer.parseInt(request.getParameter("id"));
        String pwd=request.getParameter("pwd");
        String name=request.getParameter("name");
        String tel=request.getParameter("tel");
        String address = request.getParameter("address");
        user.setId(id);
        user.setPwd(pwd);
        user.setName(name);
        user.setTel(tel);
        user.setAddress(address);
        
        
        try {
            if(DaoFactory.getUserDaoInstance().doInsert(user)){
                //跳转
                request.getRequestDispatcher("Login.jsp").forward(request, response);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

    
    }

登陆:

package servlet;

import java.io.IOException;
import java.io.PrintWriter;

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 vo.Users;
import factory.DaoFactory;

public class LoginServlet extends HttpServlet {

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        this.doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset='UTF-8'");
        request.setCharacterEncoding("UTF-8");
        
    Integer id =Integer.parseInt(request.getParameter("id"));
        
        String pwd = request.getParameter("pwd");
        //Integer limit = Integer.parseInt(request.getParameter("limit"));
        Users user = new Users();
        user.setId(id);
        user.setPwd(pwd);

        try {
            if(DaoFactory.getUserDaoInstance().findLogin(user)){
                //设置会话
                HttpSession session = request.getSession();
                session.setAttribute("id", user.getId());
                session.setAttribute("name", user.getName());
                session.setAttribute("tel", user.getTel());
                session.setAttribute("address", user.getAddress());
                //跳转
                request.getRequestDispatcher("ShopInfoSelectAllServlet").forward(request, response);
                
                
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    }
}

以上就是全部代码啦,欢迎各位小伙伴随时留言哦

 

 

 

 

 

  • 5
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值