首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >脚本和Java Servlets

脚本和Java Servlets
EN

Stack Overflow用户
提问于 2014-07-22 00:36:29
回答 2查看 69关注 0票数 0

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

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

所以,在解释完所有这些之后,这就是我想知道的。有没有脚本语言可以让我从java servlet传入和返回原生java对象?

EN

回答 2

Stack Overflow用户

发布于 2014-07-22 00:39:17

Servlet是HTTP侦听器。它们要求您传递HTTP请求和响应。它们既不知道也不关心Java对象。您必须将Java对象编组为String,并对它们进行适当编码。

票数 0
EN

Stack Overflow用户

发布于 2014-07-23 05:27:49

我终于想通了。显然,我想要的一切都内置到了java中。Java具有将java对象传递到javascript调用中的能力,并且这些对象可以像本地java对象一样被使用。我能够在javascript调用中设置一个全局java.sql.Connection,并像在java中一样读取数据库。此外,我还能够修改传入的对象,并将它们返回给调用java的代码。以下是运行正常的代码。

Java源文件。

代码语言:javascript
复制
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)

代码语言:javascript
复制
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

另外,我的公司还在使用java6,所以我不能使用nashorn引擎。每当我在代码中请求引擎时,我使用"javascript“代替,对于我需要做的有限的事情,它工作得很好。在java servlet中,这一切都能完美地工作。

希望这能帮助其他正在寻找类似东西的人。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24870179

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档