1.传递数据需要用到GET和POST方法
GET 方法向页面请求发送已编码的用户信息。页面和已编码的信息中间用 ? 字符分隔。
POST 方法不是把信息作为 URL 中 ? 字符后的文本字符串进行发送,而是把这些信息作为一个单独的消息。
2.使用Servlet读取表单数据
- getParameter():您可以调用 request.getParameter() 方法来获取表单参数的值。
- getParameterValues():如果参数出现一次以上,则调用该方法,并返回多个值,例如复选框。
- getParameterNames():如果您想要得到当前请求中的所有参数的完整列表,则调用该方法。
servlet代码:
package com.servlet.demo; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloForm extends HttpServlet { /** * Destruction of the servlet. <br> */ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 设置响应内容类型 response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "使用 GET 方法读取表单数据"; // 处理中文 String name =new String(request.getParameter("name").getBytes("ISO8859-1"),"UTF-8"); String docType = "<!DOCTYPE html> "; out.println(docType + "<html> " + "<head><title>" + title + "</title></head> " + "<body bgcolor="#f0f0f0"> " + "<h1 align="center">" + title + "</h1> " + "<ul> " + " <li><b>站点名</b>:" + name + " " + " <li><b>网址</b>:" + request.getParameter("url") + " " + "</ul> " + "</body></html>"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } public void init() throws ServletException { // Put your code here } }
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 'index.jsp' starting page</title> </head> <body> <form action="HelloForm" method="POST">
<!--<form action="HelloForm" method="GET">--> 网址名:<input type="text" name="name"> <br /> 网址:<input type="text" name="url" /> <input type="submit" value="提交" /> </form> </body> </html>