如何在 Eclipse IDE运行 Servlet

如何在 Eclipse IDE运行 Servlet

如何在 Eclipse IDE运行 Servlet,这是安装 Eclipse,设置 apache tomcat 服务器和运行第一个 hello world servlet 应用的完整指南。

下载 Eclipse IDE

在 Windows 上安装 Eclipse

转到此链接 https://www.eclipse.org/downloads,在“获取 Eclipse Oxygen”下单击“下载软件包”下载“Eclipse IDE for Java Developers”。您会在右侧看到两个选项(32 位和 64 位),如果系统是 32 位,则单击 32 位,否则单击 64 位。这将在您的系统上下载压缩文件。

要安装 Eclipse,请解压缩下载的文件并将解压缩的文件夹复制到所需的位置。

在 Mac OS X 上安装 Eclipse

转到此链接 https://www.eclipse.org/downloads 。在“获取 Eclipse Oxygen”下单击“下载软件包”❯下载“Eclipse IDE for Java Developers”。要下载点击 64 位,它将下载一个 TAR 文件。

下载完成后,双击 TAR 文件,它会将文件的内容提取到一个文件夹中。将文件夹拖到“Applications”文件夹。

要启动 Eclipse ,请单击 Eclipse 文件夹中的 Eclipse 图标。 Mac 用户可以将其拖到停靠区域以从桌面快速启动 Eclipse,类似 Windows 可以在桌面上创建 Eclipse 的快捷方式。

在 Eclipse 中安装和配置 Apache tomcat 服务器

要在 Eclipse IDE 中运行 Servlet,您需要在 Eclipse IDE 中配置 Apache tomcat Server。

在 Eclipse IDE 中创建 Servlet

第 1 步:创建项目:

让我们在 Eclipse 中创建一个 Servlet 应用。打开 Eclipse,然后单击“文件❯新建❯动态 Web 项目”。

提供项目名称,然后单击下一步

勾选显示生成web.xml部署描述符的复选框

初始项目结构:

项目创建后,层次结构(项目结构)如下所示:

第 2 步:创建 Servlet 类:

我们通过扩展HttpServlet类来创建一个HttpServlet。右键单击src文件夹并创建一个新的类文件,将该文件命名为MyServletDemo。文件路径应如下所示:Java Resources/src/default package/MyServletDemo.java

MyServletDemo.java

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

// Extend HttpServlet class to create Http Servlet

public class MyServletDemo extends HttpServlet {

private String mymsg;

public void init() throws ServletException {

mymsg = "Hello World!";

}

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException

{

// Setting up the content type of webpage

response.setContentType("text/html");

// Writing message to the web page

PrintWriter out = response.getWriter();

out.println("

" + mymsg + "

");

}

public void destroy() {

/* leaving empty for now this can be

* used when we want to do something at the end

* of Servlet life cycle

*/

}

}

第 3 步:创建一个 html 页面来调用网页上的 servlet 类

我们正在创建一个 html 文件,一旦我们点击网页上的链接就会调用 servlet。在WebContent文件夹中创建此文件。文件的路径应如下所示:WebContent/index.html

index.html

BeginnersBook Servlet Demo

Click to call Servlet

编辑web.xml文件

此文件可在此路径WebContent/WEB-INF/web.xml中找到。在此文件中,我们将使用特定 URL 映射 Servlet。由于我们在单击index.html页面上的链接时调用欢迎页面,因此我们将欢迎页面映射到我们上面创建的 Servlet 类。

BeginnersBookDemo

index.html

index.htm

index.jsp

default.html

default.htm

default.jsp

MyHttpServletDemo

MyServletDemo

MyHttpServletDemo

/welcome

最终项目结构

运行项目:

右键单击index.html,在服务器上运行。

单击“全部添加”以在服务器上部署项目。单击完成

输出:

单击链接后,您将看到此屏幕:

💫 相关推荐

扬声器测试
国内有bt365网站吗

扬声器测试

📅 08-16 👁️ 1148
《望阙台》译文及注释
国内有bt365网站吗

《望阙台》译文及注释

📅 07-10 👁️ 894
英语干货丨名词前加不加the你还是不确定吗?
365网站余额截图

英语干货丨名词前加不加the你还是不确定吗?

📅 07-29 👁️ 646