1.服务器代码
package rouby;
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表单数据 使用get方法读取表单数据
* @author 周昆
*
*/
/*@WebServlet("/HelloForm435")*/
public class HelloForm extends HttpServlet{
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doGet(req, resp);
//设置响应内容类型
res.setContentType("text/html;charset=utf-8");
//req.getParameter()获取表单参数的值
PrintWriter pw=res.getWriter();
String title="使用get方式读取数据";
String docType = "<!DOCTYPE html> \n";
String name=new String(req.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
pw.println(docType+"<html> "
+"<head> "
+"<title>"+title+"</title> "
+"</head> "
+"<body bgcolor='#f0f0f0'> "
+"<h1>"+title+"</h1> "
+"<ul> "
+"<li><b>站点名</b>: "
+name+"</li> "
+"<li><b>网址</b>:"
+req.getParameter("url")+"</li></ul> "
+"</body></html>");
}
//处理post方法请求方法
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// TODO Auto-generated method stub
//super.doPost(req, resp);
doGet(req, res);
}
}
2.配置web.xml
<?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>servlet2</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>HelloForm</servlet-name>
<servlet-class>rouby.HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
</web-app>
3.访问地址http://localhost:8080/servlet2/HelloForm?name=%E7%99%BE%E5%BA%A6&url=www.baidu.com