content-management-systemdotcms

How to retrieve dynamic content from database?


I'm evaluating java-based cms and selecting one as our cms ,now I'm learning dotcms , I need to know how to retrieve content from db like traditional jsp/bo does,I'm new to dotcms, the official documents only tell how to add static content but dynamic content , say running a sql and getting the wanted data ,then putting them into pages. We are doing an internal website where employees can browse news, events, colleagues information etc which managed through a cms, the information is definitely dynamic and updated regularly. We plan to use spring mvc on the project. Any ideas on the question?

thank you.


Solution

  • To get this to work you need to do a few things:

    1. If you want to use a different database, then you can add a new resource to the conf/Catalina/localhost/ROOT.xml file. If you want to use the dotCMS database to host the additional tables then you can skip this step.

    2. From within your java code you can get a database connection using the DbConnectionFactory class. Now you can read the data from the database. Here's an example: import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement;

      Connection conn = DbConnectionFactory.getConnection();
      Statement selectStatement;
      try {
        selectStatement = conn.createStatement();
        try {
          selectStatement.execute("SELECT * FROM your_table WHERE your_where_clause etc...");
          ResultSet result = selectStatement.getResultSet();
          if (result.next()) {
            .. do your stuff here...
            // for example:
            // Long dbId = result.getLong("Id");
            // String stringField = result.getString("stringFieldName");
            // int intField = result.getInt("intFieldName");
          } finally  {
            selectStatement.close();
          }
        } catch (SQLException e1) {
           // Log the error here
        }
      

      }

    3. If you want to use this data in velocity you'll need to create a viewtool. Read more about that here: http://dotcms.com/docs/latest/DynamicPluginsViewtool