Servlet学习1

1.首先在Tomcat的webapp目录下新建文件夹myWebapp,作为自己的web应用。

2.myWebapp下新建WEB-INF(必须这个名)目录,WEB-INF下新建classes目录放置servlet

3.编写FirstServlet.java 带包名,类必须声明为public,提供给服务器访问。

package com.test;
import java.io.*;
import javax.servlet.*;

public class FirstServlet extends GenericServlet{
    
    public void service(ServletRequest req,ServletResponse res)throws ServletException,java.io.IOException{
        OutputStream out = res.getOutputStream();
        out.write("Hello Servlet!!!".getBytes());
    }
}

设置classpath

 set classpath=%classpath%;E:ProgramToolsapache-tomcat-8.0.48libservlet-api.jar 为javac命令编译提供引入的包

javac -d . FirstServlet.java 编译后,package包名编译为目录

4.WEB-INF下,添加web资源配置文件web.xml; 配置servlet对外访问路径

<?xml version="1.0" encoding="ISO-8859-1"?>
<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_3_1.xsd"
  version="3.1"
  metadata-complete="true">
  
	<servlet>
      <servlet-name>FirstServlet</servlet-name>
      <servlet-class>com.test.FirstServlet</servlet-class>
    </servlet>
    <servlet-mapping>
      <servlet-name>FirstServlet</servlet-name>
      <url-pattern>/test/FirstServlet</url-pattern>
    </servlet-mapping>
  
  </web-app>

  

5.启动Tomcat,访问http://localhost:8080/myWebapp/test/FirstServlet

原文地址:https://www.cnblogs.com/yongwangzhiqian/p/8227700.html