Servlet 模板

Servlet配置文件模板 web.xml

<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">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
                                                    
  <!-- 根據servlet規範,需要將servlet部署到web.xml文件 -->
  <servlet>
    <!-- servlet-name 給該servlet去個名字,默認使用Servlet的名字 -->
    <servlet-name>MyFirstServlet</servlet-name>
    <!-- servlet-class 要指明該servelt放在哪個包下 -->
    <servlet-class>com.wucheng.day01.MyFirstServlet</servlet-class>
  </servlet>

  <!-- servlet 的映射 -->
  <servlet-mapping>
    <!-- servlet-name 名字要與上面的一樣 -->
    <servlet-name>MyFirstServlet</servlet-name>
    <!-- url-pattern 資源定位,這裏就是將來訪問該Servlet的資源名部分 -->
    <url-pattern>/MyFirstServlet</url-pattern>
  </servlet-mapping>
</web-app>


Servelt類

public class MyHttpServlet extends HttpServlet{
    //在HttpServlet中,設計者對post提交和get提交分別處理
    //默認是get提交
    //doGet() doPost()都去調用了service方法
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("--doGet()..--");
        response.getWriter().println("i am httpServlet doGet()");
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("--doPost()..--");
        response.getWriter().println("i am httpServlet doPost()" + request.getParameter("username"));
    }
}


HTML頁面

<html>
  <head>
    <title>login.html</title>
  </head>
  <body>
    <form action="/ServletWeb/MyHttpServlet" method="Post">
        username:<input type="text" name="username" />
        <input type="submit" value="登陸" />
    </form>
  </body>
</html>


發佈了40 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章