我已经搜索了这个论坛和网络,找到了很多例子,但我仍然无法填充jsp中的选择框。
我编写了一个 jsp servlet,其中 servlet 返回一个数组列表,在 jsp uhsing jSTL 中,我尝试创建一个选择框并使用数组列表值填充选项。
以下是我的代码。
Servlet 代码:
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response) {
UserService userService = new UserServiceImpl();
try {
String[] questions = userService.getQNA().getQuestions();
List<String> ques = new ArrayList<String>();
ques = Arrays.asList(questions);
request.setAttribute("questionDTO", ques);
response.sendRedirect("forms/enrollMigrationUser.jsp");
} catch (IOException e) {
log.error("request failed "+ e.getMessage());
}
}
JSP代码:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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=ISO-8859-1">
<title>Enroll Migration Users</title>
</head>
<body>
<form method="post" action="/nycb/enrolluser" name="enrollForm">
<table>
<tr>
<td>User setup</td>
<td></td>
</tr>
<tr>
<td>UserId :</td>
<td><input type="text" name="userName" id="userName"/></td>
</tr>
<tr>
<td>Password :</td>
<td><input type="password" name="password" id="password"/></td>
</tr>
<tr>
<td><input type="checkbox" name="computerType" value="public">Authorize this computer</td>
<td></td>
</tr>
<tr>
<td>
<select name='role'>
<c:forEach items="<%=request.getAttribute(\"questionDTO\") %>" var="question">
<option value="<c:out value="${question}"/>"><c:out value="${question}"/></option>
</c:forEach>
</select>
</td>
<td><input type="text" name="qna6" id="qna6"/></td>
</tr>
<tr>
<td>
<select name='role'>
<c:forEach items="${questionDTO}" var="question">
<option value="<c:out value="${question}"/>"><c:out value="${question}"/></option>
</c:forEach>
</select>
</td>
<td><input type="text" name="qna6" id="qna6"/></td>
</tr>
</table>
<input type="submit" value="click" name="dropdown" id="dropdown">
</form>
我无法填充选择框,选项字段为空。
谁能告诉我我哪里出了问题吗?
最佳答案
sendRedirect()
创建一个新请求,请求中设置的任何属性在重定向的 JSP 页面中将不可用。
尝试任何一个
- 在这种情况下,您可以使用
RequestDispatcher#forward
或RequestDispatcher#include
。 - 您可以将其作为属性保存在
session
中。
示例代码:
RequestDispatcher view = request.getRequestDispatcher("forms/enrollMigrationUser.jsp");
view.forward(request, response);
或者
HttpSession session = request.getSession();
session.setAttribute("questionDTO", ques);
response.sendRedirect("forms/enrollMigrationUser.jsp");
<小时/>
始终尽量避免使用 Scriplet 元素,而使用 JSTL 和 EL。
您可以在其中从订单页面、请求、 session 和最终应用程序中的任何范围读取属性
<c:forEach items="${questionDTO}" var="question">
或从特定范围读取。
<c:forEach items="${requestScope.questionDTO}" var="question">
关于java - 使用jSTL和arraylist在jsp中动态创建select标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24339006/