BlogContacts
BlogGamesContacts

{{item}}

Writing a site on pure servlets

10.08.2018

Java, Servlet, HTML

Source code
Known technologies of Java - JSP, JSF are based on a simple servers, and finally when loaded on application server they are compiled into a child class of HttpServlet, and then compiled into bytecode. This may be seen if you look at the application server, but this code, to put it mildly, is difficult to read - it is firstly not fully obvious, secondly every line of outgoing html code is formed by separate call of the method write from page context and thirdly the code becomes 10 times larger.Let's write a simple application on pure servlets with annotations. For example, let's make one servlet, that will build an outgoing html code based on a template with parameterized expressions (for substitution), and replace them with necessary values, a kind of Hello World on pure servlets.1. Project structure:
site-on-simple-servlets
│
├── src
│   └── main
│       ├── java
│       │   └── servlets
│       │       ├── . . .
│       │       ├── . . .
│       │       ├── AbstractServlet.java
│       │       └── Index.java
│       └── resources
│           └── templates
│               ├── . . .
│               ├── . . .
│               └── Index.html
│
└── pom.xml
2. Necessary Maven dependencies: pom.xml
XML
<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
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>site-on-simple-servlets</groupId>
    <artifactId>site-on-simple-servlets</artifactId>
    <name>site-on-simple-servlets</name>
    <version>1.0</version>
    <packaging>war</packaging>

    <properties>
        <java.version>1.8</java.version>
        <maven.compiler.plugin.version>3.8.0</maven.compiler.plugin.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    </properties>

    <build>
        <finalName>site-on-simple-servlets</finalName>
        <defaultGoal>package</defaultGoal>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>
3. This will be our servlet: Index.java
Java
package servlets;

@WebServlet(name = "index", urlPatterns = {"/index.html"})
public class Index extends AbstractServlet {

    protected static String page;

    public static long lastModified = System.currentTimeMillis();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doResponse(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doResponse(request, response);
    }

    @Override
    protected void preparePage(HttpServletRequest request, HttpServletResponse response)  throws ServletException, IOException {
        InputStream is = Index.class.getResourceAsStream("/templates/pages/index.html");
        InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);

        StringWriter sw = new StringWriter();

        int read;
        while ((read = isr.read()) != -1) {
            sw.write(read);
        }

        setPage(sw.toString().replace("<--say_hello-->", "Hello World!!"));
    }

    @Override
    protected long getLastModified(HttpServletRequest request) {
        return lastModified;
    }
}
Or, it is more correctly to say, two servlets - we'll use inheritance.4. AbstractServlet.java
Java
package servlets;

public abstract class AbstractServlet extends HttpServlet {

    protected String getPage() throws ServletException, IOException {
        return (String) this.getClass().getField("page").get(this.getClass());
    }

    protected void setPage(char[] page) {
        this.getClass().getField("page").set(this.getClass(), page);
    }

    protected void doResponse(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter pw = response.getWriter();

        if (this.getPage() == null) {
            this.preparePage(request, response);
        }

        pw.write(this.getPage());
    }

    protected abstract void preparePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
}
5. Template: index.html
HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><--say_hello--></title>
</head>
<body>
    <h1><--say_hello--></h1>
</body>
</html>
Some old versions of site drakonoved.org were built on the same principle, but a little more complicated. There were not only pages with static content, but also dynamic pages, binding Java and JavaScript. No frameworks were used - everything was written on pure servlets.
Privacy policy
Back to Top