我有一个查询数据库并创建arraylists(也就是对象)的Servlet。
这个Servlet包含在一个JSP页面中,用于打印arraylists'内容,但我不知道如何将它们从Servlet传递给JSP。
如何让JSP从Servlet中获取这些对象?
这是我的Servlet代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//CREATING CONTAINERS THAT WILL BE FORWARDED
ArrayList<Volet> voletList = new ArrayList<Volet>();
ArrayList<Critere> critereList = new ArrayList<Critere>();
PrintWriter writer = response.getWriter();
try {
//CONNEXION TO DATABASE:
Class.forName("oracle.jdbc.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:oracle", "OCP", "oracle11g");
Statement st = con.createStatement();
//SQL REQUEST
String sqlVolet = "select * from ocp.volet";
ResultSet rsVolet = st.executeQuery(sqlVolet);
//WRITING FROM SQL RESULT INTO CONTAINER LIST:
while(rsVolet.next())
{
Volet volet = new Volet();
volet.setId(rsVolet.getInt(1));
volet.setDescription(rsVolet.getString(2));
voletList.add(volet);
}
String sqlCritere = "select * from ocp.critere";
ResultSet rsCritere = st.executeQuery(sqlCritere);
while(rsCritere.next())
{
Critere critere = new Critere();
critere.setId(rsCritere.getInt(1));
critere.setDescription(rsCritere.getString(2));
critere.setVoletid(rsCritere.getInt(3));
critereList.add(critere);
}
//CLOSING DATABASE CONNEXION:
con.close();
//DISPATCH THE CONTAINER THROUGH FORWARD
}
catch(Exception e)
{
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/View/ErrorPage.jsp");
request.setAttribute( "e", e );
requestDispatcher.forward(request, response);
}
}
P.S。我试图将对象转发到JSP,但它没有用。
答案 0 :(得分:0)
在servlet代码中使用request.setAttribute
request.setAttribute("attributeName",attributeValue);
RequestDispatcher reqDispatcher = getServletConfig().getServletContext().getRequestDispatcher("JSP file path");
reqDispatcher.forward(request,response);
并在jsp代码中使用request.getAttribute并键入caste it到实际对象类型。
ClassType attributeValue= (ClassType) request.getAttribute("attributeName");