URLの引数によって値を取るケース
以下のURLのようにdeptno=30の値を HelloWorldDb3 クラスへ渡すコードです。
http://127.0.0.1:8080/toro/html/helloworlddb3.html?sw=4&deptno=30
parameterMap変数は、JavaのコンテナクラスのHashMap[String,Array[String]]です。
parameterMap.get(“deptno”) 関数によって、deptnoの引数の値を取り出します。
ScalaのMAPクラスではないので、case ではSome(f)ではなく、クラスマッチングで値を取り出し、
Arrayクラスなので配列の0番目の値を取り出します。
その値を toInt関数でStringから整数Intに変換します。
これをSELECT文の条件として使い、データベースに検索します。
import scala.collection.immutable._ import scala.xml._ import seedo.database._ class HelloWorldDb3 { var tag:String = null // Replaced original tag def setTag(tg:String): Unit = {tag = tg} var parameterMap:HashMap[String,Array[String]] = null // Parameter from request of servlet def setParameterMap(pm:HashMap[String,Array[String]]) : Unit = {parameterMap = pm} def recx(record:Array[Any]) :Node = { var nodes = Queue.empty[Node] record.foreach{(fx) => nodes += <TD>{fx}</TD>} return <TR>{nodes}</TR> } // Function one argument def tb(sal:Int) : String = { val deptno = parameterMap.get("deptno") match { case v:Array[String] => v(0).toInt case null => 10 } var sql:Db = null try { sql = new Db sql.select("EMPNO,ENAME,SAL,DEPTNO,JOB,MGR") .from("EMP") .where("SAL > ?",sal) .or("DEPTNO = ?",deptno) .orderBy("EMPNO") val re = sql.executeQuery var nodes = Queue.empty[Node] re.foreach{(rec) => nodes += recx(rec)} val xml = <table border="2">{nodes}</table> return "HelloWorldDb3 " + new Date + xml.toString } catch { case e:Exception =>{ throw e } } finally { if(sql != null)sql.close } } }
結果
検索して結果は以下のとおり
deptno引数がなしの場合
http://127.0.0.1:8080/toro/html/helloworlddb3.html?sw=4
HelloWorldDb3 クラスのdeptno値は、引数がない場合は10になります。
deptno引数が30の場合
http://127.0.0.1:8080/toro/html/helloworlddb3.html?sw=4&deptno=30
SELECT文の条件にEMP表のDEPTカラムの値が30のレコードもOR条件で加わるので
レコード件数の数が増えています。
deptno引数が20の場合
http://127.0.0.1:8080/toro/html/helloworlddb3.html?sw=4&deptno=20
deptnoの引数の値によりSELECTされた結果が異なっていることがわかります。
helloworlddb3.htmlファイルの中身は、
<!doctype html> <HTML> <HEAD> <title>Home</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </HEAD> <BODY> <h2>Example6</h2> The current time is <div class="seedo:ews.HelloWorldDb3:tb:2500">emp</div>. </BODY> </HTML>
class属性の値が、
class=”seedo:ews.HelloWorldDb3:tb:2500″となり、
ews.HelloWorldDb3クラスを使用しています。