我如何将字符串数组从servlet发送到jsp并在jsp中接收它

发布于 2024-11-05 02:10:50 字数 6765 浏览 0 评论 0原文

我的 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>

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

My Servlet Code is

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

And Jsp Code is

<%@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>      </td>
                        <td>       <input name="save" type="submit" id="save" value="Save" />                
                        <input name="reset" type="reset" id="reset" value="Reset" /></td>
                    </tr>
                </table>
            </td></tr>
        </table>
    </form>
    </body>
</html>

Bt by writing this code i am not able to add item CourseId to the combobox cid. Can you say me where is the problem? Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苦妄 2024-11-12 02:10:50

您有 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 标签来迭代 < code>List 或 Map。对于 Map,每次迭代都会为您提供一个 var 属性中的Map.Entry,该属性又具有 getKey() 和 < code>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。

You've 2 synchronous lists whose items are related to each other. This is not really easy to maintain and traverse. Rather put the values of the two lists in a Map.

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

In JSP you can use the JSTL <c:forEach> tag to iterate over a List or a Map. In case of a Map, each iteration will give you a Map.Entry in the var attribute which in turn has getKey() and getValue() methods. So this should do:

<%@ 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>

Further, the first two lines in your processRequest() method

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

should be removed since that's the responsibly of the JSP, not the servlet. You will otherwise risk IllegalStateException errors when doing so.

Also get rid of the @page import in top of your JSP. They are at the wrong place, all associated code belongs in the servlet.

痴情换悲伤 2024-11-12 02:10:50
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>
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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文