在开始前,先把Tomcat的/lib/servlet-api.jar加入到项目依赖库中。
Servlet类继承HttpServlet类,提供以下方法相应客户端请求:
- doGet() 响应客户端的get请求
- doPost() 响应客户端的post请求
- doPut 和 doDelete,不常用,不去了解
另外,HttpServlet还有两个方法:
- init() 创建Servlet实例时调用该方法
- destroy() 销毁Servlet实例时调用该方法
练习######
配合JSP编写一个小页面,收集表单数据后打印在浏览器上。
form.jsp代码如下
<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
收集参数的表单页
FIrstServlet.java代码如下
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintStream;
/**
* Created by FanXiao on 2017/5/11.
*/
@WebServlet(name="firstServlet",urlPatterns={"/firstServlet"})
public class FirstServlet extends HttpServlet{
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
//设置解码方式
request.setCharacterEncoding("GBK");
response.setContentType("text/html;charSet=GBK");
//获取name、gender、color和country等请求参数值
String name = request.getParameter("name");
String gender = request.getParameter("gender");
String[] color = request.getParameterValues("color");
String country = request.getParameter("country");
//获取out
PrintStream out = new PrintStream((response.getOutputStream()));
//输出html页面
out.println("");
out.println("");
out.println("Servlet测试");
out.println("");
out.println("name:" + name + "
");
out.println("gender:" + gender + "
");
out.println("colors");
for (String c : color){
out.println(c + " ");
}
out.println("
");
out.println("country:" + country + "
");
out.println("");
out.println("