【简单的三层架构】简单的三层架构 查询数据库所有数据并且展示在前端

表现层


@WebServlet("/selectAllServlet")
public class selectAllServlet extends HttpServlet {
    private  final BrandService brandService = new BrandService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
//          调用业务逻辑层查询数据
        List brands = brandService.selectAll();
//           将查询到底数据放到request域中,用来请求转发
        request.setAttribute("brands", brands);
//             将数据转发到jsp页面用来展示
        request.getRequestDispatcher("brandSelect.jsp").forward(request,response);
    }

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

业务逻辑层

public class BrandService {
//          业务逻辑层操作数据库查询数据
    public List selectAll(){
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        List brands = mapper.selectAll();
        sqlSession.close();
        return brands;
    }
}

数据访问层

public interface BrandMapper {
//    数据库查询
    List selectAll();
}

数据库操作





    
    

    

前端页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


    Title




<%--便利集合--%> <%--${brands}后端传过来的集合--%> <%--brand集合中每一个实体类对象--%> <%--a标签用来跳转,并且要带上当前数据的id--%>
序号 品牌名称 企业名称 排序 品牌介绍 状态 操作
${brand.id} ${brand.brandName} ${brand.companyName} ${brand.ordered} ${brand.description} 启用 禁用 修改 删除

工具类

public class SqlSessionFactoryUtils {

    private static SqlSessionFactory sqlSessionFactory;

    static {
        //静态代码块会随着类的加载而自动执行,且只执行一次

        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static SqlSessionFactory getSqlSessionFactory(){
        return sqlSessionFactory;
    }
}

你可能感兴趣的:(前端,架构)