Java之MVC模式实现注册登录功能

文章目录

  • 一、描述
    • 源码结构图
  • 二、需要的jar包
  • 三、分层源码
      • 3.1 bean下的Users类,代码入下
      • 3.2 DAO层里面的接口类、实现类,代码如下
        • 接口类代码如下
        • 实现类代码如下:
      • 3.3 framework框架下有Action接口,和该接口的实现类
        • Action接口类代码如下
        • Action实现类Login登录实现类
        • Action实现类register登录实现类
        • 实现Action的servlet
      • 3.4 controller层控制的源码
        • Login的servlet源码如下:
        • Register的servlet源码如下:
      • 3.5 web.xml配置文件

一、描述

Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp负责数据显示,javabean负责封装数据。 Servlet+JSP+JavaBean模式程序各个模块之间层次清晰,web开发推荐采用此种模式。

这里以一个最常用的用户登录注册程序来讲解Servlet+JSP+JavaBean开发模式,通过这个用户登录注册程序综合案例,把之前的学过的XML、Xpath、Servlet、jsp的知识点都串联起来。

源码结构图

Java之MVC模式实现注册登录功能_第1张图片

二、需要的jar包

dom4j-1.6.1.jar dom4j用于操作XML文件
jaxen-1.1-beta-6.jar 用于解析XPath表达式
commons-beanutils-1.8.0.jar 工具类,用于处理bean对象
commons-logging.jar commons-beanutils-1.8.0.jar的依赖jar包
jstl.jar jstl标签库和EL表达式依赖包
standard.jar jstl标签库和EL表达式依赖包

三、分层源码

3.1 bean下的Users类,代码入下

package com.bean;

/**
 * @Author: pomelo
 * @Create: 2020-03-25 12:15
 * @ProjectName: MVC
 * @Package: com.bean
 * @ClassName: Users
 * @Description: 用户实体类
 * @Version: 1.0
 */
public class Users {
    private int id;
    private String name;
    private String password;
    private String tel;

    public  Users(){};

    public Users(String name, String password) {
        this.name = name;
        this.password = password;
    }

    public Users(String name, String password, String tel) {
        this.name = name;
        this.password = password;
        this.tel = tel;
    }

    public Users(int id, String name, String password, String tel) {
        this.id = id;
        this.name = name;
        this.password = password;
        this.tel = tel;
    }

    public int getId() {
        return id;
    }

    public void setId(int 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 getTel() {
        return tel;
    }

    public void setTel(String tel) {
        this.tel = tel;
    }
}

3.2 DAO层里面的接口类、实现类,代码如下

接口类代码如下

public interface UserDao {
    //注册用户
    int userInfoAdd(Users user);
    //用户登录
    Users getUserBypwd(String name, String password);

}

实现类代码如下:

package com.dao.impl;

import com.bean.Users;
import com.dao.UserDao;
import com.util.ConnectionSource;

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

/**
 * @Author: pomelo
 * @Create: 2020-03-25 12:20
 * @ProjectName: MVC
 * @Package: com.dao.impl
 * @ClassName: UserDaoImpl
 * @Description:
 * @Version: 1.0
 */
public class UserDaoImpl implements UserDao {

    @Override
    public int userInfoAdd(Users user) {
        PreparedStatement pState = null;
        Connection conn = null;
        int num = 0;

        try {
            conn = ConnectionSource.getConnection();

            String sql = "insert into username (name,password,tel) values(?,?,?)";

            pState = conn.prepareStatement(sql);
            pState.setString(1,user.getName());
            pState.setString(2,user.getPassword());
            pState.setString(3,user.getTel());

            num = pState.executeUpdate();

            if (num == 1){
                System.out.println("添加成功");
            }else {
                System.out.println("添加失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            ConnectionSource.closeAll(conn,pState);
        }
        return num;
    }

    @Override
    public Users getUserBypwd(String name, String password) {
        Connection conn = null;
        PreparedStatement pState = null;
        ResultSet res = null;
        Users user = null;

        try {
            conn = ConnectionSource.getConnection();
            String sql = "select * from username where name = ? and password = ?";

            pState = conn.prepareStatement(sql);
            pState.setString(1,name);
            pState.setString(2,password);

            res = pState.executeQuery();


        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            ConnectionSource.closeAll(conn,pState,res);
        }
        return user;
    }
}

3.3 framework框架下有Action接口,和该接口的实现类

Action接口类代码如下

public interface Action {
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception;

}

Action实现类Login登录实现类

package com.action;

import com.bean.Users;
import com.dao.UserDao;
import com.dao.impl.UserDaoImpl;
import framework.Action;

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

/**
 * @Author: pomelo
 * @Create: 2020-03-25 14:26
 * @ProjectName: mvctext
 * @Package: com.action
 * @ClassName: LoginAction
 * @Description:
 * @Version: 1.0
 */
public class LoginAction implements Action {

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //获取参数
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String tel = request.getParameter("tel");

        UserDao userDao = new UserDaoImpl();
        Users users = userDao.getUserBypwd(name,password);

        if (users != null){
            return "success.jsp";
        }else{
            return "login.jsp";
        }
    }
}

Action实现类register登录实现类

package com.action;

import com.bean.Users;
import com.dao.UserDao;
import com.dao.impl.UserDaoImpl;
import framework.Action;

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

/**
 * @Author: pomelo
 * @Create: 2020-03-25 14:26
 * @ProjectName: mvctext
 * @Package: com.action
 * @ClassName: RegisterAction
 * @Description:
 * @Version: 1.0
 */
public class RegisterAction implements Action {
    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {

        //获取参数
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String tel = request.getParameter("tel");

        Users users = new Users();
        users.setName(name);
        users.setPassword(password);
        users.setTel(tel);

        UserDao userDao = new UserDaoImpl();

        int num = userDao.userInfoAdd(users);
        if (num == 1) {
            return "login.jsp";
            //response.setHeader("refresh","3;url=login.jsp");
            //response.sendRedirect("shangcheng/index.jsp");
        } else {
            //response.setHeader("refresh","3;url=register.jsp");
            return "register.jsp";
        }

    }
}

实现Action的servlet

package framework;

import com.action.LoginAction;
import com.action.RegisterAction;

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 java.io.IOException;

/**
 * @Author: pomelo
 * @Create: 2020-03-25 14:09
 * @ProjectName: mvctext
 * @Package: ${PACKAGE_NAME}
 * @ClassName: ${NAME}
 * @Description: ${description}
 * @Version: 1.0
 */
@WebServlet(name = "ActionServlet")
public class ActionServlet extends HttpServlet{
    private static final long serialVersionUID = 1L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 设置编码集
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");

            Action action = getAction(request);
            String result = action.execute(request, response);
            //转发 根据返回字符串跳转页面
            request.getRequestDispatcher(result).forward(request, response);

        } catch (Exception e) {
            response.sendError(500,"出错");
            e.printStackTrace();
        }
    }



    public Action getAction(HttpServletRequest request){
        Action action = null;
        //获取请求的uri = /mvc/login.action
        String uri = request.getRequestURI();
        //获取上下文路径以后的部分   /mvc
        String contextPath = request.getContextPath();
        //截取上下文路径以后的部分
        String actionPath = uri.substring(contextPath.length());
        //获取Action名称  trim()去除前后空格 /login.action
        String actionName = actionPath.substring(1,actionPath.lastIndexOf(".")).trim(); //
        // login register
        if("login".equals(actionName)){
            //执行登陆
            action = new LoginAction();
        }else if("register".equals(actionName)){
            //执行注册
            action = new RegisterAction();
        }
        return action;
    }

}

3.4 controller层控制的源码

Login的servlet源码如下:

package com.controller;

import com.bean.Users;
import com.dao.UserDao;
import com.dao.impl.UserDaoImpl;

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 java.io.IOException;

/**
 * @Author: pomelo
 * @Create: 2020-03-25 12:34
 * @ProjectName: MVC
 * @Package: ${PACKAGE_NAME}
 * @ClassName: ${NAME}
 * @Description: ${description}
 * @Version: 1.0
 */
@WebServlet(name = "Login")
public class Login extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //获取参数
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        String tel = request.getParameter("tel");

        UserDao userDao = new UserDaoImpl();
        Users users = userDao.getUserBypwd(name,password);

        if (users != null){
            response.sendRedirect("success.jsp");
        }else{
            response.sendRedirect("login.jsp");
        }



    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}

Register的servlet源码如下:

package com.controller;

import com.bean.Users;
import com.dao.UserDao;
import com.dao.impl.UserDaoImpl;

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 java.io.IOException;

/**
 * @Author: pomelo
 * @Create: 2020-03-25 12:35
 * @ProjectName: MVC
 * @Package: ${PACKAGE_NAME}
 * @ClassName: ${NAME}
 * @Description: ${description}
 * @Version: 1.0
 */
@WebServlet(name = "Register")
public class Register extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //获取参数
        String name = request.getParameter("name");
        String password = request.getParameter("pwd");
        String tel = request.getParameter("tel");

        Users users = new Users();
        users.setName(name);
        users.setPassword(password);
        users.setTel(tel);

        UserDao userDao = new UserDaoImpl();

        int num = userDao.userInfoAdd(users);
        if (num == 1){
            response.setHeader("refresh","3;url=login.jsp");
            //response.sendRedirect("shangcheng/index.jsp");
        }else{
            response.setHeader("refresh","3;url=register.jsp");

        }
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       this.doPost(request,response);

    }
}



3.5 web.xml配置文件

    <servlet>
        <servlet-name>ActionServlet</servlet-name>
        <servlet-class>framework.ActionServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ActionServlet</servlet-name>
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

你可能感兴趣的:(JavaWeb)