servlet で HelloWorld
tomcat も入れたので、Servlet で HelloWorld くらい表示してみようと思う。
参考URLはこちら
http://thinkit.co.jp/free/article/0708/2/6?page=0,0
いつもの通り、ほぼコピペです。
まず servlet 系の source をコンパイルするには CLASSPATH に追加設定が必要。
export CLASSPATH=$CLASSPATH;$CATALINA_HOME/lib/servlet-api.jar
.bashrc に上記の設定を加えて、shell 叩き直し。
記事の中では、common/lib 内の jar ファイルを使用していますが、tomcat6 から common ディレクトリはなくなったようです。その他の ~/lib ディレクトリと統合して、一つの lib ディレクトリになったそうな。
HelloWorld.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorld extends HttpServlet{
public void service(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello World</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello World</h1>");
out.println("</body>");
out.println("</html>");
out.close();
}
}
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<servlet>
<servlet-name>
hello
</servlet-name>
<servlet-class>
HelloWorld
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>
hello
</servlet-name>
<url-pattern>
/hello/
</url-pattern>
</servlet-mapping>
</web-app>
はそのまんまコピー。
javac HelloWorld.java
でコンパイルし、HelloWorld.class を作成。
あとは、webapps 配下に次の各ディレクトリを作成し、
- webapps/helloworld
- webapps/helloworld/WEB-INF
- webapps/helloworld/WEB-INF/classes
- webapps/helloworld/WEB-INF/lib
web.xml と HelloWorld.class をそれぞれ、
- webapps/helloworld/WEB-INF/web.xml
- webapps/helloworld/WEB-INF/classes/HelloWorld.class
に配置する。
ブラウザ上から、
http://localhost:8080/helloworld/hello/
にアクセスすると見事 HelloWorld !
※ URL の末尾に「/」を入れないと、エラーになります。
何かしら設定すると、「/」なしを「/」ありと読んでくれたような気もしますが。