自己在记事本上创建一个Servlet类,通过Dos命令窗口编译Servlet,再把编译好的class文件部署到tomcat服务器运行。
- package cn.itcast.firstapp.servlet;
-
- import java.io.*;
- import javax.servlet.*;
-
- public class FirstServlet extends GenericServlet {
- public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
- // 得到输出流对象
- PrintWriter out = response.getWriter();
- // 使用输出流对象向客户端发送字符数据,在这里就是servlet对请求的响应
- out.println("Hello World");
- }
- }
javac -encoding utf-8 FirstServlet.java
1、打开tomcat的webapps目录:
2、创建web应用名称,即创建文件夹,名称为chapter03
3、在chapter03文件夹下,创建\WEB-INF\classes\cn\itcast\firstapp\servlet目录,将字节码文件复制到这里,如下图:
在web.xml中配置如下:
- "1.0" encoding="UTF-8"?>
- <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
-
- <servlet>
- <servlet-name>FirstServletservlet-name>
- <servlet-class>cn.itcast.firstapp.servlet.FirstServletservlet-class>
- servlet>
-
-
- <servlet-mapping>
- <servlet-name>FirstServletservlet-name>
-
- <url-pattern>/FirstServleturl-pattern>
- servlet-mapping>
-
- web-app>
http://localhost:8080/chapter03/FirstServlet
结果如下: