Servlet 3.1 处理 POST 表单

Java Servlet 处理 POST 表单数据

使用表单的 POST 方法范例

下面的范例中的 servlet 可以处理 GET 和 POST 提交的数据

// author: 简单教程(www.twle.cn)
// Copyright © 2015-2065 www.twle.cn. All rights reserved.

package cn.twle.demo;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*; 
import javax.servlet.annotation.WebServlet;
import java.util.Enumeration;

@WebServlet(name = "FormPostServlet", urlPatterns = {"form/post"})
public class FormPostServlet extends HttpServlet 
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();
        String title = "使用 POST 方法读取表单数据 | 简单教程(www.twle.cn)";

        String docType = "<!DOCTYPE html>";
        out.println(docType +
            "<title>" + title + "</title>" +
            "<p>" + title + "</p>\n" +
            "<ul>\n" +
            "  <li><b>站点名</b>:"
            + request.getParameter("name") + "\n" +
            "  <li><b>网址</b>:"
            + request.getParameter("url") + "\n" +
            "</ul>");
    }

    // 处理 POST 方法请求的方法
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

form_post.jsp

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8" %> 
<!DOCTYPE html>
<meta charset="utf-8">
<title>Servlet POST 表单范例 | 简单教程(www.twle.cn)</title>
<p>Servlet POST 表单范例 | 简单教程(www.twle.cn)</p>
<form action="/servlet/form/post" method="POST">
网址名<input type="text" name="name">
<br />
 &nbsp; <input type="text" name="url" />
<input type="submit" value="提交" />

</form>

在浏览器上输入 http://localhost:8080/servlet/form-post.jsp 显示结果如下

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.