简体   繁体   English

Rest Web Services API的预处理

[英]Preprocessing for rest web services api

I am building a simple web service in Java using Jersey to add and delete users from a DB. 我正在使用Jersey构建Java中的简单Web服务,以便从数据库中添加和删除用户。

Where is the best way to do the preprocessing for this, eg if i want to establish a connection with the DB? 对此进行预处理的最佳方法在哪里,例如,如果我想与数据库建立连接?

@Path("/user/service")
public class UserService 
{
    private Connection connect = null;
    final private String host = "localhost";
    final private String user = "qwerty";
    final private String passwd = "mysql";
    final private String database = "user_db";

    public void connectToDB() throws Exception 
    {
        Class.forName("com.mysql.jdbc.Driver");
        connect = DriverManager.getConnection("jdbc:mysql://" + host + "/"
                        + database + "?" + "user=" + user + "&password=" + passwd);
    }

    @PUT
    @Path("/create")
    public void createUser(){
        System.out.println("Inside Create User method");
    }

    @GET
    @Path("/get/{id}")
    public String getUser(@PathParam("id")String userid, @QueryParam("first")String first){
        System.out.println("GET: " + first);
    }
}

I want to call connectToDB() once at the start and not inside every request. 我想在开始时调用一次connectToDB(),而不是在每个请求中调用一次。

Thanks 谢谢

You can create singleton class and move your connectToDB logic into that singleton class and when invoked that singleton class will make a DB connection which can be used in all subsequent calls from the API. 您可以创建单例类,并将connectToDB逻辑移到该单例类中,当调用该单例类时,将建立一个数据库连接,该连接可用于从API进行的所有后续调用中。

You can also create a connection inside a static block but that's not a clean way imo. 您也可以在静态块内创建连接,但这不是imo的干净方法。

More on singleton 有关单例的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM