一、编写Servlet代码,继承自HttpServlet类,并覆盖 public void doGet(HttpServletRequest req, HttpServletResponse resp) 方法
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 SimpleHello extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
PrintWriter out = resp.getWriter() ;
out.println("hello world");
out.close() ;
}
}
二、部署Servlet。在web.xml中加入如下代码:
<servlet>
<servlet-name>SimpleHello</servlet-name>
<servlet-class>cc.apl330.SimpleHello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SimpleHello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
三、测试。在浏览器中输入:http://localhost:8080/ServletTest/hello
服务器过程是这样的:
1 服务器检测请求地址:http://localhost:8080/ServletTest/hello
2 得到字符串: /hello
3 在web.xml中寻找 <servlet-mapping>下的<url-pattern>内的值是否有对应的。有,就找到<servlet-name>的值
4 在web.xml中寻找 <servlet> 找到相应的servlet类执行