Tomcat ではエラーページがアプリケーション側で設定されていない場合、デフォルトのエラーページが表示されます。
アプリケーション側でエラーページを設定すればいいのですが、設定もれした場合にこういうページがいやだという場合は、カスタマイズして好きなページにすることができます。なお、下段のサーバーのバージョンを変更したい場合は、プロパティファイルの変更ですみます。これについては、Tomcat7のSecurity Considerationsのページに記述があります。
カスタマイズするには、ErrorPageReportValve を拡張することになります。拡張する場合には、プロジェクトを作成し、拡張したクラスとMBeansを記述したファイルを含めてjarにして、$CATALINA_HOME/lib に追加し、 server.xml を編集します。
まず、追加するクラスですが、org.apache.catalina.valves.ErrorReportValve を継承し、report メソッドをオーバーライドして適当なレスポンスを返すようにします。
package info.hilife_jp.tech.catalina.valves;
import java.io.IOException;
import java.io.Writer;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.util.ServerInfo;
public class MyErrorReportValve extends
org.apache.catalina.valves.ErrorReportValve {
@Override
protected void report(Request request, Response response,
Throwable throwable) {
// Do nothing on non-HTTP responses
int statusCode = response.getStatus();
// Do nothing on a 1xx, 2xx and 3xx status
// Do nothing if anything has been written already
if ((statusCode < 400) || (response.getContentWritten() > 0)) {
return;
}
try {
response.sendRedirect("http://www.yakult-swallows.co.jp/");
} catch (IOException e) {
// ignore
}
}
}
これは、エラー時に外部のURLにリダイレクトさせる例です。固定のHTMLページを表示させたい場合は、オーバーライドする元のメソッドを参考にHTMLを組み立てることになります。
次に、MBeans記述子です。作成したクラスと同じパッケージにmbeans-descriptors.xml を作成します。
<?xml version="1.0"?>
<mbeans-descriptors>
<mbean name="ErrorReportValve"
description="Implementation of a Valve that outputs HTML error pages"
domain="Catalina"
group="Valve"
type="info.hilife_jp.tech.catalina.valves.MyErrorReportValve">
<attribute name="asyncSupported"
description="Does this valve support async reporting."
is="true"
type="boolean"/>
<attribute name="className"
description="Fully qualified class name of the managed object"
type="java.lang.String"
writeable="false"/>
<attribute name="info"
description="Information about this implementation"
type="java.lang.String"
writeable="false"/>
<attribute name="stateName"
description="The name of the LifecycleState that this component is currently in"
type="java.lang.String"
writeable="false"/>
</mbean>
</mbeans-descriptors>
これは、元のErrorReportValve と同じパッケージにある、mbeans-descriptors.xml を参考にクラス名のみ書き換えています。
ここまで作成したら、jarにパッケージングして作成したjarを $CATALINA_HOME/lib に入れておきます。
最後に、追加したErrorReportValveを使うように、server.xml を編集します。Host要素にerrorReportValveClass属性を追加します。
<?xml version="1.0" encoding="UTF-8"?>
<Server>
<Service>
<Engine>
<!--中略-->
<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true"
errorReportValveClass="info.hilife_jp.tech.catalina.valves.MyErrorReportValve">
<!--中略-->
</Host>
</Engine>
</Service>
</Server>
これでTomcatを起動して、適当にエラーを起こせば(存在しないリソースを指定して404エラーを出すのが簡単でしょう)、指定したページにリダイレクトされるはずです。
また、MBeanが設定されているかどうかは、VisualVMなどを使えばわかります。
最近のコメント