我用doPost方法创建了一个简单的jython servlet文件。我试图发布一个表单但是在servlet中我没有得到帖子值。以下是我尝试使用的代码。
Test.html
---------
<form action='Index.py' method='post'>
<input type="text" name="username" value="ifti" />
<input type="text" name="password" value="ifti1233" />
<input type="submit" name="Submit" value="Submit" />
</form>
Index.py
--------
from javax.servlet.http import HttpServlet
import cgi, cgitb, os, sys, shutil
import urllib2
import org.python.util.PyFilter
cgitb.enable();
class Index(HttpServlet):
def doPost(self,req,res):
res.setContentType("text/html")
form = cgi.FieldStorage()
out = res.getWriter()
keys = form.keys()
keys.sort()
pageContent = "<br />number of keys: "+str(len(keys))
for key in keys:
pageContent += fieldStorage[ key ].value
out.println(pageContent)
答案 0 :(得分:1)
cgi.FieldStorage
期望来自流程的标准输入或其环境的输入。这就是Web服务器和CGI请求处理程序协作以提供HTTP请求的方式。
Servlet使用不同的协议将原始HTTP请求从Web服务器传输到请求处理程序,并且不能从标准输入/环境中读取HTTP请求。这就是为什么cgi.FieldStorage()
没有检测到任何帖子字段的原因。相反,已处理的请求在传递给HttpServletRequest
的{{1}}对象中提供。您可以调用doPost()
上的方法来获取帖子字段和标题,例如
HttpServletRequest
使用您的测试表单,您应该看到与此类似的输出:
import cgi
from pprint import pformat
from javax.servlet.http import HttpServlet
class Index(HttpServlet):
def doPost(self,req,res):
res.setContentType("text/html")
out = res.getWriter()
out.println('<strong>Headers</strong>')
headers = {}
for n in req.headerNames:
headers[n] = req.getHeader(n)
out.println('<pre>')
out.println(pformat(headers))
out.println('</pre><br />')
out.println('<strong>Form fields</strong>')
# get the POST data fields
form = {}
for field in req.parameterMap:
form[field] = list(req.parameterMap[field])
# # Alternative - if you *really* want a FieldStorage object, construct
# # one from the request body, headers and faked environment variables.
# # N.B. assumes that the request body is one line of POST data only.
# from StringIO import StringIO
# request_body = req.reader.readLine()
# form = cgi.FieldStorage(fp=StringIO(request_body),
# headers=headers,
# environ={'REQUEST_METHOD': 'POST',
# 'CONTENT_LENGTH': len(request_body)})
out.println('<pre>%s</pre><br />' % pformat(form))