What is the proper way of handling configurations (database login and passwords, etc.) in a dynamic web project?

后端 未结 1 933
深忆病人
深忆病人 2021-02-09 17:20

I just got my hands on doing dynamic web programming using JSP. What is the proper way to handle the configurations?

For example, database name, host, login, and passwor

1条回答
  •  执笔经年
    2021-02-09 18:13

    Configuration is usually stored in a properties or XML file which is been placed in the application's runtime classpath or at a fixed location which is specified as a VM argument. A properties file can be accessed using java.util.Properties API. A XML file can be parsed using JAXP or JAXB.

    Here's an example of such a properties file:

    jdbc.url = jdbc:mysql://localhost:3306/javabase
    jdbc.driver = com.mysql.jdbc.Driver
    jdbc.username = java
    jdbc.password = d$7hF_r!9Y
    

    Assuming that it's named config.properties and it's been placed in the root of the classpath (or its root path is been added to the classpath), here's how you could load it from the classpath:

    Properties properties = new Properties();
    properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("config.properties"));
    String url = properties.getProperty("jdbc.url");
    String driver = properties.getProperty("jdbc.driver");
    String username = properties.getProperty("jdbc.username");
    String password = properties.getProperty("jdbc.password");
    // ...
    

    Here's an example of a XML file:

    
    
        
            jdbc:mysql://localhost:3306/javabase
            com.mysql.jdbc.Driver
            java
            d$7hF_r!9Y
        
    
    

    Assuming that it's called config.xml and it's been placed in the root of the classpath, here's an example how you could load it by JAXP:

    InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("config.xml");
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(input));
    XPath xpath = XPathFactory.newInstance().newXPath();
    String url = (String) xpath.compile("//config//jdbc//url").evaluate(document, XPathConstants.STRING);
    String driver = (String) xpath.compile("//config//jdbc//driver").evaluate(document, XPathConstants.STRING);
    String username = (String) xpath.compile("//config//jdbc//username").evaluate(document, XPathConstants.STRING);
    String password = (String) xpath.compile("//config//jdbc//password").evaluate(document, XPathConstants.STRING);
    // ...
    

    It's only a bit more verbose although JAXB can make life easier if it's a rather complex file.

    Securing the access to properties or XML files in turn is to be controlled at higher (OS/platform) level.

    See also:

    • Properties tutorial

    0 讨论(0)
提交回复
热议问题