Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

日本語を表示する Servlet の簡単な例

次の表示を出すサーブレットです。
servelet_jun25.png

フォルダー構造
/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("今晩は<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>

コンパイル

Make

Tomcat の再起動

sudo systemctl restart tomcat9
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away