一:Servlet
Servlet是Java服务器端编程,不同于一般的Java应用程序,Servlet程序是运行在服务器上的,服务器有很多种,Tomcat只是其中一种。
例子:
在Eclipse中新建一个Web
在src中新建一个包,其中新建一个类叫 XXXXServlet
编写Servlet程序如下:
1 package com.sally.servlet; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import java.util.Date; 6 7 import javax.servlet.ServletConfig; 8 import javax.servlet.ServletException; 9 import javax.servlet.annotation.WebServlet; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 14 /** 15 * Servlet implementation class HelloWorldServlet 16 */ 17 @WebServlet("/HelloWorldServlet") 18 public class HelloWorldServlet extends HttpServlet { 19 private static final long serialVersionUID = 1L; 20 21 /** 22 * @see HttpServlet#HttpServlet() 23 */ 24 public HelloWorldServlet() { 25 super(); 26 // TODO Auto-generated constructor stub 27 } 28 29 /** 30 * @see Servlet#init(ServletConfig) 31 */ 32 public void init(ServletConfig config) throws ServletException { 33 34 } 35 36 /** 37 * @see Servlet#destroy() 38 */ 39 public void destroy() { 40 41 } 42 43 /** 44 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 45 */ 46 @SuppressWarnings("deprecation") 47 @Override 48 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 49 response.setContentType("text/html"); 50 PrintWriter out = response.getWriter(); 51 out.println("<html><head><title>Hello World Sample</title></head>"); 52 out.println("<body><h1>Hello World Title<h1><h2>" +new Date().toLocaleString() + "</h2></body></html>"); 53 out.flush(); 54 } 55 56 /** 57 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 58 */ 59 @Override 60 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 61 System.out.println("进入"+ this.getClass().getName()); 62 } 63 64 }
Servlet程序没有main方法,类一般都需要继承HttpServlet类。
二:web.xml
打开web.xml,编写内容如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 5 id="WebApp_ID" version="3.0"> 6 <servlet> 7 <servlet-name>HelloWorldServletName</servlet-name> 8 <servlet-class>com.sally.servlet.HelloWorldServlet</servlet-class> 9 </servlet> 10 <servlet-mapping> 11 <servlet-name>HelloWorldServletName</servlet-name> <!--servlet-name 要和上面的保持一致--> 12 <url-pattern>/HelloWorld</url-pattern> 13 </servlet-mapping> 14 </web-app>
三:访问(HelloWorldServlet)页面
首先进行部署,这里采用在Tomcat的conf的server.xml的Host标签中加入
<Context docBase="Web" path="/Web" reloadable="true" source="org.eclipse.jst.jee.server:Web"/></Host>
然后运行服务器:
然后在浏览器中输入:http://localhost:8080/HelloWeb/HelloWorld
效果如:如下