In this post, we’ll explore Servlets and Filters in a lightweight way using Javalin, a modern Java web framework that simplifies HTTP handling. We’ll write easy-to-follow code examples and show their outputs.
1. What Are Servlets and Filters?
Servlet
- A Servlet is a Java class that handles HTTP requests (GET, POST, etc.) and generates responses.
- It’s the backbone of Java web applications (before frameworks like Spring took over).
- Example use cases: API endpoints, dynamic content generation.
Filter
- A Filter intercepts requests/responses before they reach a Servlet (or after they leave it).
- Useful for:
- Authentication/Authorization
- Logging
- Input validation
- Response compression
2. Setting Up Javalin
Javalin is a minimalist framework that simplifies Servlet/Filter-like behavior without XML configurations. First, add the dependency (Maven):
<dependency>
<groupId>io.javalin</groupId>
<artifactId>javalin</artifactId>
<version>6.0.0</version>
</dependency>
3. Basic Servlet Example in Javalin
In Javalin, a Servlet-like behavior is achieved using get(), post(), etc., methods.
Example: Simple GET Endpoint
import io.javalin.Javalin;
public class SimpleServlet {
public static void main(String[] args) {
Javalin app = Javalin.create().start(7070);
app.get("/hello", ctx -> {
ctx.result("Hello from Javalin Servlet!");
});
}
}
Output
- Visit
http://localhost:7070/helloin a browser. - Response:
Hello from Javalin Servlet!
4. Basic Filter Example in Javalin
Javalin doesn’t have a direct Filter interface, but we can mimic it using middleware (before() and after() hooks).
Example: Logging Filter
import io.javalin.Javalin;
public class LoggingFilter {
public static void main(String[] args) {
Javalin app = Javalin.create()
.before(ctx -> {
System.out.println("[Filter] Request received: " + ctx.method() + " " + ctx.path());
})
.after(ctx -> {
System.out.println("[Filter] Response sent: " + ctx.status());
})
.start(7070);
app.get("/greet", ctx -> {
ctx.result("Greetings from Javalin!");
});
}
}
Output
- Visit
http://localhost:7070/greet. - Console Logs:
[Filter] Request received: GET /greet [Filter] Response sent: 200 - Browser Response:
Greetings from Javalin!
5. Advanced Filter: Authentication Middleware
Let’s implement a simple auth filter that checks for a token.
Example: Auth Middleware
import io.javalin.Javalin;
import io.javalin.http.Handler;
public class AuthFilter {
public static void main(String[] args) {
Javalin app = Javalin.create().start(7070);
// Auth middleware
Handler authMiddleware = ctx -> {
String token = ctx.header("Authorization");
if (token == null || !token.equals("secret123")) {
ctx.status(401).result("Unauthorized");
return;
}
ctx.next(); // Proceed if authorized
};
// Protected endpoint
app.before("/protected/*", authMiddleware);
app.get("/protected/data", ctx -> {
ctx.result("This is secret data!");
});
// Public endpoint
app.get("/public", ctx -> {
ctx.result("Anyone can see this.");
});
}
}
Output
-
Without Token:
curl http://localhost:7070/protected/data- Response:
401 Unauthorized
-
With Token:
curl -H "Authorization: secret123" http://localhost:7070/protected/data- Response:
This is secret data!
-
Public Endpoint:
curl http://localhost:7070/public- Response:
Anyone can see this.
6. Conclusion
- Servlets in Javalin are handled via
get(),post(), etc., methods. - Filters can be implemented using middleware (
before()/after()hooks). - Javalin’s simplicity makes it great for learning web fundamentals.
SEO Meta Tags
<meta name="description" content="Learn Servlets and Filters in Java with Javalin examples. Easy code snippets for beginners.">
<link rel="canonical" href="https://example.com/javalin-servlets-filters" />
<meta name="keywords" content="Java,Javalin,Servlet,Filter,Middleware,Web Development,Tutorial">
Further Reading
Happy coding! 🚀