outオブジェクト

広告

outオブジェクトはJSPの実行結果をクライアントへの出力するためのオブジェクトで、JspWriterクラスのオブジェクトです。

まずJspWriterのクラス図を見て下さい。

java.lang.Object
  java.io.Writer
    javax.servlet.jsp.JspWriter

public abstract class JspWriter
extends java.io.Writer

暗黙オブジェクトは既にオブジェクトが作成された状態となっているのでメソッドについてだけ確認していきます。

printメソッドとprintlnメソッド

outオブジェクトの主な用途は引数に指定した値を文字列に変換してから出力バッファに出力するために使います。

例えば次のようにJSPページ内で記述されていた場合を考えて見ます。

<p>
<%
  out.println("サンプル");
%>
</p>

これは次のように記述した場合と同じになります。

<p>
サンプル
</p>

メソッドとしては「print」メソッドと「println」メソッドがあり「println」メソッドの方は改行も出力されます。ただし出力されるHTMLページ内で改行は行われますが、<br>に変換されるわけではないのでHTMLページの表示上では違いはありません。

また例として「println」メソッドの引数には各データ型毎に一通りの種類が用意されています。

abstract voidprintln(boolean x)
abstract voidprintln(char x)
abstract voidprintln(char[] x)
abstract voidprintln(double x)
abstract voidprintln(float x)
abstract voidprintln(int x)
abstract voidprintln(long x)
abstract voidprintln(java.lang.Object x)
abstract voidprintln(java.lang.String x)
abstract voidprintln()

このため、「println」メソッドの引数にはデータ型を意識せずに利用することができます。「print」メソッドも同様です。それでは1つだけ定義を確認してみます。

Print an integer and then terminate the line. This method behaves as
though it invokes print(int) and then println(). 

Parameters:
  x - the int to write 
Throws: 
  java.io.IOException - If an error occured while writing

その他のメソッド

それ以外に用意されているメソッドをいくつか紹介しておきます。

まずは出力バッファをクリアする「clear」メソッドです。

Clear the contents of the buffer. If the buffer has been already been
flushed then the clear operation shall throw an IOException to signal
the fact that some data has already been irrevocably written to the 
client response stream. 

Throws: 
  java.io.IOException - If an I/O error occurs

次に出力バッファをフラッシュする「flush」メソッドです。

Flush the stream. If the stream has saved any characters from the 
various write() methods in a buffer, write them immediately to their
intended destination. Then, if that destination is another character
or byte stream, flush it. Thus one flush() invocation will flush all
the buffers in a chain of Writers and OutputStreams. 

The method may be invoked indirectly if the buffer size is exceeded. 

Once a stream has been closed, further write() or flush() 
invocations will cause an IOException to be thrown. 

Throws: 
  java.io.IOException - If an I/O error occurs

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。