java 如何跑html

在Java中,可以使用JEditorPane或WebView组件来运行HTML。将HTML内容设置为组件的URL,然后显示该组件即可。

Java 如何运行 HTML

java 如何跑html

单元1:使用 Java 的内置 Web 服务器运行 HTML

1、1 导入所需的包和类

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

1、2 创建一个继承自 HttpServlet 的类,并重写 doGet() 方法

public class MyServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置响应内容类型为 HTML
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        // 写入 HTML 内容
        out.println("<html>");
        out.println("<body>");
        out.println("<h1>Hello, World!</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

1、3 在主类中创建 ServletContext 对象,并注册自定义的 Servlet

public static void main(String[] args) throws Exception {
    // 创建一个新的 ServletContext 对象
    ServletContext context = new MyServletContext();
    
    // 注册自定义的 Servlet
    context.addServlet("myServlet", new MyServlet()).addMapping("/myServlet");
}

1、4 启动 Web 服务器并访问 HTML 页面

public static void main(String[] args) throws Exception {
    // ...(省略上述代码)
    
    // 启动 Web 服务器,监听指定端口(8080)
    Server server = new Server(8080);
    server.start();
    
    // 访问 HTML 页面,URL 格式为 http://localhost:8080/myServlet
    System.out.println("HTML page is running at http://localhost:8080/myServlet");
}

单元2:使用第三方库 Jetty 运行 HTML

2、1 添加 Jetty 依赖到项目中(以 Maven 为例)

<dependencies>
    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-server</artifactId>
        <version>9.4.35.v20201120</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-servlet</artifactId>
        <version>9.4.35.v20201120</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-webapp</artifactId>
        <version>9.4.35.v20201120</version>
    </dependency>
</dependencies>

2、2 创建一个继承自 javax.servlet.http.HttpServlet 的类,并重写 doGet() 方法(与单元1相同)

2、3 在主类中创建 Jetty 服务器对象,并配置路由和处理程序(与单元1中的上下文对象类似)

public static void main(String[] args) throws Exception {
    // ...(省略上述代码)
    Server server = new Server(8080);
    HttpConfiguration config = new HttpConfiguration(); // 配置 HTTP 选项等参数(可选)
    ServerConnector connector = new ServerConnector(server, config); // 根据需要配置连接器(可选)
    server.addConnector(connector); // 添加连接器到服务器(可选)
    HandlerCollection handlers = new HandlerCollection(); // 创建处理程序集合对象(可选)
    handlers.setHandlers(Arrays.asList(new MyServletHandler())); // 将自定义的处理程序添加到集合中(可选)
    server.setHandler(handlers); // 设置服务器的处理程序集合(可选)
    server.start(); // 启动服务器,监听指定端口(8080)
}