JSPのコンパイルバージョンを設定する方法を記述します。
背景
スクリプトレットでswitch文を使っているJSPにアクセスしたら、エラーが発生しました。
<%
String name = request.getAttribute("name");
switch(name) {
case "A":
//処理
default:
//処理
}
%>
エラーメッセージ
Cannot switch on a value of type String for source level below 1.7. Only convertible int values or enum variables are permitted
Sring型の値をswitch文で使うには、Java1.7以上でないといけないので、JSPのコンパイルバージョンを上げる必要があります。
環境
- Tomcat7
- Java7
設定方法
まずTomcat7の現在のJSPコンパイルバージョンを見てみましょう。
http://tomcat.apache.org/tomcat-7.0-doc/jasper-howto.html#Configuration
- compilerSourceVM - What JDK version are the source files compatible with? (Default value: 1.6)
- compilerTargetVM - What JDK version are the generated files compatible with? (Default value: 1.6)
デフォルトは「1.6」と書かれています。
設定ファイルにcompilerSourceVM
とcompilerTargetVM
情報を追加する必要があります。
<servlet>
<servlet-name>jsp</servlet-name>
<servlet-class>org.apache.jasper.servlet.JspServlet</servlet-class>
<init-param>
<param-name>fork</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>xpoweredBy</param-name>
<param-value>false</param-value>
</init-param>
<!-- ここから -->
<init-param>
<param-name>compilerSourceVM</param-name>
<param-value>1.7</param-value>
</init-param>
<init-param>
<param-name>compilerTargetVM</param-name>
<param-value>1.7</param-value>
</init-param>
<!-- ここまでを追加 -->
<load-on-startup>3</load-on-startup>
</servlet>
以上です。
参考サイト
http://qiita.com/hibinohirokatsu/items/80563665baeae5ba01fe
http://docs.escenic.com/ece-tech-notes/5.7/jsp_servlet_configuration.html
http://stackoverflow.com/questions/17545720/unable-to-switch-on-string-type-in-jdk-7
疑問点
- compilerSourceVMとcompilerTargetVMの違い。コンパイル時か実行時かの違い?