从Java Servlets应用程序执行Python脚本

问题描述 投票:0回答:1

Context

我目前正在使用Java Servlet和Python编写客户端/服务器Web应用程序。

我正面临客户端交互的问题,主要是在生成输入方面。

生成输入需要通过在客户端本地执行python脚本来修改输入用户的数据,然后通过POST请求将其提交给Servlet服务器。

[接收到此数据后,Servlet将把它传递给另一个python服务器端脚本进行检查。

由于计算量大(2 ^ 4096)位长,因此在此过程中Python是必需的。

问题

提交表单时:

我如何从表单字段中提取数据,将其内容作为输入参数传递到本地python脚本中,执行python脚本。然后将新的计算数据从python脚本返回到Web浏览器,以向服务器发出POST请求?

javascript java python rest servlet-3.0
1个回答
1
投票

您在这里有两种可能:

[1)Java作为控制器

从Java Servlet中获取表单数据:

String Form_text_data = request.getParameter("text_input");

如果有很多字段,您可以实例化一个StringBuilder(需要所有请求的文件),以获取所有目标字段答案的一个字符串-确保在将这些字段添加到String Builder之前对这些字段进行完整性检查。

然后将您的String结果从字符串生成器传递给具有exec方法的Runtime类:

StringBuilder Python_script_command = new StringBuilder("python PATH/TO/YOUR/PYTHON_SCRIPT.py");

Python_script_command.append(Form_text_data) // Repeat this as many time as you wish for each form fields, but be sure to make sanity check before to avoid any injections that you do not want

Process p = Runtime.getRuntime().exec(Python_script_command.toString());

您可以通过以下方式绑定输出来读取输出:

       BufferedReader stdInput = new BufferedReader(new 
             InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new 
             InputStreamReader(p.getErrorStream()));

    // read the output from the command
    System.out.println("Here is the standard output of the command:\n");
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
    }

请参阅本文以获取更多详细信息:

http://alvinalexander.com/java/edu/pj/pj010016

2)从python API框架执行,例如FLASK

您还可以直接在python中构建REST API,并且当用户提交表单时,可以通过POST请求将其发送给python应用程序

然后提取所需数据非常简单:

from flask import Flask, request
app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    default_name = '0' 
    data = request.form.get('input_name', default_name) #here is an example on one data getter from a form field

请参阅此答案以获取更多详细信息(How to get form data in Flask?

然后直接在python中使用此数据,再次要进行各种健全性检查

© www.soinside.com 2019 - 2024. All rights reserved.