SpringMVC 矩阵乘法:使用对象接收输入并展示结果
首先,需要定义一个矩阵类,包含行数、列数和元素值:
public class Matrix {
private int rows;
private int columns;
private int[][] values;
public Matrix(int rows, int columns, int[][] values) {
this.rows = rows;
this.columns = columns;
this.values = values;
}
// getters and setters
public int get(int i, int j) {
return values[i][j];
}
public void set(int i, int j, int value) {
values[i][j] = value;
}
public Matrix multiply(Matrix other) {
int[][] resultValues = new int[rows][other.columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < other.columns; j++) {
int sum = 0;
for (int k = 0; k < columns; k++) {
sum += values[i][k] * other.values[k][j];
}
resultValues[i][j] = sum;
}
}
return new Matrix(rows, other.columns, resultValues);
}
}
然后,需要定义一个控制器类,在其中处理请求并返回视图:
@Controller
public class MatrixController {
@RequestMapping('/multiply')
public String multiply(@RequestParam('matrix1') Matrix matrix1,
@RequestParam('matrix2') Matrix matrix2,
Model model) {
Matrix result = matrix1.multiply(matrix2);
model.addAttribute('result', result);
return 'result-view';
}
}
其中,@RequestParam 注解用于接收请求中的两个矩阵对象,Model 对象用于传递结果到视图中,'result-view' 是视图的名称。
最后,需要定义一个视图模板 result-view.jsp,用于显示矩阵乘法的结果:
<%@ taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core' %>
<!DOCTYPE html>
<html>
<head>
<title>Matrix Multiplication Result</title>
</head>
<body>
<h1>Matrix Multiplication Result</h1>
<table>
<c:forEach items='${result.values}' var='row'>
<tr>
<c:forEach items='${row}' var='value'>
<td>${value}</td>
</c:forEach>
</tr>
</c:forEach>
</table>
</body>
</html>
其中,<c:forEach> 标签用于遍历矩阵的元素并显示在表格中。
完成以上步骤后,就可以启动应用程序并访问 /multiply 路径,输入两个矩阵的信息,进行乘法运算并显示结果了。
原文地址: https://www.cveoy.top/t/topic/nHMT 著作权归作者所有。请勿转载和采集!