在Javaweb中使用Scala

 

     Java 是一门比较优秀的编程语言, 其最大功劳是建立非常繁荣的JVM平台生态。不过 Java 语法比较麻烦,写过 C, Python 的人总是想使用简洁的语法,又希望利用上 Java 平台的强大,因此,催生了 Groovy , Scala 这样的 JVM 语言。那么为什么选择 Scala 呢? 因为 Scala 是一门富有想象力的语言!

  本文尝试在 Javaweb 中使用 Scala , 使用 Scala 编写一个 Servlet ,项目见  http://www.cnblogs.com/lovesqcc/p/4037708.html 。值得注意的是, Intellj 提供了将 Java 转化为 Scala 的功能! 不信,你可以将 Java 代码直接复制到 Scala 文件中。

  在 Javaweb 项目中使用 Scala , 需要添加如下依赖和插件:  

<dependency>
            <groupId>org.scala-lang</groupId>
            <artifactId>scala-library</artifactId>
            <version>2.10.1</version>
        </dependency>
<plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.8.1</version>
                <configuration>
                    <includes>
                        <include>**/*.java</include>
                        <include>**/*.scala</include>
                    </includes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.scala-tools</groupId>
                <artifactId>maven-scala-plugin</artifactId>
                <version>2.15.2</version>
                <executions>
                    <execution>
                        <id>scala-compile-first</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>scala-test-compile</id>
                        <phase>process-test-resources</phase>
                        <goals>
                            <goal>testCompile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

 

     Scala Servlet: 

package servlets

import java.io.IOException
import javax.servlet.ServletException
import javax.servlet.http.{HttpServletResponse, HttpServletRequest, HttpServlet}

import autocomplete.{SimpleWordMatcher, PrefixMatcher}
import scala.collection.JavaConversions._

/**
 * Created by lovesqcc on 16-3-19.
 */
class AutoCompleteServletUsingScala extends HttpServlet {

  protected var wordMatcher: PrefixMatcher = new SimpleWordMatcher

  @throws(classOf[ServletException])
  @throws(classOf[IOException])
  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) {
    doPost(req, resp)
  }

  @throws(classOf[ServletException])
  @throws(classOf[IOException])
  override def doPost(req: HttpServletRequest, resp: HttpServletResponse) {
    resp.setContentType("text/plain;charset=UTF8")
    val inputText: String = req.getParameter("inputText")
    val matchers = wordMatcher.obtainMatchedWords(inputText)

    var content = ""
    matchers.foreach {
        word => content += word + " "
    }

    resp.getWriter print content

  }

}

 

posted @ 2016-03-19 08:33  琴水玉  阅读(4190)  评论(0编辑  收藏  举报