第一个Servlet程序
发布日期:2021-05-09 05:16:48 浏览次数:12 分类:博客文章

本文共 1928 字,大约阅读时间需要 6 分钟。

 

第一个Servlet程序

 

Servlet

  Servlet是Java服务器端编程,不同于一般的Java应用程序,Servlet程序是运行在服务器上的,服务器有很多种,Tomcat只是其中一种。

 

程序实例

  在MyEclipse中新建一个Web Project。

  在src中新建一个包,其中新建一个类叫HelloWorldServlet。

  编写Servlet程序如下:

package com.shengqishiwind.servlet;import java.io.IOException;import java.io.PrintWriter;import java.util.Date;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class HelloWorldServlet extends HttpServlet{    @SuppressWarnings("deprecation")    @Override    public void doGet(HttpServletRequest req, HttpServletResponse resp)            throws ServletException, IOException    {        // 首先将访问修饰符覆写为public        // 设置内容类型         resp.setContentType("text/html");        PrintWriter out = resp.getWriter();        out.println("Hello World Sample");        out.println("

Hello World Title

" +new Date().toLocaleString() + "

"); out.flush(); }}

 

  Servlet程序没有main方法,类一般都需要继承HttpServlet类。

 

web.xml

  web.xml叫做deployment descriptor,部署描述符。

 

  打开web.xml,编写内容如下:

 

HelloWorldServletName
com.shengqishiwind.servlet.HelloWorldServlet
HelloWorldServletName
/HelloWorld

 

 

 

 

访问这个页面

  首先进行部署,这里采用在Tomcat的conf的server.xml的Host标签中加入:(详见

 

 

 

 

  然后运行服务器:

  点击IDE中的Run Server按钮: 

  

  然后在浏览器中输入:

  就可以看到页面。

 

 

过程解释

 

  首先,服务器收到请求,根据其逻辑路径(HelloWeb),找到其物理路径("E:\MDD\MyEclipseWorkspace\HelloWeb\WebRoot")(配置文件中列出的);

  然后根据后面的HelloWorld,找到web.xml中对应的url-pattern,然后找到对应的名字:HelloWorldServletName,根据它找到对应的servlet,其中列出了类名:com.shengqishiwind.servlet.HelloWorldServlet,

  实例化这个类的对象,再执行其中的doGet()方法,将页面返回。

 

  注意,更改Java代码不需要重启服务器(因为server.xml配置文件中加了reloadable="true",所以更改代码时服务器会重启),但是更改配置代码(web.xml中代码)需要重启服务器。

  

  我们可以将Servlet看作是嵌套了HTML代码的Java类;可以将JSP看作是嵌套了Java代码的HTML页面。

 

参考资料

  圣思园张龙老师视频教程。

上一篇:一个简单的Web登录程序 GET和POST的区别
下一篇:使用MyEclipse开发 服务器的部署方式(续)

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年04月14日 08时01分31秒