Brian Var
Brian Var

Reputation: 6227

How to print an array to an input field in jsp?

An array of integers fibSequence is passed over to a jsp page result using a redirect which is retrieved like this: <%String[] fibSequence = request.getParameterValues("fibSequence");%>. But when I set the input field's value to the fibSequence array I get a memory address of the array and not the integer values stored in the array:

[Ljava.lang.String;@678f482d

mem address

This is how the array is being output to the text box:

<input type="text" name="fibNum" value="<%=fibSequence%>" size="40px" style="font-size:30pt;height:60px">

and also I've tried like this from the below answer but the output is still the same:

<input type="text" name="fibNum" value="<%=java.util.Arrays.deepToString(fibSequence)%>" size="40px" style="font-size:30pt;height:60px">

Does anyone know how the contents of the array can be output to a textbox in jsp?

I have tried to use the Arrays.toString method to print out the values, but I get an error Arrays cannot be resolved:

<%=Arrays.toString(fibSequence)%>

Upvotes: 1

Views: 2468

Answers (2)

viartemev
viartemev

Reputation: 301

This example is work:
web.xml

<web-app>
  <display-name>Archetype Created Web Application</display-name>
    <filter>
        <filter-name>filter</filter-name>
        <filter-class>ru.bmstu.FirstFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filter</filter-name>
        <url-pattern>*</url-pattern>
    </filter-mapping>
</web-app>

FirsFilter.java

...
    void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter from FirstFilter");
        String[] cba = {"1", "2", "3", "5"};
        request.setAttribute("cba", cba);
        filterChain.doFilter(request, response);
    }
...

index.jsp

<%@ page import="java.util.Arrays" %>
<html>
<body>
<h3>This is the JBoss example!</h3>
<% String[] abc = {"1", "2", "3"};%>
<%=Arrays.toString(abc)%>
<% String[] cba = (String[]) request.getAttribute("cba"); %>
<%=Arrays.toString(cba)%>
</body>
</html>

Result is:

This is the JBoss example!
[1, 2, 3] [1, 2, 3, 5]

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201429

You're getting the default Object.toString() because array (and array is an Object) doesn't override toString(). You could use Arrays.toString(Object[]) like

value="<%=java.util.Arrays.toString(fibSequence)%>"

Or add the import for java.util.Arrays to your JSP.

Upvotes: 1

Related Questions