繁体   English   中英

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

[英]How to pass a parameter from jsp to java class?

我正在使用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>

我想将变量名放入分配给玩家的构造函数ChatAnnotation()中的以下Java类中:

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 = "";
    }
}

首先,如果要调用ChatAnnotation的构造函数并更改播放器名称,则必须设置参数化的构造函数。

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

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

<%
    String name = (String) session.getAttribute("realname");
    ChatAnnotation chat = new ChatAnnotation(name);
%>

所有的拳头都将一个构造方法+ 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();
%>

在您的文件中写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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM