我正在从事学校项目,我需要以下拉格式从jsp文件中的数据库动态显示学年,部分和中等。我从java类中获取数据库值并尝试在jsp中调用tat java方法来显示这些值,但我没有得到nething der而且我不想在jsp文件中写入查询..请帮助我在过去3天尝试。 .. 我的java类
public class EmpBean {
public java.util.List dataList(){
ArrayList list=new ArrayList();
try {
Class.forName("driver");
Connection con = DriverManager.getConnection("url", "user", "pwd");
Statement st = con.createStatement();
System.out.println("hiiiii");
ResultSet rs = st.executeQuery("select * from employee");
while(rs.next()){
list.add(rs.getString("name"));
list.add(rs.getString("address"));
list.add(rs.getString("contactNo"));
list.add(rs.getString("email"));
}
System.out.println(rs.getString("contactNo"));
}
catch(Exception e){}
return list;
}
}
和我的jsp文件:
<%@page language="java" import="java.util.*" %>
<html>
<body>
<table border="1" width="303">
<tr>
<td width="119"><b>Name</b></td>
</tr>
<%Iterator itr;%>
<%
EmpBean p = new EmpBean();
List list= (List) p.dataList();
%>
for (itr=list.iterator(); itr.hasNext(); ) {
%>
<tr>
<select name="" id="" style="width: 150px;"">
<option value="-1"><%=itr.next()%></option>
</select>
</tr>
<%
}
%>
</table>
</body>
</html>
修改1:
错误讯息:
> The server encountered an internal error () that prevented it from
> fulfilling this request. exception org.apache.jasper.JasperException:
> An exception occurred processing JSP page
> /Administrative/collectFees.jsp at line 93 90: <td colspan="4"><div
> id="fndiv"> 91: <%Iterator itr;%> 92: <% List data=
> (List)request.getAttribute("data"); 93: for (itr=data.iterator();
> itr.hasNext(); ){ 94: %> 95: <select name="year1" id="yr1"
> style="width: 150px;" onclick="showDetails()"> 96: <option
> value="-1">><%=itr.next()%></option> root cause
> java.lang.NullPointerException
答案 0 :(得分:7)
尝试
<%
java.util.List list = new EmpBean().dataList();
%>
要迭代你可以使用
<select>
<%for(String txt : new EmpBean().dataList()){%>
<option><%=txt%></option>
<%}%>
</select>
答案 1 :(得分:3)
坚持良好的编码惯例是好的。
总结以下线程:“在JSP中使用scriptlet(那些&lt; %%&gt;事物)的确非常不鼓励”
答案 2 :(得分:1)
<tr>
<td><select name="" id="" style="width: 150px;"">
<option value="-1"><%=itr.next()%></option>
</select></td>
</tr>
你忘记了td标签