我是Spring mvc的新手。目前我正在嘗試創建一個網頁來使用spring mvc執行視圖和創建Employee Object。但是,在我的網頁查看員工的不顯示,數據不會顯示在每個循環的jsp頁面中使用
我的控制器是遵循
package com.testapp.springmvc.controllers;
import java.util.HashMap;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.testapp.springmvc..models.Employee;
@Controller
public class TestController {
HashMap<Integer, Employee> employees = new HashMap<>();
Integer count = 0;
@RequestMapping(value = "/employee", method = RequestMethod.GET)
public String employee(Model model) {
model.addAttribute("employee", new Employee());
model.addAttribute("listOfEmployee", employees.values());
return "employee";
}
@RequestMapping(value = "/employee", method = RequestMethod.POST)
public String addEmployee(@ModelAttribute("employee") Employee employee) {
employees.put(++count, employee);
return "redirect:employee";
}
}
我的JSP的觀點是按照事先
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form:form action="employee" commandName="employee" method="post">
<table>
<tr>
<td><form:input path="id" disable="true" /></td>
</tr>
<tr>
<td>Name of Employee <br> <form:input type="text"
path="fname" name="fname" />
</td>
</tr>
<tr>
<td>Surname of Employee <br> <form:input path="lname"
type="text" name="lname" />
</tr>
<tr>
<td><input type="submit" value="Add Employee" /></td>
</tr>
</table>
</form:form>
<c:if test="${!empty listOfEmployee}">
<table>
<tr>
<th>Employee Name</th>
<th>Surname</th>
</tr>
<c:forEach items="${listOfEmployee}" var="employee">
<tr>
<td>${employee.fname}</td>
<td>${employee.lname}</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
感謝。
你從控制器調用哪種方法? –
當jsp加載employee()方法被調用時,當我們點擊提交按鈕時,addEmployee()被調用。 – nitika
爲什麼你要放這個model.addAttribute(「employee」,new Employee());因爲你聲明僱員對象的哈希映射 – PacMan