【问题标题】:Edit .jsp file from Java - Tomcat websocket从 Java 编辑 .jsp 文件 - Tomcat websocket
【发布时间】:2021-01-16 15:34:26
【问题描述】:

经过努力,我设法将客户端与 tomcat 服务器通信。我终于在服务器的handleMessage 中收到了消息。我现在必须更新index.jsp 文件的内容以添加收到的消息。

这是我的服务器 java 类:

package network.server;

import javax.enterprise.context.ApplicationScoped;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@ApplicationScoped
@ServerEndpoint("/status")
public class WebSocket {
    private Set<Session> sessions = new HashSet<>();
    private Session session;

    @OnOpen
    public void onOpen(Session session){
        System.out.println("Session opened in WebSocket ");
        this.session = session;
        sessions.add(session);
    }

    @OnMessage
    public void handleMessage(String message) {
        if (session.isOpen() && session != null){
            try {
                System.out.println("Received this message in the server: " + message);

                //TODO edit jsp
                session.getBasicRemote().sendText("This is a totally unnecessary answer from the server.");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{
            System.out.println("Session is not opened or null");
        }
    }



    @OnClose
    public void close(Session session) {
        System.out.println("Session closed ==>");
        sessions.remove(session);
    }

    @OnError
    public void onError(Throwable e) {
        System.out.println(e.getMessage());
        e.printStackTrace();
    }
}

index.jsp 是默认的:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>My title</title>
  </head>
  <body>
  Hello world!
  </body>
</html>

我怎样才能做到这一点?

【问题讨论】:

    标签: java jsp web tomcat websocket


    【解决方案1】:

    想通了。要编辑jsp,您必须首先在您的java 类中extends HttpServlet 并在其上添加@WebServlet("/uri")。这使它成为一个 servlet,您可以使用 doPostdoGet 的可覆盖函数。

    完成后,在 jsp 文件中,您可以使用 method 标记访问这些方法,例如:

    <form action="servlet" method="get" name="form">
        <input type="submit" value="View nodes"/>
      </form>
    

    操作应与@WebServlet 中使用的uri 匹配。

    或者创建一个你自己的 html,关联到一个带有 websocket 的 javascript 文件,以便像这样与 Tomcat 对话:

    const socket = new WebSocket("ws://localhost:8080/test_war_exploded/status");
    socket.send("Hello there");
    

    并从tomcat回答(s是会话):

    s.getBasicRemote().sendText("General kenobi");
    

    不以这种方式使用 jsp 文件,但您也可以通过这种方式编辑网站。

    在此处查看servlet example,在此处查看websocket example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多