这个程序是在页面上显示当前时间
1。首先确认tomcat安装完毕,我用的是tomcat5.0.28,刚开始用6.0感觉很不好用。安装的时候注意tomcat默认的端口是8080,如果安装了oracle,他有一个服务占用了8080端口,把他改了就可以了方法如下:登录到oracle,点开XML数据库——配置——Http-port,值我把他改成了8090,如图
2。右击我的电脑——管理——服务和应用程序——服务,找到tomcat那一项,将它改为手动,如图
3。安装Myeclipse,这是eclipse的一个插件,功能非常强大,可以自己从网上下载,安装好。因为太大了200多m没法传上去。
4。打开eclipse,窗口——首选项——MyEclipse——Application Servers——Tomcat5,把Tomcat Server点成Enable,Tomcat Home Directory 添上安装Tomcat的路径,我的是装在D:/Program Files/Tomcat 5.0下,如图所示:
5。在eclipse中新建一个Web Project 项目项目名称设为test,servlet类名为T整个项目结构如下图:
6。在中T.java中,输入如下代码:
package t1;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class T extends HttpServlet {
/**
* Constructor of the object.
*/
public T() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print(new Date());
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
}
其实这里面很多代码是新建一个Servlet类自动生成的,自己要改动的只是doGet和doPost方法。
7。打开web.xml,输入如下代码:
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">
8.保存。在myeclipse中将此项目和tomcat关联,方法如下:点击eclipse中按钮,出现如下图所示
点击add,出现如下图所示:
点击完成。ok,关联完成。
9。保存项目。在myeclipse中将tomcat启动,打开ie,在地址栏中输入:http://localhost:8080/test/servlet/T,就可以看到当前时间了。