Servlet Hello World程序
下文是笔者编写的Servlet Hello World程序,供大家学习,如下所示:
源码下载
实现思路: 1.建立相应的Class文件 2.配置相应的web.xml文件 3.启动tomcat测试ServletServlet需实现一个Servlet接口,下例中实现的是一个HttpServlet类,并重写其中的doGet方法,如下所示:
package servlet01; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ServletHelloWorld extends HttpServlet { /** * */ private static final long serialVersionUID = 888; private String msg; @Override public void init() throws ServletException { // TODO Auto-generated method stub super.init(); msg = "java265.com is Java WebSite."; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub resp.setContentType("text/html"); // 实际的逻辑是在这里 PrintWriter o = resp.getWriter(); o.println("<h1>" + msg + "</h1>"); } }二、配置相应的web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>servlet01</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>helloWorld</servlet-name> <servlet-class>servlet01.ServletHelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloWorld</servlet-name> <url-pattern>/index</url-pattern> </servlet-mapping> </web-app>三、使用tomcat运行此示例程序,将会得到以下效果
源码下载
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。