Servlet创建很简单,主要有两种方法:一是创建一个普通的Java类使其继承HttpServlet类,在手动配置web.xml文件注册Servlet对象。另一种是直接通过IDE继承开发工具进行创建。
(1)声明Servlet对象
在web.xml中,通过<servlet>标签声明一个Servlet对象。再此标签下主要包含两个子元素,分别为:<servlet-name>和<servlet-class>。其中<servlet-name>元素用于指定Servlet的名称,该名称可以是自定义的名称;<servlet-class>元素用于指定Servlet对象的完整位置。包括Servlet对象的包名和类名。其生命语法格式:
<servlet>
<servlet-name>SimpleServlet</servlet-name>
<servlet-class>com.zgy.servlet</servlet-class>
</servlet>
(2)映射Servlet
在web.xml文件中声明了Servlet对象后,需要映射访问Servlet的URL。该操作使用<servlet-mapping>标签进行配置。<servlet-mappig>标签包含两个子元素,分别为<servlet-name>和<url-pattern>。其中,<servlet-name>元素与<servlet>标签中的<servlet-name>元素相对应,不可以随便更改命名。<url-pattern>元素用于映射访问URL。其配置方法:
<servlet-mapping>
<servlet-name>SimpleServlet</servlet-name>
<url-pattern>/SimpleServlet</url-pattern>
</servlet-mapping>
范例:
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. <br>
*
* 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("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>Servlet 实例</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" Servlet实例 ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
}
web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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">
<display-name></display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.zgy.servlet.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/servlet/MyServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
原文地址:http://blog.csdn.net/yaguanzhou2014/article/details/41527427