一、什么是Servlet
Servlet是SUN公司提供的一门用于开发动态web资源的技术。它是Java Web三大组件 之一,它工作在客户端请求与服务器响应的中间层。
二、Servlet生命周期
代表生命周期的三个方法:init()、service()、destroy()。
- init():当Servlet第一次被装载时,Servlet引擎调用init()方法,只调用一次。
- service():这是Servlet真正处理请求的地方。对于每个请求,Servlet引擎将调用Servlet的service方法,并把Servlet请求和响应对象做为参数传递给它。
- destroy():当Servlet即将被卸载时由Servlet引擎来调用,这个方法用来清除并释放在init方法中所分配的资源,只调用一次。
三、Servlet工作过程
- 客户端对web服务器发出访问请求。
- web服务器接收到请求后将其发送给Servlet。
- Servlet容器为此产生一个实例对象并调用ServletAPI中相应的方法来对客户端HTTP请求进行处理,然后将处理的响应结果返回给WEB服务器。
- web服务器把从Servlet实例对象中收到的响应结果发送回客户端。
四、Servlet项目实战
新建项目:
- Dnamic Web Project:If you want to create a content-based Web application that does not contain any dynamic content (such as servlets, JSP files, filters, and associated metadata) you might prefer to create a static Web project, as opposed to a dynamic Web project.
- Static Web Project:Create a Web project for static content (HTML files) only.
项目取名为:HelloServlet
如果Target runtime为空,请参考:安装和配置Tomcat详解 进行配置。
新建Servlet
方法一:
方法二:
包名和类名:
点Finish生成Hello类:
新建XML文件:
编辑Web.xml文件代码:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_2_5.xsd">
<servlet>
<!-- 类名 -->
<servlet-name>Hello</servlet-name>
<!-- 所在的包 -->
<servlet-class>com.lj.hello.Hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<!-- 访问的网址 -->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
com.lj.hello.Hello,不能写错了:包名+类名。
doGet里面加代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("HelloWorld!!!");
}
运行项目:
没Server时:
有Server时:
如果报错:
如报:“HttpServlet cannot be resolved to a type”这种报错。
请参考:关于HttpServlet cannot be resolved to a type的解决方法
成功运行后: