在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 } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2015-03-19 编写更少bug的程序的六条准则