Rebecca_chu
Rebecca_chu

Reputation: 71

How to pass a parameter from jsp to java class?

I'm using Tomcat8 WebSocket to build a chat room, and the code comes from tomcat's example. But I don't know how to pass my variable into java class, here's my code:

<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>

I want to put variable name into the following java class, inside the constructor ChatAnnotation() that assign to player:

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

Upvotes: 0

Views: 5867

Answers (3)

Abdelhak
Abdelhak

Reputation: 8387

In your file write 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);
    %> 

In your class java do this:

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

Upvotes: 0

Vishal Gajera
Vishal Gajera

Reputation: 4207

Fist of all make one constructor+public getPlayer() method into ChatAnnotation-class like,

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

you .jsp page do likewise,

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

at other end where you want to use(otherFile.jsp) it, pull from session it back, as like when you put it,

<%
ChatAnnotation chatAnno = (ChatAnnotation)session.getAttribute("chatAnno");
String playerName = chatAnno.getPlayer();
%>

Upvotes: 1

Naruto
Naruto

Reputation: 4329

First of all, if you want to call Constructor of ChatAnnotation and change the player name then you have to make parameterized constructor.

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

Now to call this,you have to create object in your JSP page and pass the value to the constructor.

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

Upvotes: 1

Related Questions