【问题标题】:confused with the design of servlet与 servlet 的设计混淆
【发布时间】:2014-10-17 15:12:19
【问题描述】:

我想创建一个以 Json 格式接收数据并将数据存储在数据库中的 servlet。当我通过http请求向servlet发送数据时,它将与表建立连接,创建表并存储数据。创建连接和表的代码只能在第一次完成。我无法设计出第一次创建连接和表并在其余时间将数据存储到行中的代码设计

我的代码如下:-

public class Master extends 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    handle(request, response);
}

private void handle(HttpServletRequest req, HttpServletResponse resp) {
    JSONObject jsonObject = null;
    if ( req.getMethod().equalsIgnoreCase("POST")) {
        try {
            String jsonString = extractJsonBody()

           /* code for connection with database
            create table
            store the data */

        } catch (Exception e) {
            System.out.println("Json in bad format");
        }
    }
}

【问题讨论】:

标签: java servlets web-applications


【解决方案1】:

你可以使用servlet的init方法进行连接和表 如果数据库中不存在表,则使用条件检查创建。

public void init(ServletConfig config) throws ServletException { // Store the ServletConfig object and log the initialization 
super.init(config);`` 
// create the database connection and table creation with condition if 
//table do not exist in DB
 }

【讨论】:

  • 是否可以在启动服务器时执行一些代码,然后再向 servlet 发出任何 POST/Get 请求
【解决方案2】:

您可以使用 Singleton 设计模式来创建数据库和表。

参见下面的示例以使用单例模式创建数据库

public class DataBaseConnector {
    private static DataBaseConnector dbConnector = new DataBaseConnector();

    private Connection dbConnection;

    private DataBaseConnector() {        
        // create database connection here 
    }

    public static DataBaseConnector getInstance() {
        if(dbConnector == null) {
            dbConnector = new DataBaseConnector();
        }
        return dbConnector;
    }

    public Connection getDbConnection() {
        return dbConnection;
    }
}

使用应用程序创建数据库架构不是一个好习惯。为此使用单独的脚本。

【讨论】:

    猜你喜欢
    • 2012-12-27
    • 2015-01-17
    • 1970-01-01
    • 2011-09-09
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2017-05-07
    • 1970-01-01
    相关资源
    最近更新 更多