完成用户登录注册功能

一,需求分析

整体分析框架如下图,需要的包也如下图,它们放在src下

 

所有的需求如下图所示,

1,我们创建一个名为day12的数据库,其中创建了一个users表

2,在myeclipse中我们新建一个名为day12_user的web项目,

3,在src下我们创建了如下几个java包:

                   com.itheima.damain    实体类包,          其中包括 User类

                   com.itheima.dao          接口包    ,        其中包括 UserDao接口

                   com.itheima.dao.impl   接口实现类包,    其中包括  UserDaoImpl实现类

                   com.itheima.service     接口包                 其中包括service接口

                   com.itheima.service.impl  接口实现类包    其中包括service接口实现类

                   com.itheima.utils           工具包            其中包括一般的关闭,连接数据库的函数 

                   com.itheima.exception    异常包

                   com.itheima.web.servlet    servlet包       包括loginServlet和registerServlet

首先是主页main.jsp

<body>
         <h1>欢迎来到主页</h1>
       <form action="/day12_user/login.jsp"  method = "post">
              <input  type = "submit"   value = "登陆"   >
       </form>
       <form action="/day12_user/register.jsp"   method = "post">
             <input  type = "submit"   value= "注册">
       </form>
</body>

 

对于登陆板块,选择登陆按钮,进入login.jsp

 

<body>
      <form action="/day12_user/demo1"   method= "post">
           用户名:<input   type = "text"   name = "username"  ><br>
            密码:<input   type = "password"   name = "password"   ><br>
              <input type = "submit" value = "登陆"><br>
      </form>
</body>

 

web.xml如下图所示

<servlet>
    <servlet-name>loginServlet</servlet-name>
    <servlet-class>com.itheima.web.servlet.loginServlet</servlet-class>
  </servlet>
  <servlet>
    <servlet-name>registerServlet</servlet-name>
    <servlet-class>com.itheima.web.servlet.registerServlet</servlet-class>
  </servlet>


  <servlet-mapping>
    <servlet-name>loginServlet</servlet-name>
    <url-pattern>/demo1</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
    <servlet-name>registerServlet</servlet-name>
    <url-pattern>/demo2</url-pattern>
  </servlet-mapping>    

关于user用户的板块,com.itheima.damain    实体类包,          其中包括 User类,源码如下文所示

//实体bean,用于封装数据
public class User {
      private    int id;
      private    String username;
      private    String password;
      private    String email;
      private    Date birthday;
    
      public User(String username, String password, String email, Date birthday) {
        super();
        this.username = username;
        this.password = password;
        this.email = email;
        this.birthday = birthday;
    }    
    public User() {
        // TODO Auto-generated constructor stub
    }
    public int getId() {
        return id;
    }
    public String getUsername() {
        return username;
    }    
    public String getPassword() {
        return password;
    }
    public String getEmail() {
        return email;
    }
    public Date getBirthday() {
        return birthday;
    }    
}

com.itheima.web.servlet    servlet包       包括loginServlet和registerServlet

loginservlet的源码如下图所示,只写一个完整源码,其他的servlet类似

package com.itheima.web.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.itheima.damain.User;
import com.itheima.service.impl.UserService;
import com.itheima.service.impl.UserServiceImpl;

@SuppressWarnings("serial")
public class loginServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
       //设置编码模式
request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //获取表单数据, 并将表单数据存入到login函数中 String name = request.getParameter("username"); String pwd = request.getParameter("password"); //处理业务逻辑,实现login 方法,里面涉及到finduser方法 UserService us = new UserServiceImpl();// User u = us.login(name,pwd); //分发转向 if(u!=null){ out.write("<br/>欢迎你,登陆成功,3秒跳转首页"); request.setAttribute("u", u.getUsername()); request.getRequestDispatcher("/success.jsp").forward(request, response); }else{ //实现刷新功能 out.write("用户名或密码错误,请重新登陆"); response.setHeader("refresh", "1;url=/day12_user/login.jsp"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

上面是登陆成功后的主页,其源码为success.jsp

<body>
   <h1>这是主页</h1>
      欢迎  ${u} ,来到主页      
</body>

对于loginservlet中,有一句代码进行解析

//处理业务逻辑,实现login 方法,里面涉及到finduser方法

 UserService us = new UserServiceImpl(); 这句是创建父接口指向子类对象
 User u = us.login(name,pwd);    


com.itheima.service     接口包                 其中包括Userservice接口,
com.itheima.service.impl  接口实现类包              其中包括UserserviceImpl接口实现类
userService源代码如下
public interface UserService {
     //根据用户和密码实现登陆
      public   User  login(String name,String pwd);
      //注册
      public  int register(User user);
}

UserServiceImpl实现类源码如下:
package com.itheima.service.impl;

import com.itheima.damain.User;
import com.itheima.dao.UserDao;
import com.itheima.dao.impl.UserDaoImpl;

public class UserServiceImpl  implements UserService{  
      // 实现用户登录的方法
    public User login(String name,String pwd) {
        // TODO Auto-generated method stub
     //用实现类来指向父类的接口
         UserDao dao = new  UserDaoImpl();
         return   dao.finduser(name,pwd);
    }
    public int register(User user) {
        // TODO Auto-generated method stub
         UserDao dao = new  UserDaoImpl();
         return  dao.adduser(user);
    }
}
UserDao接口源码如下
public interface UserDao {    
    // 查找用户
     public  User finduser(String name,String password);
    // 添加用户
     public  int  adduser(User user);
}
UserDaoImpl源码如下:
package com.itheima.dao.impl;

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

import com.itheima.damain.User;
import com.itheima.dao.UserDao;
import com.itheima.utils.DBUtils;

/**
 * 数据访问层对于方法的实现
 * @author zjf-pc
 *
 */
public class UserDaoImpl  implements UserDao{
/**
 * 查找用户的实现方法
 */
    public User finduser(String name,String password) {
        // TODO Auto-generated method stub
       Connection conn = null;
       PreparedStatement ps = null;
       ResultSet rs = null;
       User u = null;
         try {
            conn = DBUtils.getConnection();
            //找到与浏览器中getConnection输入用户名和密码一致的sql语句,并保存在rs中
            String sql = "select * from users where username= ? and password = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1,name);
            ps.setString(2, password);
            //得到sql中的结果
            rs = ps.executeQuery();
            while(rs.next())
            {
                //新创建一个user对象,将rs中的属性均赋值给user对象
                //如果之前的rs内容为空的话,那么此时返回的u也为null
                u = new User();
                u.setId(rs.getInt(1));
                u.setUsername(rs.getString(2));
                u.setPassword(rs.getString(3));
                u.setEmail(rs.getString(4));
                u.setBirthday(rs.getDate(5));
            }
        } catch (Exception e) {
          e.printStackTrace();
        }finally{
         DBUtils.closeAll(rs, ps, conn);
        }     
        return u;
    }
/**
 * 添加用户的实现方法
 */
    public int adduser(User user) {
        // TODO Auto-generated method stub
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        int i =0;
        try{
            conn = DBUtils.getConnection();
            //向数据库库表中插入一行语句如下
            String sql = "insert  into  users(username,password,email,birthday)values(?,?,?,?);";
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getEmail());
            SimpleDateFormat sdf = new  SimpleDateFormat("yyyy-MM-DD");
            ps.setString(4, sdf.format(user.getBirthday()));
           //将数据更新到表中
            i =  ps.executeUpdate();
            } catch (Exception e) {
            e.printStackTrace();
            }finally{
             DBUtils.closeAll(rs, ps, conn);
            }
             return i;
    }
    public UserDaoImpl() {
        super();
        // TODO Auto-generated constructor stub
    }    
}

 对于用户注册板块,register.jsp如下图所示

<body>
      <h1>用户注册页面</h1>
      <form action="/day12_user/demo2"  method = "post">
        用户名:<input  type = "text"  name = "username"/><br>
        密码: <input  type = "password" name = "password"/><br>
        邮箱:<input type = "text" name = "email"/><br>
        出生日期:<input type = "text" name = "birthday"/><br>
        <input type = "submit"  value = "注册"><br>
      </form>
</body>

//web.xml中对应的是这个,那么相应的registerServlet会在下文看到
<servlet-mapping> <servlet-name>registerServlet</servlet-name> <url-pattern>/demo2</url-pattern> </servlet-mapping>
 
registerServlet源码如下文所示
public class registerServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
         //设置编码模式
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        int i =0;
        //获取表单数据
               String name =  request.getParameter("username");
               String pwd =  request.getParameter("password");
               String email =  request.getParameter("email");
               String birthday =  request.getParameter("birthday");
               SimpleDateFormat sdf = new  SimpleDateFormat("yyyy-MM-DD"); 
            try {
              //将获取到的表单数据封装到u中
              User   u = new User(name,pwd,email, sdf.parse(birthday));
              UserService us = new  UserServiceImpl();//这在上文有解析
             //对封装在u中的数据进行注册,使其记录在数据库表中
              i = us.register(u);//这也在上文有解析
              if(i!=0)
              {
                 out.write("注册成功,信息如下:<br>");
                 out.write("<br>姓名:"+u.getUsername());
                 out.write("<br>邮箱:"+u.getEmail());
                 out.write("<br>出生日期:"+sdf.format(u.getBirthday()));    
               }else {
                 out.write("注册信息不成功");
                }  
            } catch (Exception e) {
               e.printStackTrace();
            }
        
        //处理业务逻辑
        //分发转向
    }
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            doGet(request, response);
      }
}



posted on 2017-03-31 22:27  我想静静_zjf  阅读(13166)  评论(0编辑  收藏  举报

导航