tomcat環境下配置並建立一個servlet小程式
阿新 • • 發佈:2019-01-05
第一個Servlet服務端小程式程式
1,在webapps裡建立一個資料夾myweb,作為你的網站根目錄
在myweb中建立一個目錄WEB-INF
在WEB-INF中建立一個classes目錄
在WEB-INF中建立一個web.xml
可參照下圖建立目錄:
2,在web.xml中配置servlet
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <servlet> <servlet-name>Servlet1</servlet-name> <servlet-class>ServletDemo</servlet-class> </servlet> <servlet-mapping> <servlet-name>Servlet1</servlet-name> <url-pattern>/Servlet1</url-pattern> </servlet-mapping> </web-app>
3.在classes目錄中建立servlet程式
ServletDemo.java 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 { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("hello word!!"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
4.通過:127.0.01:8080/myweb/Servlet1,這樣我們第一個servlet小程式hello word就成功了