Servlet 教程 之 Servlet 表单数据 4
Servlet 表单数据
使用 URL 的 GET 方法实例
下面是一个简单的 URL,将使用 GET 方法向 HelloForm 程序传递两个值。
http://localhost:8080/TomcatTest/HelloForm?name=百度&url=www.baidu.com
下面是处理 Web 浏览器输入的 HelloForm.java Servlet 程序。我们将使用 getParameter() 方法,可以很容易地访问传递的信息:
package com.baidu.test;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
Servlet implementation class HelloForm
*/
@WebServlet("/HelloForm")
public class HelloForm extends HttpServlet {
private static final long serialVersionUID = 1L;/**
@see HttpServlet#HttpServlet()
*/
public HelloForm() {
super();
// TODO Auto-generated constructor stub
}/**
@see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected 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("ISO-8859-1"),"UTF-8");
String docType = "<!DOCTYPE html> \n";
out.println(docType +"<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>站点名</b>:" + name + "\n" + " <li><b>网址</b>:" + request.getParameter("url") + "\n" + "</ul>\n" + "</body></html>");
}
// 处理 POST 方法请求的方法
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}然后我们在 web.xml 文件中创建以下条目:
<?xml version="1.0" encoding="UTF-8"?>
HelloForm
com.baidu.test.HelloForm
HelloForm
/TomcatTest/HelloForm
现在在浏览器的地址栏中输入 http://localhost:8080/TomcatTest/HelloForm?name=百度&url=www.baidu.com ,并在触发上述命令之前确保已经启动 Tomcat 服务器。