怎样编译和运行servlet?

我分五个步骤进行编译和运行servlet:
第一,环境配置:我使用的jsp环境是j2sdk1.4.0_01+Tomcat 4.1.
第二,编译servlet程序:编译servlet程序需要把C:\Tomcat 4.1\common\lib\servlet.jar文件复制到C:\j2sdk1.4.0_01\jre\lib\ext目录下,否则会发生编译错误.
第三,配置web.xml文件
在web.xml文件中加入下列描述代码:
<servlet>
<servlet-name>HelloJsp</servlet-name>
<servlet-class>HelloJsp</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloJsp</servlet-name>
<url-pattern>/servlet/HelloJsp</url-pattern>
</servlet-mapping>
第四,把编译好的class文件放在WEB-INF\classes包内或指定的目录下.
第五,运行.
事例代码:
HelloJsp.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloJsp extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(
"<html>");
out.println(
"<head>");
out.println(
"<title>Hello Jsp!</title>");
out.println(
"</head>");
out.println(
"<body>");
out.println(
"<h1>Hello Jsp!</h1>");
out.println(
"</body>");
out.println(
"</html>");
}
}
按上数步骤,最后在浏览器中输入: http:
//localhost:8080/servlet/HelloJsp
如果出现Hello Jsp!的字样就ok了!

lunzi   2005-06-21 03:04:39 评论:4   阅读:5424   引用:0
换一方式实现 @2008-04-15 17:14:56  lunzi
     可以用MyEclipse建servlet测试类,它会自动帮你配置好,然后按web.xml中的配置访问即可。
@2008-04-08 22:54:00  游客
   我也和楼上的这位朋友一样,前四步照样做了,但就是第五步运行不了,郁闷了好久 啦!
@2007-07-19 08:29:06  lunzi
加入您的web包叫test,
应该是: http://localhost:8080/test/servlet/HelloJsp访问
如果还不行,你把HelloJsp.java放在包里面,如:
package test;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloJsp extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello Jsp!</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Hello Jsp!</h1>");
out.println("</body>");
out.println("</html>");
}
}
servlet布置改为:
<servlet>
<servlet-name>HelloJsp</servlet-name>
<servlet-class>test.HelloJsp</servlet-class>
</servlet>
为何运行不了HelloJsp @2007-07-18 18:38:40  生活
(我的QQ:549466875)

   你好:

        前四步都按照你的要求做了,可是第五步却运行不了,奇怪!

界面如下:
HTTP Status 404 - Servlet HelloJsp is not available

--------------------------------------------------------------------------------

type Status report

message Servlet HelloJsp is not available

description The requested resource (Servlet HelloJsp is not available) is not available.


--------------------------------------------------------------------------------

Apache Tomcat/6.0.10

发表评论>>

署名发表(评论可管理,不必输入下面的姓名)

姓名:

主题:

内容: 最少15个,最长1000个字符

验证码: (如不清楚,请刷新)

Copyright@2004-2010 powered by YuLog