1.编写servlet,在tomcat\webapps目录下新建文件Test,Test目录如下
Test
|
classes web.xml
|
test01
|
Servletfirst.java
Servletfirst.java文件内容如下
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 package test01; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 public class Servletfirst extends HttpServlet { 12 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { 13 PrintWriter out=response.getWriter(); 14 out.println("Hello world!"); 15 } 16 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException { 17 doGet(request, response); 18 } 19 }
2.在命令行模式下往classpath变量中添加servlet-api.jar的路径,例如set classpath=%classpath%;E:\Program Files\tomcat\lib\servlet-api.jar
进入Servletfirst.java的目录,编译.java文件生成.class文件,javac -d . Servletfirst.java
3.配置web.xml文件
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 <servlet> 2 <servlet-name>Servletfirst</servlet-name> 3 <servlet-class>test01.Servletfirst</servlet-class> 4 </servlet> 5 <servlet-mapping> 6 <servlet-name>Servletfirst</servlet-name> 7 <url-pattern>/hello</url-pattern> 8 </servlet-mapping>
4.在tomcat\bin目录下执行startup.bat开启服务器
5.在浏览器地址栏里输入http://localhost:8080/Test/hello就能访问servlet了。