MVC设计模式

在这里插入图片描述

注册 - 登录 - 退出登录

  1. domain
/**
 * @Date 2019/3/11 - 16:36
 * 对应数据库的字段
 */
public class User {
    private int id;
    private String username;
    private String password;
    private String email;
    private Date birthday;

    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;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public User() {
    }

    public User(int id, String username, String password, String email, Date birthday) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}
  1. Dao层
//接口
public interface IUserDao {
    //插入数据
    public void insert(User user);
    //通过用户名和密码查找数据
    public User findUser(String username,String password);
    //通过用户名查找数据
    public User findUser(String username);
}

//实现类
public class UserDaoImpl implements IUserDao {
    @Override
    public void insert(User user) {
        Connection con = null;
        PreparedStatement ps = null;
        //1.注册驱动
        try {
            //2.获取Connection对象
            con = DBUtils.getConnection();
            //3.获取Statement对象
            String sql = "INSERT INTO t_user (username,password,email,birthday)" +
                    "VALUES (?,?,?,?)";
            ps = con.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3, user.getEmail());
            ps.setDate(4, new Date(user.getBirthday().getTime()));

            //4.执行sql语句
            ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5.关闭资源
            DBUtils.close(con, ps, null);
        }
    }

    @Override
    public User findUser(String username, String password) {
        User user = null;
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        //1.注册驱动
        try {
            //2.获取Connection对象
            con = DBUtils.getConnection();
            //3.获取Statement对象
            String sql = "SELECT * FROM t_user WHERE username = ? AND password = ?";
            ps = con.prepareStatement(sql);

            ps.setString(1, username);
            ps.setString(2, password);

            rs = ps.executeQuery();
            while (rs.next()) {
                user = new User();
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setId(rs.getInt("id"));
                user.setEmail(rs.getString("email"));
                user.setBirthday(rs.getDate("birthday"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5.关闭资源
            DBUtils.close(con, ps, rs);
        }
        return user;
    }

    @Override
    public User findUser(String username) {
        User user = null;
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        //1.注册驱动
        try {
            //2.获取Connection对象
            con = DBUtils.getConnection();
            //3.获取Statement对象
            String sql = "SELECT * FROM t_user WHERE username = ?";
            ps = con.prepareStatement(sql);

            ps.setString(1, username);

            rs = ps.executeQuery();
            while (rs.next()) {
                user = new User();
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setId(rs.getInt("id"));
                user.setEmail(rs.getString("email"));
                user.setBirthday(rs.getDate("birthday"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5.关闭资源
            DBUtils.close(con, ps, rs);
        }
        return user;
    }
}
  1. Service层
//接口
public interface IUserService {
    //注册业务
    public void register(User user);

    //登陆业务
    public User login(String username, String password);

    public User login(User user) throws UserLoginException;

    //判断用户是否已经存在
    public boolean userExist(String username);
}
//实现类
public class UserServiceImpl implements IUserService {
    private IUserDao userDao = new UserDaoImpl();

    @Override
    public void register(User user) {
        userDao.insert(user);
    }

    @Override
    public User login(String username, String password) {
        return userDao.findUser(username, password);
    }

    @Override
    public User login(User user) throws UserLoginException {
        User u = userDao.findUser(user.getUsername(), user.getPassword());
        if (u != null) {
            return u;
        } else {
            throw new UserLoginException("用户名或密码错误");
        }
    }

    @Override
    public boolean userExist(String username) {
        User user = userDao.findUser(username);
        return user != null;
    }
}
  1. 校验表单数据
public class UserForm {
    private String username;
    private String password;
    private String repassword;
    private String email;
    private String birthday;
    private Map<String, String> err = new HashMap<>();


    public boolean validate() {
        //用户名不能以空格开头或结尾,中间不能有空格,只能是字母数字下划线
        /**
         * 1.用户名不能为空,用户名长度5~10
         * 2.密码不能为空,密码长度大于6小于9
         * 3.确认密码要与之前的密码一致
         * 4.邮箱格式要正确
         * 5.日期的格式也要正确
         */
        if (username.startsWith(" ") && username.endsWith(" ")) {
            err.put("username", "*用户名不能以空格开头或结尾");
        } else if (username.trim().split(" ").length > 1) {
            err.put("username", "*用户名中不能有空格");
        } else if (!username.matches("\\w{5,15}")) {
            err.put("username", "*用户名长度应为5~15位,只能包含数字与英文大小写");
        } else if (username == null) {
            err.put("username", "*用户名不能为空");
        }

        if (password.startsWith(" ") && password.endsWith(" ")) {
            err.put("password", "*密码不能以空格开头或结尾");
        } else if (password.trim().split(" ").length > 1) {
            err.put("password", "*密码中不能有空格");
        } else if (!password.matches("\\w{6,9}")) {
            err.put("password", "*密码长度应为6~9位,只能包含数字与英文大小写");
        } else if (password == null) {
            err.put("password", "*密码不能为空");
        }

        if (!password.equals(repassword)) {
            err.put("repassword", "*两次密码输入不一致");
        }
        if (!email.matches("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$")) {
            err.put("email", "*邮箱格式输入有误");
        } else if (email == null) {
            err.put("email", "*邮箱不能为空");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
        try {
            sdf.parse(birthday);
        } catch (ParseException e) {
            err.put("birthday", "*日期格式有误,日期格式应为YYYY-MM-DD");
        }
        if (birthday == null) {
            err.put("birthday", "*生日不能为空");
        }

        return err.size() == 0;
    }


    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;
    }

    public String getRepassword() {
        return repassword;
    }

    public void setRepassword(String repassword) {
        this.repassword = repassword;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public Map<String, String> getErr() {
        return err;
    }

    public void setErr(Map<String, String> err) {
        this.err = err;
    }
}
  1. Servlet
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 5076484699939911388L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setHeader("content-type", "text/html;charset=UTF-8");
        IUserService ius = new UserServiceImpl();
        //1.获取请求参数
        User formUser = new User();
        try {
            BeanUtils.populate(formUser, req.getParameterMap());
            try {
                //登陆成功
                User DBUser = ius.login(formUser);
                //将登陆用户存储到session
                req.getSession().setAttribute("DBUser", DBUser);

                resp.sendRedirect(req.getContextPath() + "/main.jsp");
            } catch (UserLoginException e) {
                e.printStackTrace();
                req.setAttribute("Message", e.getMessage());
                //登陆失败,回到登陆页面
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

@WebServlet("/LogoutServlet")
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.清除Session的数据
        req.getSession().invalidate();
        //2.推出后回到登陆页面
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }
}

 @WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = -5155291530722492812L;
    private IUserService ius = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setHeader("Content-type", "text/html;charset=UTF-8");
        //数据校验
        /**
         * 1.用户名不能为空,用户名长度5~10
         * 2.密码不能为空,密码长度大于6小于9
         * 3.确认密码要与之前的密码一致
         * 4.邮箱格式要正确
         * 5.日期的格式也要正确
         */
        UserForm uf = new UserForm();
        try {
            BeanUtils.populate(uf, req.getParameterMap());
            if (!uf.validate()) {
                req.setAttribute("uf", uf);
                req.getRequestDispatcher("/register.jsp").forward(req, resp);
                return;
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //1.把请求参数封装成模型
        User user = new User();
        try {
            //注册日期转换
            ConvertUtils.register(new DateLocaleConverter(), Date.class);
            BeanUtils.populate(user, req.getParameterMap());
            System.out.println(user.getBirthday());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //2.调用Service层
        if (ius.userExist(user.getUsername())) {
            uf.getErr().put("username", "*用户名已存在");
            req.setAttribute("uf", uf);
            req.getRequestDispatcher("/register.jsp").forward(req, resp);
            return;
        }

        //注册
        ius.register(user);

        //3.响应客户端
        resp.getWriter().write("注册成功,3秒后进入登陆页面");
        resp.addHeader("Refresh", "3;url=" + req.getContextPath() + "/login.jsp");
    }
}
  1. jsp
1.index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>首页</title>
  </head>
  <body>
  <a href="${pageContext.request.contextPath}/login.jsp">登陆</a><br/>
  <a href="${pageContext.request.contextPath}/register.jsp">注册</a><br/>
  </body>
</html>

2.login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登陆</title>
</head>
<body>
<p>${Message}</p>
<form action="${pageContext.request.contextPath}/LoginServlet" method="post">
    <table border="1">
        <tr>
            <td>用户名</td>
            <td><input type="text" name="username"></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="password"></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="登陆"></td>
        </tr>
    </table>
</form>
</body>
</html>

3.main.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>后台</title>
</head>
<body>
${DBUser["username"]},欢迎!<a href="${pageContext.request.contextPath}/LogoutServlet">退出登录</a><br/>
后台
</body>
</html>

4.register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>注册</title>
    <style type="text/css">span {
        color: red;
    }</style>
</head>
<body>
<form action="${pageContext.request.contextPath}/RegisterServlet" method="post">
    <table border="1">
        <tr>
            <td>用户名</td>
            <td><input type="text" name="username" value="${uf.username}"><span>${uf.err['username']}</span></td>
        </tr>
        <tr>
            <td>密码</td>
            <td><input type="password" name="password" value="${uf.password}"><span>${uf.err['password']}</span></td>
        </tr>
        <tr>
            <td>确认密码</td>
            <td><input type="password" name="repassword" value="${uf.repassword}"><span>${uf.err['repassword']}</span>
            </td>
        </tr>
        <tr>
            <td>邮箱</td>
            <td><input type="text" name="email" value="${uf.email}"><span>${uf.err['email']}</span></td>
        </tr>
        <tr>
            <td>出生日期</td>
            <td><input type="text" name="birthday" value="${uf.birthday}"><span>${uf.err['birthday']}</span></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="注册">
            </td>
        </tr>
    </table>
</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值