user9338258
user9338258

Reputation:

How to pass an Array from a Class to a JSP File

This is where I create my Array:

   public class Main {
public void main() {
    String[] CartaV={"A","K","Q","J","T","9","8","7","6","5","4","3","2"};
    String[] CartaP={"S","H","C","D"};
    String[] m = new String[7];
    Random rand1 = new Random();
    Random rand2 = new Random();
    for(int i=0;i<7;i++){
        m[i]=CartaV[rand1.nextInt(13)];
        m[i]=m[i]+CartaP[rand2.nextInt(4)];
    }


    //System.out.println(mc.mejorJugada(m));
}

}

And here I got my JSP File, as you can see, I'm importing the class, but still can't find a way to print the Array:

    <%@page import="bootcamp.e003.dos.Main"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Mano7</title>
</head>
<body>
    <%
        //I want to print on screen my array
        for(int i=0;i<6;i++){
            out.println(m[i]);
        }
    %>
</body>
</html>

Upvotes: 0

Views: 511

Answers (2)

Xay
Xay

Reputation: 248

You can accomplish this using Request Attributes!

First, set your Attribute in your Servlet class, like so:

request.setAttribute("testing","testvalue"); //Pass your array here

Then in your view JSP file, you can access it like this:

String testValue = (String) request.getAttribute("testing");

if(testValue != null) {
   System.out.println("Test Value.... "+testValue);
}

Upvotes: 1

jontro
jontro

Reputation: 10628

Currently you're not invoking your main() method in the Main class.

Also you're not returning any value or using any means of sharing variables.

What you could do is change the signature to something like this:

public String[] main() {
 // Code here
  return m;
}

Then in your jsp invoke the method like this:

<%
    String m[] = (new Main()).main();
    for(int i=0;i<6;i++){
        out.println(m[i]);
    }
%>

Upvotes: 1

Related Questions