Home > Enterprise >  How to print 2d array created using java in HTML
How to print 2d array created using java in HTML

Time:10-18

I'm trying to print a 2d array on HTML. I'm trying to learn "Spring Boot Framework" and I'm stuck here. Is anybody know the solution? Posting my codes below, please help me.

MatrixApplication.java

package com.example.matrix;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MatrixApplication {

    public static void main(String[] args) {
        SpringApplication.run(MatrixApplication.class, args);
    }
}

IndexController.java

package com.example.matrix.controller;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import com.example.matrix.model.Matrix;


@Controller
public class IndexController {
    @GetMapping("/")
    public String index() {
        return "index";
    }
    
    @PostMapping("/generate")
    public String matrixRegistration(@ModelAttribute Matrix matrix, Model model) {

        matrix.fillArrayList();
        model.addAttribute("matrix", matrix);
        return "redirect:/";
    }
}

Matrix.java

package com.example.matrix.model;

import java.util.Arrays;
import java.util.Random;

public class Matrix {

    
    public String xValue;
    public String yValue;
    public String matrixList[][];
        

    public Matrix() {
        fillArrayList();
    }

    public void setMatrixList(String[][] matrixList) {
        this.matrixList = matrixList;
    }

    public void printMatrixList() {
        
        for(int i=0; i < Integer.parseInt(this.xValue); i  ){
            for(int j=0; j < Integer.parseInt(this.yValue); j  ){
                System.out.print(this.matrixList[i][j]   " ");
            }
            System.out.println("");
        }
    }

    @Override
    public String toString() {
        return "Matrix [matrixList="   Arrays.toString(matrixList)   "]";
    }

    public void fillArrayList() {
        int xValue = Integer.parseInt(this.xValue);
        int yValue = Integer.parseInt(this.yValue);
        this.matrixList = new String[xValue][yValue];
        
        
        Random rand = new Random(); 
        for(int i=0; i < xValue; i  ){
            for(int j=0; j < yValue; j  ){
                this.matrixList[i][j] = String.valueOf(rand.nextInt(100));
            }
        }
    }
}

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<form action="generate" method="post">
<label for="x">X</label>
<input type="text" name="xValue"/><br />
<label for="y">Y</label>
<input type="text" name="yValue"/> <br />
<button type="submit">Generate</button>
</form>

<table border="1" cellpadding="10">
        <table border="1" cellpadding="10">
            <tbody>
            <tr th:each="matrix : ${matrix}">
                <td th:text="${matrix.xValue}"></td>
                <td th:text="${matrix.yValue}"></td>
            </tr>
            </table>
</table>

</body>
</html>

Part of the error I got. I cut it in half because it was too long.

    java.lang.NumberFormatException: Cannot parse null string
        at java.base/java.lang.Integer.parseInt(Integer.java:630) ~[na:na]
        at java.base/java.lang.Integer.parseInt(Integer.java:786) ~[na:na]
        at com.example.matrix.model.Matrix.fillArrayList(Matrix.java:38) ~[classes/:na]
        at com.example.matrix.model.Matrix.<init>(Matrix.java:15) ~[classes/:na]
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na]
        at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77) ~[na:na]
        at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na]
        at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499) ~[na:na]
        at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480) ~[na:na]
        at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:211) ~[spring-beans-5.3.23.jar:5.3.23]
        at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.constructAttribute(ModelAttributeMethodProcessor.java:247) ~[spring-web-5.3.23.jar:5.3.23]
        at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:220) ~[spring-web-5.3.23.jar:5.3.23]
        at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:85) ~[spring-webmvc-5.3.23.jar:5.3.23]
2022-10-17 20:27:10.540 ERROR 39459 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.matrix.model.Matrix]: Constructor threw exception; nested exception is java.lang.NumberFormatException: Cannot parse null string] with root cause

java.lang.NumberFormatException: Cannot parse null string
    at java.base/java.lang.Integer.parseInt(Integer.java:630) ~[na:na]
    at java.base/java.lang.Integer.parseInt(Integer.java:786) ~[na:na]
    at com.example.matrix.model.Matrix.fillArrayList(Matrix.java:38) ~[classes/:na]
    at com.example.matrix.model.Matrix.<init>(Matrix.java:15) ~[classes/:na]
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na]
    at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:77) ~[na:na]
    at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na]
    at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499) ~[na:na]
    at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:480) ~[na:na]
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:211) ~[spring-beans-5.3.23.jar:5.3.23]
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.constructAttribute(ModelAttributeMethodProcessor.java:247) ~[spring-web-5.3.23.jar:5.3.23]
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.createAttribute(ModelAttributeMethodProcessor.java:220) ~[spring-web-5.3.23.jar:5.3.23]
    at org.springframework.web.servlet.mvc.method.annotation.ServletModelAttributeMethodProcessor.createAttribute(ServletModelAttributeMethodProcessor.java:85) ~[spring-webmvc-5.3.23.jar:5.3.23]
    at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:147) ~[spring-web-5.3.23.jar:5.3.23]
    at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:122) ~[spring-web-5.3.23.jar:5.3.23]
    at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:179) ~[spring-web-5.3.23.jar:5.3.23]
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:146) ~[spring-web-5.3.23.jar:5.3.23]

Thank you for your attention. Good deeds.

CodePudding user response:

Based on the assumption that you've filled in valid data in the form you'r submitting to the post. You will need standard setter (and maybe getter for view) methods for spring to be able to fill your model entity.


Also <tr th:each="matrix : ${matrix}"> is problematic as you'r defining the same variable name twice this way.

To prevent errors like these it's good practice to add bean validation with @NotNull on your y and x variables and modify controller as such

@PostMapping("/generate")
public String matrixRegistration(@Valid Matrix matrix, Model model, BindingResult bindingresult) 
{
    if (bindingResult.hasErrors())
    {
        //handle errors
    }
    matrix.fillArrayList();
    model.addAttribute("matrix", matrix);
    return "redirect:/";
}

see https://zetcode.com/spring/bindingresult/ for more details

CodePudding user response:

Thank you so much friends i will try yours suggestions. Now i changed to my code arrayList, maybe normal arrays not worked good.

my new Matrix.java

package com.example.matrix.model;

import java.util.ArrayList;
import java.util.Random;

public class Matrix {

    
    public int xValue;
    public int yValue;
    public ArrayList< ArrayList<Integer> > firstImplementationOfList = new ArrayList<ArrayList<Integer> >();
    
    public int getxValue() {
        return xValue;
    }


    public void setxValue(int xValue) {
        this.xValue = xValue;
    }


    public int getyValue() {
        return yValue;
    }


    public void setyValue(int yValue) {
        this.yValue = yValue;
    }


    public Matrix() {
        printMatrixList();
    }


    public void printMatrixList() {
        
        for(int i = 0; i < xValue; i  ) {
            firstImplementationOfList.add(new ArrayList<Integer>());
                System.out.println(firstImplementationOfList.get(i));
        }
    }


    public void fillArrayList() {
        Random random = new Random();
        for(int i = 0; i < xValue; i  ) {
            firstImplementationOfList.add(new ArrayList<Integer>());
            for(int j = 0; j < yValue; j  ) {
                firstImplementationOfList.get(i).add(j,random.nextInt(100));
            }
        }
    }
}

And my new IndexController.java

package com.example.matrix.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

import com.example.matrix.model.Matrix;

@Controller
public class IndexController {
    @GetMapping("/")
    public String index() {
        return "index";
    }
    
    @PostMapping("/generate")
    public String matrixRegistration(@ModelAttribute Matrix matrix, Model model) {

        matrix.fillArrayList();
        
        List listMatrix = new ArrayList<ArrayList>();
        
        for(int i = 0; i < matrix.xValue; i  ) {
            listMatrix.add(matrix.firstImplementationOfList.get(i));
        }
        
        for(int i = 0; i < matrix.xValue; i  ) {
            System.out.println(listMatrix.get(i));
        }
        
        model.addAttribute("matrix", listMatrix);
        return "redirect:/";
        
    }
}

And my new index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>

<form action="generate" method="post">
<label for="xValue">xValue</label>
<input type="number" name="xValue"/> <br />
<label for="yValue">yValue</label>
<input type="number" name="yValue"/>  <br />
<button type="submit">Generate</button>
</form>

<br />
    <table border="1" cellpadding=  "10">
    <tbody>
    <p>test</p>
            <tr th:each="matrix : ${listMatrix}">
                <td th:text="${matrix.xValue}">xValue</td>
                </td>
            </tr>
        </tbody>
    </table>

</body>
</html>

this codes working at terminal but not working on web browser. I think matrix generations and listing codes working well but i have no idea how i can sent my list to html.

I will try your suggestions now i hope that will work

  • Related