Servlet的入门案例

 


编写入门案例

1)编写java类,继承HttpServlet类

  2)重新doGet和doPost方法

3)Servlet程序交给tomcat服务器运行!!

   3.1 servlet程序的class码拷贝到WEB-INF/classes目录

   3.2 在web.xml文件中进行配置

 

package com.loaderman.demo;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class TestServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        //向浏览器输出内容
        response.getWriter().write("this is first servlet!");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

 


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!-- servlet的配置 -->
    <servlet>
        <!-- servlet的内部名称,自定义。尽量有意义 -->
        <servlet-name>mTestServlet</servlet-name>
        <!-- servlet的类全名: 包名+简单类名 -->
        <servlet-class>com.loaderman.demo.TestServlet</servlet-class>
    </servlet>


    <!-- servlet的映射配置 -->
    <servlet-mapping>
        <!-- servlet的内部名称,一定要和上面的内部名称保持一致!! -->
        <servlet-name>mTestServlet</servlet-name>
        <!-- servlet的映射路径(访问servlet的名称) -->
        <url-pattern>/demotest</url-pattern>
    </servlet-mapping>
</web-app>

 

posted on 2017-02-19 12:33  LoaderMan  阅读(193)  评论(0编辑  收藏  举报

导航