Statistical mechanics of gravitating systems in static and cosmological backgrounds