1.在tomcat安装目录中,找到lib->servlet-api.jar包,将其复制到jdk安装目录下的lib中。
2.配置classpath环境:%JAVA_HOME%/lib/servlet-api.jar;
(注:此方法将解决无法编译servlet文件的问题)
3.在web中发布servlet文件:
1)找到tomcat安装路径中:web-app->root->web-inf->web.xml
2)在该文件中加入如下代码:(</description>...</web-app>之中)
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>coreservlets.HelloServlet</servlet-class>//如何该类在一个包中,则此处的类路径为:包名.类名
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/abc/helloservlet</url-pattern>
</servlet-mapping>
保存。
4.在ie中输入:http://localhost:8080/abc/helloservlet 显示成功。
/***HelloServlet.java***/
package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String title="hello";
out.println(ServletUtilities.headWithTitle(title)+
"<body bgcolor=/"#fdf5e6/">/n"+
"<h1>"+title+"</h1>/n"+
"</body></html>");
}
}