有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

如何将参数从jsp传递到java类?

我正在使用Tomcat8 WebSocket构建聊天室,代码来自tomcat的示例。但我不知道如何将变量传递到java类中,下面是我的代码:

<jsp:useBean id="chatannotation" scope="application"
    class="websocket.chat.ChatAnnotation" />
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <%
        String name = (String) session.getAttribute("realname");
    %>
    <a href="chat.jsp">Game</a>
</body>
</html>

我想将变量名放入以下java类中,在分配给player的构造函数ChatAnnotation()中:

public class ChatAnnotation {

    private static final Log log = LogFactory.getLog(ChatAnnotation.class);
    private static final Set<ChatAnnotation> connections =
            new CopyOnWriteArraySet<>();

    private final String player;

    private String username;
    private Session session;

    public ChatAnnotation() {
        player = "";
    }
}

共 (3) 个答案

  1. # 1 楼答案

    首先,将一个构造函数+public getPlayer()方法放入ChatAnnotation类中,如下所示:

    ChatAnnotation(String name){
        player  = name;
    }
    public String getPlayer(){
      return player;
    }
    

    谢谢你。jsp页面也会这样做,

    <%
    String name = (String) session.getAttribute("realname");
    ChatAnnotation chatAnnotation = new ChatAnnotation(name);
    session.setAttribute("chatAnno",chatAnnotation);
    %>  
    

    在您想要使用它的另一端(otherFile.jsp),将它从会话中拉回来,就像您放置它一样,

    <%
    ChatAnnotation chatAnno = (ChatAnnotation)session.getAttribute("chatAnno");
    String playerName = chatAnno.getPlayer();
    %>
    
  2. # 2 楼答案

    首先,如果你想调用ChatAnnotation的构造函数并更改播放器名称,那么你必须创建参数化的构造函数

    public ChatAnnotation(String player) {
        this.player = player;
    }
    

    现在要调用它,必须在JSP页面中创建对象,并将值传递给构造函数

    <%
        String name = (String) session.getAttribute("realname");
        ChatAnnotation chat = new ChatAnnotation(name);
    %>
    
  3. # 3 楼答案

    在文件中写入jsp:

     <jsp:useBean id="chatannotation" scope="application"
    class="websocket.chat.ChatAnnotation" />
    
        <%
        String name = (String) session.getAttribute("realname");
    
    
        //   -now pass parameter "name" to your ChatAnnotation java file
       ChatAnnotation chatAnnotation = new ChatAnnotation(name);
       session.setAttribute("name",chatAnnotation);
        %> 
    

    在java类中,请执行以下操作:

      ChatAnnotation chatAnnotation = (ChatAnnotation)session.getAttribute("name");
     String name = chatAnno.getName();