Servlet創建很簡單,主要有兩種方法:一是創建一個普通的Java類使其繼承HttpServlet類,在手動配置web.xml文件注冊Servlet對象。另一種是直接通過IDE繼承開發工具進行創建。
(1)聲明Servlet對象
在web.xml中,通過
(2)映射Servlet
在web.xml文件中聲明了Servlet對象後,需要映射訪問Servlet的URL。該操作使用
范例:
package com.zgy.servlet;
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 MyServlet extends HttpServlet {
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("GBK");
PrintWriter out = response.getWriter();
out.println("");
out.println("");
out.println("
out.println("
");out.print(" Servlet實例 ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" ");
out.println("");
out.flush();
out.close();
}
}
web.xml配置
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">