【问题标题】:Scripting and Java Servlets脚本和 Java Servlet
【发布时间】:2014-07-23 05:27:48
【问题描述】:

我正在开发一款旨在帮助运输公司管理非紧急旅行的网络应用。服务器端是 Jboss Web,它是 Tomcat 6 的修改版本。我工作的公司最近的任务是为特定客户添加一些自定义功能。

该应用能够从第三方公司导入 CSV 文件。 CSV 包含公司可以导入到我们的软件中的行程列表,然后从那里管理行程。我们的一些客户一直要求的是一项功能,可以根据每条记录的 CSV 中的预约时间默认预定取件和预定下车时间。但是,我们所有的客户都有不同的方法来估计这些时间。我想我可以通过为每个公司添加一些简短的脚本来实现这个自定义功能。但是,我希望能够从脚本访问数据库。我真正想要的是能够将现有的连接对象从 java servlet 传递到脚本本身。如果我可以这样做,那么我就无需在 CSV 中打开/关闭每条记录的连接。我不会从脚本本身在数据库中设置任何数据。我只是在数据库中查找值以帮助计算。

所以,在解释完所有这些之后,这就是我想知道的。是否有脚本语言允许我从 java servlet 传入和返回本机 java 对象?

【问题讨论】:

    标签: java servlets scripting


    【解决方案1】:

    Servlet 是 HTTP 侦听器。它们要求您传递 HTTP 请求和响应。这些不知道也不关心 Java 对象。您必须将 Java 对象编组为字符串并正确编码。

    【讨论】:

      【解决方案2】:

      我终于明白了。显然我想要的一切都内置在java中。 Java 能够将 java 对象传递给 javascript 调用,并且这些对象可以像本地 java 对象一样使用。我能够在 javascript 调用中设置全局 java.sql.Connection 并完全像在 java 中那样读取数据库。此外,我能够修改传入的对象并将它们返回给调用 java 代码。这是有效的代码。

      Java 源文件。

      import java.io.FileNotFoundException;
      import java.sql.Connection;
      import java.sql.DriverManager;
      import java.sql.SQLException;
      import java.text.SimpleDateFormat;
      import java.util.Calendar;
      import java.util.Date;
      
      import javax.script.Invocable;
      import javax.script.ScriptEngine;
      import javax.script.ScriptEngineManager;
      import javax.script.ScriptException;
      
      public class JSTest {
      
          public static void main(String[] args) {
              new JSTest().go();
          }
      
          public void go(){
              Connection db = null;
              try {
                  //Initialize all of the built in Java script parsing classes
                  ScriptEngineManager manager = new ScriptEngineManager();
                  ScriptEngine engine = manager.getEngineByName("javascript");
                  db = login("127.0.0.1", "3306", "testdb", "user", "password");
                  //set the database connection as a global variable for the javascript object.
                  engine.put("g_connection",db);
                  engine.eval(new java.io.FileReader("/home/scripts/testScript.js"));
                  Invocable inv = (Invocable) engine;
      
                  //Put together some sample data for the script to manipulate
                  Calendar cal = Calendar.getInstance();
                  cal.setTimeInMillis(0);
                  cal.set(2014, 6, 20, 10, 30, 0);
                  Date apptTime = cal.getTime();
      
                  TripLeg tripLeg = new TripLeg();
                  tripLeg.setLegSequence("A");
                  tripLeg.setAppointmentTime(apptTime);
                  tripLeg.setProjectedMiles(5);
                  Trip trip = new Trip();
                  trip.setClientID(5);//This is the id of the client record. I need to look it up in the script.
                  tripLeg = (TripLeg) inv.invokeFunction("modifyTripLeg", trip, tripLeg);
      
                  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                  if (tripLeg.getScheduledPUTime() != null)
                      System.out.println(format.format(tripLeg.getScheduledPUTime()));
                  else
                      System.out.println("PU time not set.");
                  if (tripLeg.getScheduledDOTime() != null)
                      System.out.println(format.format(tripLeg.getScheduledDOTime()));
                  else
                      System.out.println("DO time not set.");
              } catch (ScriptException e) {
                  e.printStackTrace();
              } catch (FileNotFoundException e) {
                  e.printStackTrace();
              } catch (NoSuchMethodException e) {
                  e.printStackTrace();
              } finally {
                  try {
                      if (db != null)
                          db.close();
                  } catch (SQLException e) {
                      e.printStackTrace();
                  }
              }
          }
          public Connection login (String server, String port, String database, String userName, String password)
          {
              Connection  db = null;
              try {
                  Class.forName("com.mysql.jdbc.Driver");
                  String url = String.format("jdbc:mysql://%s:%s/%s", server, port, database);
                  db = DriverManager.getConnection(url, userName, password);      
              } catch (ClassNotFoundException e) {
                  e.printStackTrace();
                  return null;
              } catch (SQLException e) {
                  e.printStackTrace();
                  return null;
              } catch (Exception e) {
                  e.printStackTrace();
                  return null;
              }
              return db;
          }
          //Sample trip and trip leg classes stripped down to the bare minimum stuff that I need to access.
          public class Trip{
              private  int clientID;
              public int getClientID() {
                  return clientID;
              }
              public void setClientID(int clientID) {
                  this.clientID = clientID;
              }
          }
          public class TripLeg{
              private Date scheduledPUTime;
              private Date scheduleDOTime;
              private Date appointmentTime;
              private String legSequence;
              private double projectedMiles;
      
              public Date getScheduledPUTime() {
                  return scheduledPUTime;
              }
              public void setScheduledPUTime(Date scheduledPUTime) {
                  this.scheduledPUTime = scheduledPUTime;
              }
              public Date getScheduledDOTime() {
                  return scheduleDOTime;
              }
              public void setScheduledDOTime(Date scheduleDOTime) {
                  this.scheduleDOTime = scheduleDOTime;
              }
              public Date getAppointmentTime() {
                  return appointmentTime;
              }
              public void setAppointmentTime(Date appointmentTime) {
                  this.appointmentTime = appointmentTime;
              }
              public String getLegSequence() {
                  return legSequence;
              }
              public void setLegSequence(String legSequence) {
                  this.legSequence = legSequence;
              }
              public double getProjectedMiles() {
                  return projectedMiles;
              }
              public void setProjectedMiles(double projectedMiles) {
                  this.projectedMiles = projectedMiles;
              }
          }
      }
      

      这里是 javascript 源文件。 (/home/scripts/testScript.js)

      function modifyTrip(trip, tripLeg){
          return trip;
      };
      function modifyTripLeg(trip, tripLeg){
          var importFormat = getClientImportFormat(trip.getClientID());
          var legSequence = tripLeg.getLegSequence();
          var scheduledPUTime = tripLeg.getScheduledPUTime();
          var scheduledDOTime = tripLeg.getScheduledDOTime();
          var appointmentTime = tripLeg.getAppointmentTime();
          var projectedMiles = tripLeg.getProjectedMiles();
      
          if (importFormat == "TESTER_CLIENT"){
              if (legSequence == "A"){
                  if (isEmptyDate(scheduledPUTime) && !isEmptyDate(appointmentTime) && !isEmptyDouble(projectedMiles))
                      scheduledPUTime = new Date(appointmentTime.getTime() - ((projectedMiles + 45) * 60 *1000));
                  if (isEmptyDate(scheduledDOTime) && !isEmptyDate(appointmentTime))
                      scheduledDOTime = new Date(appointmentTime.getTime() - (15 * 60 *1000));
              }
      
              if (legSequence == "B"){
                  if (scheduledPUTime == null && appointmentTime != null && (projectedMiles != null && projectedMiles > 0.00))
                      scheduledPUTime = new Date(appointmentTime.getTime() - ((projectedMiles + 45) * 60 *1000));
                  if (scheduledDOTime == null && appointmentTime != null)
                      scheduledPUTime = new Date(appointmentTime.getTime() - (15 * 60 *1000));
              }
          }
          tripLeg.setScheduledPUTime(scheduledPUTime);
          tripLeg.setScheduledDOTime(scheduledDOTime);
          return tripLeg;
      };
      function getClientImportFormat(clientID){
          var sql = "select ImportFormat from Client where id = ?";
          var stmt = g_connection.prepareStatement(sql);
          stmt.setInt(1, clientID);
          var rs = stmt.executeQuery();
          var importFormat = "";
          if (rs.next()){
              importFormat = rs.getString(1);
          }
          rs.close();
          return importFormat;    
      }
      function isEmptyDate(testDate){
          if (!testDate)
              return true;
          if (testDate == null)
              return true;
          return false;
      };
      function isEmptyDouble(testDouble){
          if (!testDouble)
              return true;
          if (testDouble == null)
              return true;
          if (testDouble <= 0.0)
              return true;
          return false;
      }
      

      让我明白的两页: http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/prog_guide/api.html http://javalandscape.blogspot.com/2008/12/scripting-in-jdk6-jsr-223-part-2.html

      另外,我的公司仍在使用 java 6,所以我无法使用 nashorn 引擎。每当我在代码中请求引擎时,我都会使用“javascript”,而对于我需要做的有限的事情,它工作得很好。这一切都在 java servlet 中完美运行。

      希望这可以帮助其他寻找类似东西的人。

      【讨论】:

      • 我没有详细研究过你的代码。但我想知道你为什么要使用 JavaScript?希望您知道,尽管名称如此,JavaScript 与 Java 无关。如果您已经使用 Servlet 在 Java 中工作,那么您可以在纯 Java 中进行 CSV 文件读取、数据库访问和日期时间工作。此外,为了在 Java 中进行日期时间工作,不要使用捆绑的 java.util.Date 和 .Calendar 以及 SimpleDateFormat 类,因为它们非常麻烦。在 Java 8 中使用 Joda-Time 或新的 java.time。额外提示:Vaadin
      • 情况就是这样。我们有一个网络应用程序,可帮助非紧急交通 (NET) 提供商管理他们的日常旅行。还有另一个机构收集旅行并将其分配给全州的各种 NET 提供商。这家大型机构每天至少一次向这些 NET 提供商中的每一个提供 CSV 文件,其中包含提供商应该负责的所有行程。我们的客户(NET 提供商)想要的是能够在导入 CSV 文件时添加一些自定义功能。他们希望能够根据修改预定的接送时间
      • 预约时间。此设置时间的公式特定于每个 NET 提供商。所以我需要一种方法来编写公式。如果我可以在纯 Java 中做到这一点,那就太好了。有什么建议吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      • 1970-01-01
      • 1970-01-01
      • 2016-04-13
      相关资源
      最近更新 更多