[Java] A simple example of a Servlet that displays Japanese

less than 1 minute read

It is a servlet that outputs the following display. servelet_jun25.png

Folder structure Put the following folders under /var/lib/tomcat9/webapps.

$ tree /var/lib/tomcat9/webapps/hello
/var/lib/tomcat9/webapps/hello
└── WEB-INF
    ├── classes
    │  ├── HelloWorld.class
    │  ├── HelloWorld.java
    │  └── Makefile
    ├── lib
    └── web.xml

HelloWorld.java


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet {
public void doGet(HttpServletRequest request,
(HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();

out.println("<!DOCTYPE html>");
out.println("<html lang=\"ja\">");

out.println("<head>");
out.println("<meta http-equiv=\"CONTENT-TYPE\" content=\"text/html; charset=utf-8\" />");
out.println("</head>");

out.println("<body>");
out.println("Hello World!<p />");
out.println("Good Evening! PM 20:15<p />");
out.println("Tonight <p />");
out.println("</body>");
out.println("</html>");
out.close();
}
}

Makefile


HelloWorld.class: HelloWorld.java
javac -classpath /usr/share/tomcat9/lib/servlet-api.jar HelloWorld.java
clean:
rm -f *.class

web.xml


<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>
hello
</servlet-name>
<url-pattern>
/servlet/hello
</url-pattern>
</servlet-mapping>

</web-app>

compile

Make

Restart tomcat

sudo systemctl restart tomcat9