Reputation: 127
I want to print out 3 buttons using a function inside the jsp file. what is the right way to do so, because my way seems to be wrong.
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test Page</title>
<%!
int j = 3;
%>
<%!
public void manyButtons() {
for (int i = 0; i < j; i++) {
%>
<input type="button" value="button<%=i%>"/>
<%!
}
}
%>
</head
>
<body>
<% manyButtons(); %>
</body>
</html>
Upvotes: 2
Views: 1272
Reputation: 124215
I am not Java EE developer but from what I know your JSP will be translated into servlet which will contain method that you are creating. You must know, that request
and response
objects are passed to service()
method so your method wont have access to response object by default, so it is not able to put output data to writer from response.
If you really must use methods (I would probably use <c:for ...>
from JSTL like Raskolnikov showed +1 for him) you could return data generated in method as String and use them in <%= manyLabels() %>
. What I mean is something like
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Test Page</title>
<%!
public String manyLabels(int j) {
StringBuilder sb=new StringBuilder();
for (int i = 0; i < j; i++) {
sb.append("<input type=\"button\" value=\"button"+i+"\"/>");
}
return sb.toString();
}
%>
</head
>
<body>
<%= manyLabels(3) %>
</body>
</html>
Upvotes: 1
Reputation: 296
As the comment says you want to avoid using Java for this. Thankfully you can easily do it with JSTL. Use a forEach loop like so:
<c:forEach var="i" begin="1" end="3" step="1" varStatus="status">
<input type="button" value="button${i}"/>
</c:forEach>
This should replicate what you're trying to do.
Upvotes: 2