我如何将字符串数组从servlet发送到jsp并在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> </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 通过编写此代码,我无法将项目 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您有 2 个同步列表,其项目彼此相关。这确实不容易维护和遍历。而是将两个列表的值放入
Map
中。在 JSP 中,您可以使用 JSTL
标签来迭代 < code>List 或Map
。对于Map
,每次迭代都会为您提供一个var
属性中的Map.Entry
,该属性又具有getKey()
和 < code>getValue() 方法。所以应该这样做:此外,您的
processRequest()
方法中的前两行应该删除,因为这是 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
.In JSP you can use the JSTL
<c:forEach>
tag to iterate over aList
or aMap
. In case of aMap
, each iteration will give you aMap.Entry
in thevar
attribute which in turn hasgetKey()
andgetValue()
methods. So this should do:Further, the first two lines in your
processRequest()
methodshould 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.服务程序
jsp
Servlet
jsp