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>


你可能感兴趣的:(servlet)