从零写一个Java WEB框架(一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/GG_and_DD/article/details/80646626
  • 该系列,其实是对《架构探险》这本书的实践。本人想记录自己的学习心得所写下的。
  • 从一个简单的Servlet项目开始起步。对每一层进行优化,然后形成一个轻量级的框架。
  • 每一篇,都是针对项目的不足点进行优化的。
  • 项目已放上github

项目的基本搭建。

一个非常基础的Servlet项目。
image.png

基本功能是:
- 对数据表-客户表进行数据处理。

部分代码讲解

例如:客户的数据获取

Controller 层

/*
*  获取客户端的数据
* */
@WebServlet("/customer_show")
public class CustomerShowServlet  extends HttpServlet{

    private static CustomerService customerService;

    static {
        customerService = new CustomerService();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method != null) {
            if ("getList".equals(method)) {
                List<Customer> customerList =
                        customerService.getCustomerList();
                PrintWriter writer = resp.getWriter();
                System.out.println(customerList);
                writer.write(customerList.toString());
                writer.flush();
                writer.close();


            }
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

思路:
- 通过HttpServletRequest 获取到路径上的值,然后对比值,执行相应的Servlet方法。

server 层中的获取所有客户信息的方法

 /*
     *  获取客户列表
     * */
    public List<Customer> getCustomerList() {
        Connection conn = null;

        try {
            List<Customer> list = new ArrayList<>();
            String sql = "select * from customer";
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                Customer customer = new Customer();
                customer.setId(resultSet.getLong("id"));
                customer.setName(resultSet.getString("name"));
                customer.setContact(resultSet.getString("contact"));
                customer.setTelephone(resultSet.getString("telephone"));
                customer.setEmail(resultSet.getString("email"));
                customer.setRemark(resultSet.getString("remark"));
                list.add(customer);

            }

            return list;
            }

思路:
- 从数据库中获取到数据后,将数据填写到对象里面

缺陷:
- 代码太过臃肿。本来获取客户列表数据就3步。1 查询 2 数据赋值给新对象 3 将新对象存进集合。 在第二步 数据赋值给对象 代码灵活性不高,如果对象类有修改,这里也将需要修改,耦合度高。所以需要赋值这一步需要封装一下。

在CustomerService 层 加载数据库

public class CustomerService {

    private static final String DRIVER;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;

    private static final Logger logger = LoggerFactory.getLogger(CustomerService.class);


    static{
        System.out.println("配置加载");
        Properties conf = PropsUtil.loadProps("config.properties");
        DRIVER = conf.getProperty("jdbc.driver");
        URL = conf.getProperty("jdbc.url");
        USERNAME = conf.getProperty("jdbc.username");
        PASSWORD = conf.getProperty("jdbc.password");

        //JDBC流程第一步 加载驱动
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            logger.error("加载jdbc驱动失败",e);
            e.printStackTrace();
        }
    }

思路:
- 利用静态代码块,加载JDBC驱动

缺陷:
- 把JDBC驱动加载卸载Service层,那么每个Service类都需要加载一次JDBC驱动。所有应该提取出来,只需要加载一次就可以。

加载Properties文件 工具类

 /*
    *  加载属性文件
    * */
    public static Properties loadProps(String fileName) {
        Properties props = null;
        InputStream is = null;

        //获取fileName的InputStream

        try {
            is = PropsUtil.class.getClassLoader().getResourceAsStream(fileName);
            props = new Properties();
            props.load(is);
            return props;
        } catch (IOException e) {
            log.error("加载Properties错误",e);
            e.printStackTrace();

        }finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("流关闭失败",e);
                    e.printStackTrace();
                }
            }
        }

        return null;

    }

访问

URL: localhost:8080/customer_show?method=getList

结果:
image.png

总结

一个项目的基本结构已经是实现出来了。从前端访问到返回数据。可以说现在是可以完成基本业务的。但是这个项目如果需要扩展,那需要修改的地方就会很多。所以,为了增加项目的可扩展性,将会对项目进行优化,主要方向是对代码进行封装,降低耦合度。

猜你喜欢

转载自blog.csdn.net/GG_and_DD/article/details/80646626
今日推荐