tags:

views:

417

answers:

1

I created a simple Java/JSP web app and added a basic Scala servlet. Everything works and I've included the Scala file and web.xml below. How can I modify my little "trainer" servlet so I can query a MySql table and generate an HTML <table>...</table>. Btw, I will look into Lift at a later time. At the moment, my plan is to add a several new Scala servlets into an existing web app.


ScalaTrainer.scala

package com.mdm.h4

import javax.servlet.http.{HttpServlet,
HttpServletRequest => HSReq, HttpServletResponse => HSResp}

class ScalaTrainer extends HttpServlet
{
  def html =
    <html>
      <head>
        <title>Hello Scala</title>
      </head>
      <body>
        <p style="text-align: center">This is 100% pure Scala.</p>
        <p>It's now
          {currentDate}
        </p>
        <p>My name is
          {name}
          and I'm learning
          {language}.
        </p>
      </body>
    </html>

  def name = "Mike"
  def language = "Scala"

  def currentDate = java.util.Calendar.getInstance().getTime()

  override def doGet(req: HSReq, resp: HSResp) {

    resp.getWriter().print(html)

  }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

    <servlet>
        <display-name>trainer</display-name>
        <servlet-name>ScalaTrainer</servlet-name>
        <servlet-class>com.mdm.h4.ScalaTrainer</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>ScalaTrainer</servlet-name>
        <url-pattern>/trainer</url-pattern>
    </servlet-mapping>
</web-app>
A: 

Your first option should be to check if the existing application that you are enhancing already uses something to access MySQL. If it does then just leverage that. It will avoid compatibility issues.

Otherwise, if you want to do something that is very scala-like, you should have a look at scala-query at http://github.com/szeiger/scala-query.

You can also leverage any Java ORM. With Scala you can tap into existing framework and libraries.

Finally, if you just want something that doesn't require you to download many things and to sift through documentation, you can use straight JDBC (search for "JDBC MySQL" in google or on SO):

val s = conn.createStatement()
s.executeQuery("SELECT * FROM EMP")
val rs = s.getResultSet()
while (rs.next()) {
  ...
}
rs.close()
s.close()
huynhjl
Shouldn't there be a more Scala like solution to talk to the DB and generate the HTML table? select fields ("name" of characterVarying(30)) from ("my_table")
Yes, I recommended *scala-query* for this. See http://github.com/szeiger/scala-query/blob/master/src/test/scala/com/novocode/squery/test/MainTest.scala for some sample code.
huynhjl