
Short answer: To serve an RSS feed from a Javalin application, add a GET handler for /feed.xml, read the newest published rows with JDBC, build the document with the XML tools that ship with the JDK so every value is escaped, format dates with DateTimeFormatter.RFC_1123_DATE_TIME in UTC and return the result with the application/rss+xml content type. Compute an ETag from the newest publication time and answer a matching If-None-Match header with a 304, test the address with curl and a validator, then give the public URL to an auto-poster so every new item reaches your social channels.
Javalin is a small web framework for Java and Kotlin that runs on Jetty and stays out of the way: no annotations, no dependency injection container, no configuration beyond a few lines of code. It is a popular choice for APIs, internal tools and modest content sites that want the Java ecosystem without the weight of a full application server. Sooner or later such an application publishes something that people want to follow: articles, release notes, listings or event dates. A feed is the standard way to let readers, aggregators and auto-posters watch that content without an account or an API key. This guide builds a complete Javalin RSS feed with escaping, stable identifiers, correct dates and conditional requests, explains each decision and ends with the checks that keep the feed dependable once other systems rely on it.
A feed is worth adding whenever the application publishes things that people outside it want to follow:
If your content already lives in a blog or a CMS, use the feed it provides instead; see how to find your WordPress feed link. If you run Spring Boot rather than Javalin, see the Spring Boot guide with Rome, and for Kotlin with Ktor see the Ktor guide. The approach below uses only Javalin, JDBC and the JDK, which keeps the dependency list short.
Create a Maven or Gradle project and add Javalin and a JDBC driver. The example uses SQLite, but the query and the document builder stay the same with PostgreSQL or MySQL.
<dependency>
<groupId>io.javalin</groupId>
<artifactId>javalin</artifactId>
<version>6.3.0</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.46.1.0</version>
</dependency>Keep the public address of the site in configuration rather than reading it from the incoming request. Behind a reverse proxy, the request may show an internal host name or a plain http scheme, and a feed full of internal addresses is useless to every reader. The example reads the address from an environment variable with a safe default.
The handler below queries the published rows, builds a DOM document, serialises it and writes the response. The condition on the publication time matters: without it, an item scheduled for tomorrow would appear in the feed today, and an auto-poster would share it before it exists on the website. Publication times are stored as epoch seconds in UTC.
import io.javalin.Javalin;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;
import java.sql.*;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class FeedApp {
static final String SITE_URL = System.getenv().getOrDefault("SITE_URL", "https://www.example.com");
public static void main(String[] args) {
Javalin app = Javalin.create();
app.get("/feed.xml", ctx -> {
try (Connection db = DriverManager.getConnection("jdbc:sqlite:data/site.db");
PreparedStatement st = db.prepareStatement(
"SELECT id, title, slug, summary, published_at FROM posts " +
"WHERE status = 'published' AND published_at <= ? " +
"ORDER BY published_at DESC LIMIT 20")) {
st.setLong(1, Instant.now().getEpochSecond());
ResultSet rs = st.executeQuery();
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
Element rss = doc.createElement("rss");
rss.setAttribute("version", "2.0");
rss.setAttribute("xmlns:atom", "http://www.w3.org/2005/Atom");
doc.appendChild(rss);
Element channel = doc.createElement("channel");
rss.appendChild(channel);
add(doc, channel, "title", "Example News");
add(doc, channel, "link", SITE_URL + "/");
add(doc, channel, "description", "The latest posts from Example News");
add(doc, channel, "language", "en");
Element self = doc.createElement("atom:link");
self.setAttribute("href", SITE_URL + "/feed.xml");
self.setAttribute("rel", "self");
self.setAttribute("type", "application/rss+xml");
channel.appendChild(self);
long newest = 0;
int count = 0;
while (rs.next()) {
long published = rs.getLong("published_at");
if (newest == 0) newest = published;
count++;
Element item = doc.createElement("item");
add(doc, item, "title", rs.getString("title"));
add(doc, item, "link", SITE_URL + "/" + rs.getString("slug") + "/");
Element guid = add(doc, item, "guid", "post-" + rs.getLong("id"));
guid.setAttribute("isPermaLink", "false");
add(doc, item, "pubDate", DateTimeFormatter.RFC_1123_DATE_TIME
.format(Instant.ofEpochSecond(published).atOffset(ZoneOffset.UTC)));
add(doc, item, "description", rs.getString("summary"));
channel.appendChild(item);
}
String etag = "\"" + newest + "-" + count + "\"";
ctx.header("ETag", etag);
ctx.header("Cache-Control", "public, max-age=300");
if (etag.equals(ctx.header("If-None-Match"))) {
ctx.status(304);
return;
}
var tf = TransformerFactory.newInstance().newTransformer();
tf.setOutputProperty(OutputKeys.INDENT, "yes");
tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
StringWriter out = new StringWriter();
tf.transform(new DOMSource(doc), new StreamResult(out));
ctx.contentType("application/rss+xml; charset=utf-8").result(out.toString());
}
});
app.start(7070);
}
static Element add(Document doc, Element parent, String name, String text) {
Element e = doc.createElement(name);
e.setTextContent(text);
parent.appendChild(e);
return e;
}
}Run the class, open the route in a browser or with curl, and you should see well-formed XML with at most twenty items, newest first. Because the text of every element is set with setTextContent, the serialiser escapes ampersands and angle brackets for you, which is the main reason to build a document rather than join strings by hand. In a real application, use a connection pool rather than opening a connection in the handler.
| Feed field | Source in the example | Rule to keep |
|---|---|---|
| title | The title column | Plain text, escaped, no markup |
| link | Site address plus slug | Absolute address that returns 200 directly |
| guid | The row id with a prefix | Never changes, even if the slug changes |
| pubDate | The publication timestamp in UTC | RFC 1123 with GMT, never in the future |
| description | The summary column | One or two sentences that make sense alone |
The identifier is the most important decision. An auto-poster remembers which items it has already shared by their GUID. If the value changes when someone edits a slug or republishes an article, the same story is shared again. Using the database id with a fixed prefix avoids that. The problem and its fixes are described in why a feed auto-posts the same article twice.
RSS dates follow RFC 822, with English abbreviations for days and months. The RFC_1123_DATE_TIME formatter in java.time prints exactly that shape, and because the instant is converted to UTC first, the zone is written as GMT, which every parser accepts. The formatter always uses English names whatever the default locale of the server, so there is no risk of localised month names that readers cannot parse. Do not use ISO_INSTANT here; that format belongs to Atom feeds, and many RSS readers reject it. If a validator complains about dates, read the guide to RSS date format errors.
Auto-posters, readers and search engines request a feed often, and almost always nothing has changed. The handler above deals with that in two ways. It computes an ETag from the newest publication time and the number of items, sets the header on every response and, when the If-None-Match header of the request matches, finishes with a 304 and no body. The Cache-Control header lets a proxy or a content delivery network keep the response for a few minutes. Together they cut the cost of each check to one query, and you can go further by caching the rendered document in memory for the same period.
If you edit old items and want the feed to change, store an updated time and include it in the ETag. Do not cache for hours, because a long cache delays every new post by the same amount. The background to both techniques is in the guide to ETags and conditional GET và the guide to feed caching.
In production, package the application as a runnable jar, run it under a process manager and put a reverse proxy in front of it that terminates HTTPS. Keep the public address in your own setting rather than trusting forwarded headers, so that links in the feed are always correct. Check that the proxy does not strip the ETag and Cache-Control headers and that it does not add its own long cache that keeps old XML for too long. After every deployment, request the feed once to confirm that it still returns 200 and that the address is exactly the one you gave to the auto-poster. If the feed ever stops updating, this checklist shows what to inspect first.
An auto-poster is more useful when each item carries a picture. Add an enclosure element with the url, length and type attributes, filled from an image column, and use an absolute https address and a file of reasonable size. Without an image, many networks show a plain text card. How tools read these elements is explained in the guide to enclosure tags. If a summary legitimately contains HTML, keep it escaped as the serialiser does, or wrap it in a CDATA section with createCDATASection, as described in the CDATA guide.
There is a longer checklist in the feed validation guide and a short curl routine in the guide to debugging a feed with curl. The Javalin documentation covers handlers, headers and content types in more depth.
PostRSS has been publishing RSS and Atom feeds to social networks since 2014. Paste the address of your feed route, connect your accounts and choose how each post is built from the title, the description or the page title. PostRSS checks the feed as often as every minute and shares each new item, with its image and link, to the channels you choose among 66 supported networks, messengers, team chats and blogs, including LinkedIn, X, Bluesky, Mastodon and Telegram. Keyword filters, UTM parameters and posting windows let you tune each channel, and webhooks connect PostRSS to your own systems. See the PostRSS features page and the plan limits on the pricing page. More developer guides are under the Technical Guide tag.
Javalin needs only a handler, a query and the XML tools of the JDK to serve a dependable RSS feed: select published items dated in the past, let the DOM serialiser escape every value, use a stable GUID, format dates in RFC 1123 UTC, build links from a configured public address and send the result with the right content type, an ETag and a short cache. Test the route with curl and a validator, keep the address unchanged and connect it to an auto-poster. After that, every item you publish can reach your social channels automatically.
No. Javalin has no feed support, but the XML tools that ship with the JDK produce a valid feed from a DOM document, and a few lines in the handler add the ETag and cache headers that make the route cheap to poll.
The serialiser escapes every text value, so a title with an ampersand or an angle bracket cannot break the XML. A template works too, but you must remember to escape every value yourself.
Yes. Rome is the common choice in the Java world and produces RSS and Atom from the same model. The handler stays the same; only the document building changes.
Between ten and twenty of the newest published items is enough. An auto-poster only needs recent items, and a smaller file is faster to download and parse.
Give every item a stable identifier and use it as the GUID. Avoid editing the publication date of items that are already public, because some tools treat a changed date as a new item.
Yes. PostRSS reads any valid RSS or Atom address that is reachable without a login. Paste the address, connect your channels and new items are shared as soon as they appear.
What changed in the networks, what broke, and how to fix it before it costs you reach.
Do Internet Solutions, đội ngũ đứng sau PostRSS, phát triển. Mỗi sản phẩm giúp bạn tiết kiệm thời gian theo một cách riêng.