本文章主要演示如何通过struts2中的动作类将表单的数据传递给python脚本文件,再通过脚本插入mysql数据库中。
主要文件包括:py_form.jsp(输入表单数据)、py_success.jsp(操作成功提示)、struts.xml(struts2核心控制器配置)、web.xml(过滤器配置)、pyAction.class(动作类,用于响应表单提交)、form.py(表单数据处理)、struts2及操作python脚本所需的jar包,接下来贴出详细代码及相关文件:
struts.xml(struts2核心控制器配置)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "struts-2.1.7.dtd" > <struts> <package name="hello" extends="struts-default"> <!-- pyAction --> <action name="python" class="cn.itcast.action.pyAction"> <result name="success">/py_success.jsp</result> <result name="error">/py_error.jsp</result> </action> </package> </struts>
web.xml(过滤器配置)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>chapter</display-name> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
pyAction.class(动作类,用于响应表单提交)
package cn.itcast.action; import java.io.BufferedReader; import java.io.InputStreamReader; import com.opensymphony.xwork2.ActionSupport; public class pyAction extends ActionSupport { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String execute() throws Exception { String username = name; System.out.println("start..."); System.out.println("调用py脚本连接mySQL数据库..."); String[] args1 = new String[]{"python", "D:\form.py", username}; Process pr = Runtime.getRuntime().exec(args1); BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream())); //打印脚本中的print()的内容 String line; while((line = in.readLine()) != null){ System.out.println(line); } in.close(); /*waitFor():导致当前线程等待,如有必要,一直要等到由该 Process 对象表示的进程已经终止。 如果已终止该子进程,此方法立即返回。如果没有终止该子进程,调用的线程将被阻塞,直到退出子进程, 根据惯例,0 表示正常终止*/ pr.waitFor(); System.out.println("操作结束!"); return SUCCESS; } }
form.py(表单数据处理)
from sqlalchemy import create_engine import pandas as pd import sys # sys.argv[]:一个从程序外部获取参数的桥梁,从外部取得的参数可以是多个,所以获得的是一个列表(list),。其第一个元素是程序本身,随后才依次是外部给予的参数。 test = sys.argv[1] engine = create_engine(r'mysql+pymysql://root:root@localhost:3306/test?charset=utf8') print("连接成功,正在插入数据到数据表test2...") data = pd.DataFrame({'name': [test]}) data.to_sql('test2', con=engine, if_exists = 'append') print("插入数据成功...")
struts2及操作python脚本所需的jar包(由于当前信号较差,几次上传附件失败,故仅截图)
py_form.jsp(输入表单数据)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'py_form.jsp' starting page</title>
</head>
<body>
<form action='python' method='post'>
<input type='text' name='name' />
<input type='submit' value='提交' />
</form>
</body>
</html>
py_success.jsp(操作成功提示)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'py_success.jsp' starting page</title>
</head>
<body>
${name } 登录成功
</body>
</html>
运行成功后在myeclipse控制台输出如下