簡體   English   中英

我如何將字符串數組從 servlet 發送到 jsp 並在 jsp 中接收

[英]How can i send an array of string from servlet to jsp and recieve it in jsp

我的 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 代碼為

<%@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 添加到 combobox cid。 你能告訴我問題出在哪里嗎? 謝謝。

您有 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();

應該刪除,因為這是 JSP 的責任,而不是 servlet。 否則,您將面臨IllegalStateException錯誤的風險。

還要擺脫 JSP 頂部的@page import 他們在錯誤的地方,所有相關的代碼都屬於 servlet。

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

小服務程序

//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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM