简体   繁体   中英

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>

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);
}

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]);
    }
%>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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