java虚拟主机运行servlet时需要在调用路径前以“/servlet/”开头,请参考以下示例:示例中包括test.jsp、web.xml、HelloWorld.class三个文件,分别上传到站点目录下
/htdocs/test.jsp
/htdocs/WEB-INF/web.xml
/htdocs/WEB-INF/classes/HelloWorld.class
上传后访问 http://yourdomain/test.jsp 。
样例程序如下:
(1)web.xml的配置
<?xml version="1.0" ?>
<web-app>
<!-- HICHINA Servlet Test -->
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/servlet/HelloWorld</url-pattern>
</servlet-mapping>
<!-- HICHINA Servlet Test -->
</web-app>
(2)test.jsp文件
<html>
<head>
<title>Hello JSP World!</title>
</head>
<body>
<h1>Hello, JSP World!</h1>
<p>The time now is : <%= new java.util.Date() %>.</p>
<p>To see the servlet example <a href="/servlet/HelloWorld">click here</a>.</p>
</body>
</html>
(3)HelloWorld.java源文件,需要您在本地编译成HellWorld.class
// Filename : HelloWorld.java
// Description : This servlet merely says hello!
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloWorld extends HttpServlet {
public void doGet ( HttpServletRequest request, HttpServletResponse response )
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("");
out.println("Hello, Cruel World!");
out.println("");
out.println("Hello, Cruel World !");
out.println("This is my first servlet.");
out.println("");
}// end doGet
}
//code end
servlet使用实例
最新推荐文章于 2022-10-24 15:11:37 发布