前提:JDK,Eclipse,Tomcat裝好,環境變量配好
- 添加Eclipse的Tomcat插件(下載路徑:http://www.eclipsetotale.com/tomcatPlugin.html)
- 插件裝好之後Window -〉 Perferences -〉 Tomcat 配置Tomcat路徑,然後重啟eclipse
- 新建一個Tomcat Project:ServletDemo
- 右鍵ServletDemo工程 -〉 創建一個Class:ServletDemo.java(創建的Class會自動生成到/WEB-INF/src目錄中)
- 在WEB-INF下添加web.xml
- 點開Project看看Build Automatically又沒有鉤上,沒有鉤上說明不是自動編譯,需要手動Alt + B編譯一下
- 啟動Tomcat,IE輸入http://localhost:8888/ServletDemo/show運行
ServletDemo.java
- package com.tianjf;
-
- import java.io.IOException;
- import java.io.PrintWriter;
-
- import javax.servlet.ServletException;
- import javax.servlet.http.HttpServlet;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- public class ServletDemo extends HttpServlet {
-
- private static final long serialVersionUID = 382354197754278695L;
-
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- resp.setContentType("text/html;charset=UTF-8");
- PrintWriter out = resp.getWriter();
- out.println("<html><head>");
- out.println("<title>First Servlet Hello</title>");
- out.println("</head><body>");
- out.println("Hello!Servlet!");
- out.println("</body></html>");
- out.close();
-
- super.doGet(req, resp);
- }
- }
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
- http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
-
- <servlet>
- <servlet-name>Servlet</servlet-name>
- <servlet-class>com.tianjf.ServletDemo</servlet-class>
- <load-on-startup>0</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>Servlet</servlet-name>
- <url-pattern>/show</url-pattern>
- </servlet-mapping>
- </web-app>