刚才看了几篇对Servlet总结的文章,发现他们都有异曲同工之处,上来就是这样写的:
Servlet三个要素:
1.必须继承自HttpServlet
2.必须实现doGet()或者doPost()
3.必须在web.xml中配置Servlet
<servlet>
<servlet-name> </servlet-name>
<servlet-class> </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> </servlet-name>
<url-pattern> </url-pattern>
</servelt-mapping>
有谁说了编写一个Servlet必须继承自HttpServlet类,必须实现doGet()或者doPost() ,难道实现Servlet接口就不行了吗?
其实编写一个Servlet主要有三种方法,一是实现Servlet接口,二是继承抽象类GenericServlet,三是继承HttpServlet类。下面分别用这三种方法去实现Servlet:
(一)要从实现Servlet接口来编写一个Servlet是比较麻烦的,因为必须实现Servlet接口中的所有方法,Servlet接口主要定义了五个方法,它们分别为:
(1)void init(ServletConfig config) throws ServletException
(2)ServletConfig getServletConfig()
(3)void service(ServletRequest req,ervletResponse res) throws ServletException,IOException
(4)String getServletInfo()
(5)void destroy()
下面用实现Servlet接口的方法编写一个Servlet:
import
javax.servlet.
*
;
import
java.io.
*
;
public
class
TestServlet
implements
Servlet
{
public
void
init(ServletConfig config)
throws
ServletException
{
System.out.println(
"
init
"
);
}
public
ServletConfig getServletConfig()
{
reture
null
;
}
public
void
service(ServletRequest req,ServletResponse res)
throws
ServletException,IOException
{
//
这里可以实现请求后要做的内容
PrintWriter out
=
response.getWriter();
out.println(
"
Hello World!
"
);
}
public
String getServletInfo()
{
return
null
;
}
public
void
destroy()
{
System.out.println(
"
destory
"
);
}
}