新建一个项目,点击 src 选择 New|Servlet .创建一个FirstSer.java文件
package com.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;
/**
* Servlet implementation class FirstSer
*/
public class FirstSer extends HttpServlet {
private static final long serialVersionUID = 1L; //为该servlet设置一个UID号
/**
* @see HttpServlet#HttpServlet()
*/
public FirstSer() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8"); //设置输出流的类型和编码类型
PrintWriter out = response.getWriter(); //得到输出流
out.println("<html>");
out.println("<head><title>The first servlet </title></head>");
out.println("<body>");
out.println("servlet program");
out.println("</body>");
out.println("</html>");
out.flush(); //清楚缓冲区
out.close(); //关闭输出流
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
配置web.xml
<servlet> <!--注册Servlet-->
<description>the description of my component</description>
<display-name>FirstSer</display-name>
<servlet-name>FirstSer</servlet-name>
<servlet-class>com.servlet.FirstSer</servlet-class>
</servlet>
<servlet-mapping> <!--映射servlet-->
<servlet-name>FirstSer</servlet-name>
<url-pattern>/Servlet</url-pattern> <!--Servlet的对外访问路径-->
</servlet-mapping>