Java Servlet read web page
last modified November 30, 2026
Java Servlet read web page tutorial shows how to read a web page in a Java web application using a Servlet.
Java Servlet
Servlet is a Java class which responds to a network request. Java servlets are used to build web applications. They run in servlet containers such as Tomcat or Jetty. Modern-day Java web development uses frameworks that are built on top of servlets, including Spring and Vaadin.
Apache Commons Validator is a Java library that validates data. We use this library to validate correct URL values.
Java Servlet read web page example
In the following example, we read a web page with InputStream
and display the HTML code of the page to the client. The name of the web page
is sent from an input tag of an HTML form.
$ tree
.
├── nb-configuration.xml
├── pom.xml
└── src
├── main
│ ├── java
│ │ └── com
│ │ └── zetcode
│ │ ├── service
│ │ │ └── WebPageReader.java
│ │ └── web
│ │ └── ReadWebPage.java
│ └── webapp
│ └── index.html
└── test
└── java
This is the project structure.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.zetcode</groupId>
<artifactId>JavaServletReadWebpage</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>25</maven.compiler.release>
</properties>
<dependencies>
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.1.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.5.1</version>
</plugin>
<plugin>
<groupId>org.eclipse.jetty.ee11</groupId>
<artifactId>jetty-ee11-maven-plugin</artifactId>
<version>12.1.15</version>
<configuration>
<webApp>
<contextPath>/app</contextPath>
</webApp>
</configuration>
</plugin>
</plugins>
</build>
</project>
The jakarta.servlet-api artifact provides the Servlet API. The
example uses the JDK's java.net.http.HttpClient, so no additional
HTTP client dependency is needed. The Jetty plugin runs the application with
mvn jetty:run at /app.
package com.zetcode.web;
import com.zetcode.service.WebPageReader;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(name = "ReadWebPage", urlPatterns = {"/ReadWebPage"},
initParams = { @WebInitParam(name = "allowedHosts",
value = "example.com,www.example.com") })
public class ReadWebPage extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain;charset=UTF-8");
String page = request.getParameter("webpage");
String allowedHosts = getServletConfig().getInitParameter("allowedHosts");
String content = new WebPageReader(page, allowedHosts).getWebPageContent();
PrintWriter out = response.getWriter();
out.print(content);
}
}
The ReadWebPage servlet reads the contents of the given web page and
sends the text to the client.
response.setContentType("text/plain;charset=UTF-8");
The response is in plain text and the text encoding is UTF-8.
String page = request.getParameter("webpage");
String allowedHosts = getServletConfig().getInitParameter("allowedHosts");
We get the name of the web page from the request parameter with
getParameter. The allowedHosts init parameter
contains the comma-separated host allowlist.
String content = new WebPageReader(page, allowedHosts).getWebPageContent();
WebPageReader is used to get the contents of the web page.
PrintWriter out = response.getWriter(); out.print(content);
We send the text to the client through a character writer.
package com.zetcode.service;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Arrays;
import java.util.Locale;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
public class WebPageReader {
private static final int MAX_BYTES = 1_000_000;
private final String webpage;
private final Set<String> allowedHosts;
public WebPageReader(String webpage, String allowedHosts) {
this.webpage = webpage;
String hosts = allowedHosts == null ? "" : allowedHosts;
this.allowedHosts = Arrays.stream(hosts.split(","))
.map(String::trim)
.filter(host -> !host.isEmpty())
.map(host -> host.toLowerCase(Locale.ROOT))
.collect(Collectors.toUnmodifiableSet());
}
public String getWebPageContent() {
if (webpage == null || webpage.isBlank()) {
return "Invalid URL; use http(s)://www.example.com format";
}
try {
URI uri = URI.create(webpage);
if (!isAllowed(uri)) {
return "URL is not allowed";
}
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NEVER)
.build();
HttpRequest request = HttpRequest.newBuilder(uri)
.timeout(Duration.ofSeconds(10))
.header("User-Agent", "ZetCode Servlet Example")
.GET()
.build();
HttpResponse<InputStream> response = client.send(request,
HttpResponse.BodyHandlers.ofInputStream());
try (InputStream is = response.body()) {
if (response.statusCode() != 200) {
return "Cannot read webpage: HTTP " + response.statusCode();
}
byte[] bytes = is.readNBytes(MAX_BYTES + 1);
if (bytes.length > MAX_BYTES) {
return "Web page is too large";
}
return new String(bytes, StandardCharsets.UTF_8);
}
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return "Interrupted while reading the webpage";
} catch (IllegalArgumentException | IOException ex) {
Logger.getLogger(WebPageReader.class.getName())
.log(Level.SEVERE, null, ex);
return "Cannot read webpage";
}
}
private boolean isAllowed(URI uri) {
String scheme = uri.getScheme();
String host = uri.getHost();
return ("http".equalsIgnoreCase(scheme)
|| "https".equalsIgnoreCase(scheme))
&& host != null
&& allowedHosts.contains(host.toLowerCase(Locale.ROOT));
}
}
WebPageReader reads the contents of a web page.
private boolean isAllowed(URI uri) {
String scheme = uri.getScheme();
String host = uri.getHost();
return ("http".equalsIgnoreCase(scheme)
|| "https".equalsIgnoreCase(scheme))
&& host != null
&& allowedHosts.contains(host.toLowerCase(Locale.ROOT));
}
Before we read the web page, we check that the URL uses HTTP or HTTPS and that its host is in the allowlist. This prevents the servlet from being used as a proxy for internal services.
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.followRedirects(HttpClient.Redirect.NEVER)
.build();
HttpRequest request = HttpRequest.newBuilder(uri)
.timeout(Duration.ofSeconds(10))
.header("User-Agent", "ZetCode Servlet Example")
.GET()
.build();
HttpResponse<InputStream> response = client.send(request,
HttpResponse.BodyHandlers.ofInputStream());
We use the JDK HttpClient with connect and read timeouts. Redirects
are disabled so an allowed host cannot redirect the request to another host.
try (InputStream is = response.body()) {
if (response.statusCode() != 200) {
return "Cannot read webpage: HTTP " + response.statusCode();
}
byte[] bytes = is.readNBytes(MAX_BYTES + 1);
if (bytes.length > MAX_BYTES) {
return "Web page is too large";
}
return new String(bytes, StandardCharsets.UTF_8);
}
We read at most one megabyte and decode it as UTF-8. The size cap prevents a large response from exhausting server memory.
<!DOCTYPE html>
<html>
<head>
<title>Home page</title>
<meta charset="UTF-8">
</head>
<body>
<form action="ReadWebPage">
<label for="page">Enter an allowed web page URL:</label>
<input type="text" id="page" name="webpage"
value="https://example.com/">
<button type="submit">Submit</button>
</form>
</body>
</html>
The home page contains the form, which sends the web page to be read to the
application. The URL must be absolute and its host must be listed in the
allowedHosts init parameter. The example allows
example.com and www.example.com.
In the screenshot we can see the contents of a simple web page.
In this tutorial, we have created a Java Servlet application, which reads the contents of a chosen web page and sends the HTML back to the client in plain text.
Verified output
The allowed host returns the page as plain text. A URL for a host that is not in the allowlist is rejected without making a network request.
$ curl 'localhost:8080/app/ReadWebPage?webpage=https://example.com/' <!doctype html><html lang=en><head>...<title>Example Domain</title>... $ curl 'localhost:8080/app/ReadWebPage?webpage=http://169.254.169.254/latest/meta-data/' URL is not allowed