servlet创建

  • servlet是一个在服务器上运行的小程序。一个servlet就是一个java类。并且可以通过“请求-相应”编程模型来访问这个驻留在服务器内存里的servlet程序。
  •  
  • 继承HttpServlet
  • 重写doGet()或doPost()方法
  • 在web.xml中注册servlet
  •  
  • Servlet :
  • package servlet;
  • import java.io.IOException;
  • import java.io.PrintWriter;
  • import javax.servlet.ServletException;
  • import javax.servlet.annotation.WebServlet;
  • import javax.servlet.http.HttpServlet;
  • import javax.servlet.http.HttpServletRequest;
  • import javax.servlet.http.HttpServletResponse;
  • /**
  •  * Servlet implementation class TestServlet
  •  */
  • @WebServlet("/TestServlet")
  • public class TestServlet extends HttpServlet {
  •        private static final long serialVersionUID = 1L;
  •       
  •        @Override
  •        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  •               // TODO Auto-generated method stub
  •               PrintWriter out=resp.getWriter();
  •               out.println("hello--");
  •        }
  •        @Override
  •        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  •               // TODO Auto-generated method stub
  •               PrintWriter out=resp.getWriter();
  •               out.println("world");
  •        }
  • }
 
  • web.xml :
  • <?xml version="1.0" encoding="UTF-8"?>
  •   <display-name>Test</display-name>
  •   <welcome-file-list>
  •     <welcome-file>index.html</welcome-file>
  •     <welcome-file>index.htm</welcome-file>
  •     <welcome-file>index.jsp</welcome-file>
  •     <welcome-file>default.html</welcome-file>
  •     <welcome-file>default.htm</welcome-file>
  •     <welcome-file>default.jsp</welcome-file>
  •   </welcome-file-list>
  •  
  •   <servlet>
  •        <servlet-name>TestServlet</servlet-name>
  •        <servlet-class>servlet.TestServlet</servlet-class>
  •   </servlet>
  •   <servlet-mapping>
  •        <servlet-name>TestServlet</servlet-name>
  •        <url-pattern>/servlet/TestServlet</url-pattern>
  •   </servlet-mapping>
  • </web-app>
 
posted @ 2019-05-12 13:52  woldcn  阅读(145)  评论(0编辑  收藏  举报