三层架构——登录功能表单的实现

一、控制层

1.登录

整体逻辑:测试层(控制层)调业务层,完成业务逻辑判断,业务层调Dao层查询与返回数据,Dao层调工具类

@WebServlet("/login")
public class LoginController extends HttpServlet {
    //整体逻辑:测试层(控制层)调业务层,完成业务逻辑判断,业务层调Dao层查询与返回数据,Dao层调工具类
    //这里使用多态的方式实例化业务层对象,方便于解耦合方便换实现类
    //注意:这里的多态要先在实现类只能实现接口不然就会报错
    private AdminService adminService=new AdminServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 编写controller层,用于接受前端参数,并将从前端获取得到的数据传到业务层,及接收业务层返回数据
        //1.解决输入数据与输出数据的乱码问题
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //2.使用req.getParameter从前端传过来的数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //3.调用业务层的方法,业务层返回一个对象
        Admin admin=adminService.login(username,password);
        //4.判断对象是否为空
            if (admin!=null){
                resp.getWriter().write("<h1>登录成功<h1/>");
                //利用路径跳转跳转到展示页面
                resp.getWriter().write("<a href='show'>展示所有</a>");
            }else{
                resp.getWriter().write("<h1>登录失败<h1/>");
            }
        }
    }

2.展示

@WebServlet("/show")
public class ShowController extends HttpServlet {
    private AdminService adminService=new AdminServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //思路:在这里也要进行再一次页面跳转因为尽量让每一层都单一的做一个业务功能
        List<Admin>   adminList = adminService.showAll();
        //利用req.setAttribute进行存值
        req.setAttribute("showAll",adminList);
        //利用转发进行数据的传递
        req.getRequestDispatcher("showjsp").forward(req,resp);
    }
}

二、业务层

 //实例化对象
    private AdminDao adminDao=new AdminDaoImpl();
    //一般在业务层中加入事务的判断
    //注意:这里发生错误时,不能采用捕获的方式,要使用抛出
    @Override
    public Admin login(String username, String password) {
        Admin res=null;
        try {
            DruidUtils.begin();
            Admin admin= adminDao.selectByUsername(username);
            if (admin!=null&&password.equals(admin.getPassword())){
                res=admin;
            }
            DruidUtils.commit();
        } catch (Exception e) {
            e.printStackTrace();
            DruidUtils.rollback();
        }
       return res;
    }

    @Override
    public List<Admin> showAll()  {
        try {
            DruidUtils.begin();
            List<Admin>  list = adminDao.selectAll();
            DruidUtils.commit();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            DruidUtils.rollback();
        }
        return null;
    }

三、数据访问层(Dao层)

//方便调取Druid工具
    private QueryRunner runner=new QueryRunner();
    @Override
    public Admin selectByUsername(String username) throws SQLException {
        String sql="select * from admin where username=?";
        return runner.query(DruidUtils.getConnection(),sql,new BeanHandler<>(Admin.class),username);
    }

    @Override
    public List<Admin> selectAll() throws SQLException {
        String sql="select * from admin";
        return runner.query(DruidUtils.getConnection(),sql,new BeanListHandler<>(Admin.class));

四、工具类

 private static DataSource dataSource;
    private static final ThreadLocal<Connection> TH=new ThreadLocal<>();
    static {
        try {
            Properties p=new Properties();
            InputStream is=DruidUtils.class.getResourceAsStream("/db.properties");
            //InputStream is=DruidDataSourceFactory.class.getResourceAsStream("/db.properties");
            p.load(is);
            dataSource=DruidDataSourceFactory.createDataSource(p);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection(){
            try {
                Connection conn=TH.get();
                if (conn==null){
                conn=dataSource.getConnection();
                TH.set(conn);
                }
                return conn;
            } catch (SQLException e) {
                e.printStackTrace();
            }
        return null;
    }
    public static void begin() throws SQLException {
        Connection conn=getConnection();
        conn.setAutoCommit(false);
    }
    public static void commit() throws SQLException {
        Connection conn=getConnection();
        conn.commit();
        TH.remove();
        closeAll(conn);
    }
    public static void rollback(){
        try {
            Connection conn=getConnection();
            conn.rollback();
            TH.remove();
            closeAll(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void closeAll(AutoCloseable...ac){
        for (AutoCloseable c:ac){
            if (c!=null){
                try {
                    c.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

五、展示页面

@WebServlet("/showjsp")
public class Showjsp  extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //思路:这里取值过后,要把取到到的值赋予一个集合存着
        //解决乱码问题
        req.setCharacterEncoding("utf-8");
        //取值
        resp.setContentType("text/html;charset=utf-8");
        List<Admin> adminList = (List<Admin>) req.getAttribute("showAll");
        PrintWriter printWriter = resp.getWriter();
        if(adminList!=null){
            printWriter.println("<html>");
            printWriter.println("<head>");
            printWriter.println("<meta charset='UTF-8'>");
            printWriter.println("<title>显示所有</title>");
            printWriter.println("</head>");
            printWriter.println("<body>");
            printWriter.println("<table border='1'>");
            printWriter.println("   <tr>");
            printWriter.println("       <td>username</td>");
            printWriter.println("       <td>password</td>");
            printWriter.println("       <td>phone</td>");
            printWriter.println("       <td>address</td>");
            printWriter.println("   </tr>");
            for(Admin admin : adminList){
                printWriter.println("   <tr>");
                printWriter.println("       <td>"+admin.getUsername()+"</td>");
                printWriter.println("       <td>"+admin.getPassword()+"</td>");
                printWriter.println("       <td>"+admin.getPhone()+"</td>");
                printWriter.println("       <td>"+admin.getAddress()+"</td>");
                printWriter.println("   </tr>");
            }
            printWriter.println("</table>");
            printWriter.println("</body>");
            printWriter.println("</html>");
        }else{
            printWriter.println("<html>");
            printWriter.println("<head>");
            printWriter.println("<meta charset='UTF-8'>");
            printWriter.println("<title>显示所有</title>");
            printWriter.println("</head>");
            printWriter.println("<body>");
            printWriter.println("<h3>当前没有用户!</h3>");
            printWriter.println("</body>");
            printWriter.println("</html>");
        }
    }
}

六、HTML页面

<form action="/login"><!--记住这里要写个跳转的页面才能成功跳转到想要的页面-->
        用户名:<input type="text" name="username"><br>
        密码:<input type="text" name="password"><br>
        验证码:<input type="text" name="code"><img src="validate"><br>
        <input type="submit">
    </form>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值