【问题标题】:How to get request parameters in a Scalatra Servlet?如何在 Scalatra Servlet 中获取请求参数?
【发布时间】:2015-07-14 17:38:19
【问题描述】:

我目前有一个工作的 Scalactra servlet。

class MyScalatraServlet extends MyScalatraWebAppStack {
   get("/") {
      response.getWriter().println("Test")
      val scDate = com.example.app.ScalaDate.printDate()
      response.getWriter().println(scDate)
      val cmd = "spark-submit --jars /home/cloudera/Desktop/SparkDisc/lib/DME.jar/..../discovery_2.10-1.0.jar hdfs:/user/cloudera/sample0.txt"//hard coded file path
      val output = cmd.!! // Captures the output
      response.getWriter().println(output)
   }
}

文件路径当前是硬编码的。我可以做些什么来允许用户输入文件路径参数吗?非常感谢您的帮助!

【问题讨论】:

    标签: servlets scalatra


    【解决方案1】:

    使用GETPOST,可以输入参数,如下:

    import org.scalatra._
    import scalate.ScalateSupport
    import com.google.gson.Gson
    import java.util.concurrent.TimeUnit
    import java.util.Date
    
    class Queue(var id: String, var act: String, var waitSec: Int) {
      override def toString = id + ", " + act + ", " + waitSec.toString
    }
    
    class MyScalatraServlet extends ScalatraServlet with ScalateSupport {
    
      get("/hello/:query") {
        <html>
          <body>
            <pre>
              {params("query")}
            </pre>
          </body>
        </html>
      }
    
      post("/hello") {
    
        println("A request comes: " + "%tF %<tT" format new Date)
    
        val jsonString = request.body
        try {
          val gson = new Gson
          val queue = gson.fromJson(jsonString, classOf[Queue])
          // for debugging
          println("Your name: " + queue)
    
          if (queue.act.equals("stop")) {
            println("Wait for: " + queue.waitSec.toString)
            TimeUnit.SECONDS.sleep(queue.waitSec)
          }
    
          response.addHeader("ACK", "GOT IT")
        } catch {
          case e: Exception =>
            e.printStackTrace
            response.addHeader("ACK", "BOOM!")
        }
      }
    
      notFound {
        // Try to render a ScalateTemplate if no route matched
        findTemplate(requestPath) map { path =>
          contentType = "text/html"
          layoutTemplate(path)
        } orElse serveStaticResource() getOrElse resourceNotFound()
      }
    }
    
    1. 获取

    你应该参考Scalatra 2.4 guide ... Routes 您可以通过访问http://localhost:8080/hello/query查看输入的查询
    但是,我认为通过查询输入文件路径并不好。

    1. 发布

    上面的例子,你可以让它停止处理servlet。 遵循 JSON 对处理此代码很有用。

    {"id":"001","act":"stop","waitSec":100}
    

    像这样执行卷曲:

    $ curl -i -X POST -d "{\"id\":\"001\",\"act\":\"stop\",\"waitSec\":100}" http://localhost:8080/hello -H "Content-Type: application/json"
    

    例如,您可以将 JSON 键值替换为文件路径。

    【讨论】:

      猜你喜欢
      • 2011-11-02
      • 2021-08-11
      • 1970-01-01
      • 2015-08-17
      • 2013-01-05
      • 2011-05-01
      • 2017-10-21
      • 2021-01-12
      • 1970-01-01
      相关资源
      最近更新 更多