Spring MVC中如何提取列表内designation为空的姓名至单独列表
实现步骤
1. 定义员工实体类
创建对应数据结构的Employee实体类,包含所需字段及对应的构造方法、Getter/Setter:
public class Employee { private String name; private String salary; private String designation; public Employee(String name, String salary, String designation) { this.name = name; this.salary = salary; this.designation = designation; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSalary() { return salary; } public void setSalary(String salary) { this.salary = salary; } public String getDesignation() { return designation; } public void setDesignation(String designation) { this.designation = designation; } }
2. 编写Spring MVC Controller逻辑
在Controller中初始化员工数据,过滤出designation为空字符串的人员姓名,将结果存入Model传递给JSP:
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @Controller public class EmployeeController { @GetMapping("/empty-designation-staff") public String getEmptyDesignationStaff(Model model) { // 初始化给定的员工数据集 List<Employee> employeeList = new ArrayList<>(); employeeList.add(new Employee("zakir", "44003", "")); employeeList.add(new Employee("Sheela", "24303", "Developer")); employeeList.add(new Employee("Meghana", "100000", "Tester")); // 过滤出职位为空的员工姓名列表 List<String> emptyDesigNames = employeeList.stream() .filter(emp -> emp.getDesignation().isEmpty()) .map(Employee::getName) .collect(Collectors.toList()); // 将列表存入Model,供JSP页面调用 model.addAttribute("emptyDesigNames", emptyDesigNames); // 返回对应的JSP视图名称 return "staff-view"; } }
3. 编写JSP页面渲染下拉框
在staff-view.jsp中使用JSTL标签循环生成下拉框选项:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html> <html> <head> <title>职位为空员工列表</title> </head> <body> <h3>职位未填写的员工</h3> <select> <c:forEach items="${emptyDesigNames}" var="name"> <option value="${name}">${name}</option> </c:forEach> </select> </body> </html>
注意事项
- 确保项目已引入JSTL依赖,否则JSP中的
<c:forEach>标签无法正常生效。 - 若员工数据来自数据库或其他外部源,只需替换Controller中初始化
employeeList的逻辑,过滤规则保持不变即可。
内容的提问来源于stack exchange,提问作者hussain
相关产品推荐
相关产品推荐

