我怎么能从servlet发送一个字符串数组到jsp并在jsp中接收它

时间:2011-05-05 08:58:46

标签: java jsp servlets

我的Servlet代码是

package DBCon;

import java.io.*;
import java.net.*;
import java.util.ArrayList;

import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
/**
 *
 * @author Nayan
 */
public class loadCourseId extends HttpServlet {

    /** 
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        ArrayList ar1=new ArrayList();
        ArrayList ar2=new ArrayList();
        int i;
        i=0;

        try
        {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost/online_exam?"+"user=root&password=pass");
            Statement stmt=con.createStatement();
            ResultSet rs=stmt.executeQuery("select * from course");

            while(rs.next())
            {
                ar1.add(rs.getString(1));
                ar2.add(rs.getString(2));
            }
            request.getSession().setAttribute("CourseID", ar1);
            request.getSession().setAttribute("CourseName", ar2);
            RequestDispatcher requestDispatcher=getServletContext().getRequestDispatcher("http://localhost:8080/ONLINE_EXAM/removeCourse.jsp");
            requestDispatcher.forward(request,response);


        }
         catch(Exception e) { 
            out.println("<h1>"+e.getStackTrace()+"</h1>");
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
    * Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}

Jsp Code是

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="javax.servlet.*"%>
<%@ page import="java.util.ArrayList.*" %>
<%@ page import="java.sql.*;" %>

<html>
    <head>
        <script type="text/javascript" language="Javascript" >
            window.onload=function LoadCombo()
            {

               window.action="loadCourseId.do";
               ArrayList cd=new ArrayList();
               cd.add(request.getSession().getAttribute("CourseID"));
               if(cd.isEmpty()==false)
               {
                   for(int i=0;i<cd.size();i++)
                   {
                       var newOpt = cid.appendChild(document.createElement('option'));
                       newOpt.text = cd.get(i);

                   }
               }
               else
               {
                   alert("Course table is empty")
               }

            }

        </script>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Remove Course</title>
<style type="text/css">
            <!--
body {
    background-color: #FFCCFF;
}
.style1 {
    color: #0066FF;
    font-weight: bold;
}
.style2 {font-size: 18px}
.style17 {  font-family: "Monotype Corsiva";
    font-size: 24px;
    font-weight: bold;
    font-style: italic;
    color: #6633CC;
}
.style19 {color: #000099}
.style21 {color: #000099; font-weight: bold; }
-->
        </style>
    </head>
    <body>
        <jsp:include page="Log_Admin.jsp"/><br/>
        <form action="" method="post" name="form1" id="form1" >
        <table width="46%" height="43" border="3" bgcolor="##CCCC99" align="center">
            <tr>
                <td width="85%" align="center" bgcolor="##CCCC99"><label><span class="style17">Course Information</span></label></td>
            </tr>

            <tr><td>
                <table width="666" height="207" border="0" align="center" bordercolor="#F0F0F0" bgcolor="#CCCC99" >
                    <tr>
                        <td width="186" height="46" align="left"><div align="left"><span class="style19">
                        <label><strong>Course ID</strong></label>
                        </span></div></td>

                        <td><label>
                        <select name="cid" size="1" id="cid" align="left">


                        </select>
                        </label></td>
                    </tr>
                    <tr>
                        <td height="53" align="left"><div align="left"><label><span class="style21">Course Name</span></label></div></td>
                        <td align="left"><input name="cname" type="text" id="cname" size="50" maxlength="50" /></td>
                    </tr>

                    <tr>
                        <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
                        <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input name="save" type="submit" id="save" value="Save" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <input name="reset" type="reset" id="reset" value="Reset" /></td>
                    </tr>
                </table>
            </td></tr>
        </table>
    </form>
    </body>
</html>

通过编写此代码,我无法将项目CourseId添加到组合框cid中。你能说我问题在哪里吗?感谢。

2 个答案:

答案 0 :(得分:4)

您有2个同步列表,其项目彼此相关。这不容易维护和遍历。而是将两个列表的值放在Map

Map<String, String> courses = new LinkedHashMap<String, String>();
// ...
while(resultSet.next()) {
    map.put(resultSet.getString(1), resultSet.getString(2));
}
// ...
request.setAttribute("courses", courses);

在JSP中,您可以使用JSTL <c:forEach>标记来迭代ListMap。如果是Map,则每次迭代都会在var属性中为您提供Map.Entry,而getKey()属性又包含getValue()<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> ... <select name="cid" size="1" id="cid" align="left"> <c:forEach items="${courses}" var="course"> <option value="${course.key}">${course.value}</option> </c:forEach> </select> 方法。所以这应该做:

processRequest()

此外,response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); 方法

中的前两行
IllegalStateException

应该删除,因为这是JSP的负责任,而不是servlet。否则,这样做会有@page import个错误。

还要删除JSP顶部的{{1}}。它们位于错误的位置,所有相关的代码都属于servlet。

答案 1 :(得分:1)

class MyBean{
  String val;
  String label;
  //+getters setters method
}

的Servlet

//fetching list of MyBean and setting it to request as attribute

       request.setAttribute("beanList",beanList);

   // forward this request to jsp

JSP

<select>
  <c:forEach var="bean" items="${beanList}">
    <option value="${bean.value}">${bean.label}</option>
  </c:forEach>
</select>