在Python中向服务器提交一个表单数据看起来是很容易的,但是这次经历着实让我记忆深刻,借此也为了警醒同样遇到了这样问题的你们。


要做什么?

使用Python的urllib2模块提交表单数据,并在服务器端进行验证提交的表单结果。

  • 操作系统

    Windows 7 旗舰版

  • 需要的编译器:

    • Eclipse
    • PyCharm
  • 需要的技术:
    • (基础的)Java web技术
    • (基础的)Python

服务器端代码

服务器端采用JavaWeb技术创建,使用Servlet来接收表单数据。具体内容如下:

首先是index.html:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="GetParameters" method="POST">
    <br>
    UserName : <input type="text" name= "username"><br>
    Password : <input type="password" name = "password"><br>
    <br>
    <input type= "submit" value="Submit">
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
    <input type="reset">

</form>

</body>
</html>

然后是action对应的servlet界面。GetParameters.java

package one;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetParameters extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetParameters() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
        doPost(request, response);

    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        // doGet(request, response);
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        System.out.println("Username is : " + username);
        System.out.println("Password is : " + password);

        response.getOutputStream().write("I have received you request!".getBytes());
    }

}

最后就是web.xml的配置文件(我这里偷了个懒,老是记错配置,所以就在tomcat的一个sample 下面抄了一个,然后改了改,就成了)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>Test</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>GetParameters</servlet-name>
        <servlet-class>one.GetParameters</servlet-class>
    </servlet>
    <!-- ... -->
    <servlet-mapping>
        <servlet-name>GetParameters</servlet-name>
        <url-pattern>/GetParameters</url-pattern>
    </servlet-mapping>

</web-app>

Python端代码

额,我姑且称之谓测试端吧。代码很简单,如下:

# coding:UTF-8
import sys,urllib,urllib2

def CommonWay():
    url = 'http://localhost:8080/Test/GetParameters'
    params = {
        'username':'Username',
        'password':'Password'
    }
    data = urllib.urlencode(params)
    req = urllib2.Request(url,data)
    response = urllib2.urlopen(req)
    content = response.read()
    print content

CommonWay()
print "Succeed!"

运行结果

Python控制台的输出结果是这样的

D:\Software\Python2\python.exe E:/Code/Python/GetWeather/ulib2/SubmitData.py
I have received you request!
Succeed!

Process finished with exit code 0

但其实最重要的就是服务器端的处理结果了。

我们可以在Eclipse的控制台清楚的看到我们提交的表单数据。至于要对这些数据做什么样的操作,就不是今天要讲的内容了。

总结

  • 今天的收获很多,作为一个学习Python的新手,我坚信现阶段遇到的问题越多,进步的也就会越快。
  • 对一个知识点要学的深入一点,而不只是停留在表面
  • 少犯一些低级错误,比如我今天这个URL竟然都给弄错了。⊙﹏⊙b汗
  • 多多的写代码,多多的测试,才能比较扎实的掌握。而不要图快,这样基础根本打不牢固。

Python与JavaWeb的第一次碰撞的更多相关文章

  1. Python第三周第一次作业中关于工程目录各种导入的模拟学习

    目录 Python工程目录 导入自定义模块, 包 记录的缘由 模块搜索路径 模块: 导入模块 导入函数 导入类 多个类 @(Python第三周第一次作业中工程目录,模拟学习) Python工程目录 导 ...

  2. python网络爬虫。第一次测试-有道翻译

    2018-03-0720:53:56 成功的效果如下 代码备份 # -*- coding: UTF-8 -*- from urllib import request from urllib impor ...

  3. 自学Python全栈开发第一次笔记

           我已经跟着视频自学好几天Python全栈开发了,今天决定听老师的,开始写blog,听说大神都回来写blog来记录自己的成长. 我特别认真的跟着这个视频来学习,(他们开课前的保证书,我也写 ...

  4. Python学习笔记:第一次接触

    用的是windows的IDLE(python 3) 对象的认识:先创建一个list对象(用方括号) a = ['xieziyang','chenmanru'] a 对list中对象的引用 a[0] # ...

  5. Python 【第六章】:Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

    Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度 ...

  6. Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

    Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度 ...

  7. Python操作memcached及redis

    Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度 ...

  8. Python之路【第九篇】:Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

    Python之路[第九篇]:Python操作 RabbitMQ.Redis.Memcache.SQLAlchemy   Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用 ...

  9. mac 配置Python集成开发环境(Eclipse +Python+Pydev)

    1.下载Mac版64位的Eclipse. 进入到Eclipse官方网站的下载页面(http://www.eclipse.org/downloads/),我选择了下图所示的软件包, 浏览器在下载过程中使 ...

随机推荐

  1. HDU 6107 Typesetting

    Problem Description Yellowstar is writing an article that contains N words and 1 picture, and the i- ...

  2. hdu3487 splay树

    Play with Chain Time Limit: 6000/2000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) ...

  3. SPOJ DQUERY树状数组离线or主席树

    D-query Time Limit: 227MS   Memory Limit: 1572864KB   64bit IO Format: %lld & %llu Submit Status ...

  4. RHEL 7修改ssh默认端口号

    RHEL7修改默认端口号(默认port22)初次安装系统完毕后默认情况下系统已经启动了sshd服务当然我们也可以先进行检查: 步骤1,检查是否已安装ssh服务 步骤2,检查服务是否已开启 如上图所示显 ...

  5. 使用VMware Converter Standalone Client进行虚拟机 P2V提示 权限不足,无法连接\\ip\admin$的解决方法集锦

    使用VMware vCenter Converter Standalone Client进行虚拟机 P2V提示 权限不足,无法连接\\ip\admin$的解决方法集锦 步骤一 检查 远程桌面到&quo ...

  6. BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext

    这个坑爹的玩意 有几个出现错误的原因 服务器 1.服务器重复启动同一个部署 这个时候要停止然后启动 电脑差的 重启电脑 重启服务器就好了 代码 2.bean工厂不知道哪里关闭 3.bean工厂没有找到 ...

  7. 吴恩达深度学习第2课第3周编程作业 的坑(Tensorflow+Tutorial)

    可能因为Andrew Ng用的是python3,而我是python2.7的缘故,我发现了坑.如下: 在辅助文件tf_utils.py中的random_mini_batches(X, Y, mini_b ...

  8. Linux下使用MD5加密BASE64加密

    这里以字符串123456为例子,它的md5密文值为:e10adc3949ba59abbe56e057f20f883e 这里以1.txt为需要被加密的文件. 一. 用oppnssl md5 加密字符串和 ...

  9. ACM Piggy Bank

    Problem Description Before ACM can do anything, a budget must be prepared and the necessary financia ...

  10. MYSQL 索引类型、什么情况下用不上索引、什么情况下不推荐使用索引

    mysql explain的使用: http://blog.csdn.net/kaka1121/article/details/53394426 索引类型 在数据库表中,对字段建立索引可以大大提高查询 ...