トップ  eラーニング  書籍紹介  用語集

Google

言語

開発環境

Webアプリ/ミドル

データベース

OS/ネットワーク

ITスキル

海外サイト翻訳

書籍検索

用語検索

日本語出力&他のクラスを使用するServlet-tomcat上のWebアプリ作成

動作確認した環境

アプリの構成

□tomcatホームディレクトリ
├□conf
|└□Catalina
|  └□localhost
|    └◆test.xml
└□webapps
  └□test
    └□WEB-INF
      ├□classes
      |├◆SampleServlet.class 
      |└◆User.class
      └◆web.xml

コンテキスト指定(test.xml)


<Context path="/test"
         docBase="<tomcatホームディレクトリ>/webapps/test"
         debug="0" reloadable="true">
</Context>

Servlet(SampleServlet.java)

日本語が文字化けしないように文字コードをUTF-8に合わせる。


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 SampleServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws IOException, ServletException {
        User user = new User();
        // 日本語が文字化けしないように文字コードを合わせる↓
        res.setContentType("text/html; charset=UTF-8");
        PrintWriter out = res.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>サンプル</title>");
        out.println("</head>");
        out.println("<body>");
        out.println(user.getName());
        out.println("</body>");
        out.println("</html>");
    }
}

他のクラス(User.java)


public class User {
    private String name = null;
    public User() {
        name = "ユーザ";
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

コンパイル

java -classpath <tomcatホーム>/lib/servlet-api.jar:. SampleServlet.java User.java

配備記述子(web.xml)


<?xml version="1.0" encoding="UTF-8" ?>

<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>sample</servlet-name>
        <servlet-class>SampleServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>sample</servlet-name>
        <url-pattern>/sample</url-pattern>
    </servlet-mapping>
</web-app>

動作確認

ブラウザより、「http://<tomcatサーバのホスト>:8080/test/sample」へアクセス。 「ユーザ 」と表示される。

戻る

Loarding…

グループサイト  zealseeds  zealseedsラーニング  zealseedsブックス  名か字  名科辞典  幸福の木の育て方

Copyright (C) 2007-2011 zealseeds. All Rights Reserved.お問合せ