eclipse 是否可以从 Servlet 填充下拉列表(在 HTML/JSP 中)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12631307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it Possible to Populate a Dropdown (In HTML/JSP) From a Servlet?
提问by This 0ne Pr0grammer
Okay, so I had created my first jsp page which basically created 3 drop downs and populated them with information pulled from a database.
好的,所以我创建了我的第一个 jsp 页面,它基本上创建了 3 个下拉列表,并用从数据库中提取的信息填充它们。
However, I was told that this was bad code and I should use a servlet for that database function and error handling, and let the jsp strictly do the displaying.
但是,有人告诉我这是糟糕的代码,我应该为该数据库功能和错误处理使用 servlet,并让 jsp 严格执行显示。
The original jsp code is below:
原始jsp代码如下:
<%@page import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Code Selector</title>
</head>
<body>
<h1>Please select the applicable codes:</h1>
<select name='Code' onchange="showState(this.value)">
<option value="none">Select a code</option>
<%
//Pulls the ids and decriptions from the codes table and stores them in the first drop down
try
{
Class.forName("driverName").newInstance();
Connection con = DriverManager.getConnection("serverURL","username","password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select id, descr from codes");
while(rs.next())
{
%>
<option value="<%=rs.getString(1)%>"><%=rs.getString(1)%> <%=rs.getString(2)%></option>
<%
}
//Closes the database connection
stmt.close();
con.close();
}
catch (ClassNotFoundException e)
{
System.err.println("ClassNotFoundException: " + e.getMessage());
}
catch (SQLException e)
{
System.err.println("SQLException: " + e.getMessage());
}
catch (Exception e)
{
System.err.println("Generic Exception: " + e.getMessage());
}
%>
</select>
<br>
<br>
<select name='Code2' onchange="showState(this.value)">
<option value="none">Select a code</option>
<%
//Pulls the ids and decriptions from the codes table and stores them in the second drop down
try
{
Class.forName("driverName").newInstance();
Connection con = DriverManager.getConnection("serverURL","username","password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select id, descr from codes");
while(rs.next())
{
%>
<option value="<%=rs.getString(1)%>"><%=rs.getString(1)%> <%=rs.getString(2)%></option>
<%
}
//Closes the database connection
stmt.close();
con.close();
}
catch (ClassNotFoundException e)
{
System.err.println("ClassNotFoundException: " + e.getMessage());
}
catch (SQLException e)
{
System.err.println("SQLException: " + e.getMessage());
}
catch (Exception e)
{
System.err.println("Generic Exception: " + e.getMessage());
}
%>
</select>
<br>
<br>
<select name='otherCode' onchange="showState(this.value)">
<option value="none">Select a other code</option>
<%
//Pulls the ids and decriptions from the other codes table and stores them in the third drop down
try
{
Class.forName("driverName").newInstance();
Connection con = DriverManager.getConnection("serverURL","username","password");
Statement stmt = con.createStatement();
ResultSet rs2 = stmt.executeQuery("select id, descr from other_codes");
while(rs2.next())
{
%>
<option value="<%=rs2.getString(1)%>"><%=rs2.getString(1)%> <%=rs2.getString(2)%></option>
<%
}
//Closes the database connection
stmt.close();
con.close();
}
catch (ClassNotFoundException e)
{
System.err.println("ClassNotFoundException: " + e.getMessage());
}
catch (SQLException e)
{
System.err.println("SQLException: " + e.getMessage());
}
catch (Exception e)
{
System.err.println("Generic Exception: " + e.getMessage());
}
%>
</select>
<br>
<br>
<form method = "post">
<input type="submit" value="Submit">
<%
try
{
String Code = request.getParameter("Code");
String Code2 = request.getParameter("Code2");
String otherCode = request.getParameter("otherCode");
Class.forName("driverName").newInstance();
Connection con = DriverManager.getConnection("serverURL","username","password");
Statement stmt = con.createStatement();
//ResultSet rs3 = stmt.executeQuery();
System.out.println("This is the first code: " + Code);
System.out.println("This is the second code: " + Code2);
System.out.println("This is the other code: " + otherCode);
con.close();
stmt.close();
}
catch (ClassNotFoundException e)
{
System.err.println("ClassNotFoundException: " + e.getMessage());
}
catch (SQLException e)
{
System.err.println("SQLException: " + e.getMessage());
}
catch (Exception e)
{
System.err.println("Generic Exception: " + e.getMessage());
}
%>
<script>
window.close();
</script>
</form>
</body>
</html>
And so far, this is what I have with the new jsp and servlet page:
到目前为止,这就是我对新的 jsp 和 servlet 页面所拥有的:
codes-selector.jsp
代码选择器.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE>
Codes
</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H2 ALIGN="CENTER">
Please select the applicable codes:
</H2>
<FORM ACTION="http://localhost:8088/SomeProgram" METHOD="GET">
<CENTER>
<select name='code' onchange="showState(this.value)">
<option value="none">Select a code</option>
</select>
<BR>
<BR>
<select name='code2' onchange="showState(this.value)">
<option value="none">Select a code</option>
</select>
<BR>
<BR>
<select name='otherCode' onchange="showState(this.value)">
<option value="none">Select an other code</option>
</select>
<BR>
<BR>
<!-- Press this to submit form -->
<INPUT TYPE="SUBMIT" VALUE="Submit"/>
</CENTER>
</FORM>
</BODY>
</HTML>
PullCodes.java (servlet):
PullCodes.java (servlet):
package com.firstservlet.alfresco;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
/**
* Servlet implementation class PullCodes
*/
@WebServlet("/PullCodes")
public class PullCodes extends HttpServlet
{
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public PullCodes()
{
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String code = request.getParameter("code");
String code2 = request.getParameter("code2");
String otherCode = request.getParameter("otherCode");
try
{
Class.forName("driverName").newInstance();
Connection con = DriverManager.getConnection("url","username","password");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select id, descr from ref_codes");
ResultSet rs2 = stmt.executeQuery("select id, descr from ref_other_codes");
try
{
while(rs.next())
{
//Is this correct?
code+=("<option value=\"" + rs.getString(1) + "\">" + rs.getString(1) + " " + rs.getString(2) + "</option>");
}
//Closes the database connection
stmt.close();
con.close();
}
catch (Exception e)
{
System.err.println("Insertion Exception: " + e.getMessage());
}
}
catch (ClassNotFoundException e)
{
System.err.println("ClassNotFoundException: " + e.getMessage());
}
catch (SQLException e)
{
System.err.println("SQLException: " + e.getMessage());
}
catch (Exception e)
{
System.err.println("Generic Exception: " + e.getMessage());
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
// TODO Auto-generated method stub
}
}
So now, at this point, I'm not sure how to access that dropdown list element from my html page. And Googling around, I was not seeing anything that appeared to show this being done. Also, from what I read it seems most of the time a servlet is just processing information from the html/jsp page. What I'm doing right now is code+=("<option value=\"" + rs.getString(1) + "\">" + rs.getString(1) + " " + rs.getString(2) + "</option>");
. Is that correct? And if so, how do I link that with the html/jsp page? Or is it not even possible to access that html page on load and populate it using the servlet?
所以现在,在这一点上,我不确定如何从我的 html 页面访问该下拉列表元素。谷歌搜索,我没有看到任何似乎表明已经完成的事情。另外,从我读到的内容来看,大部分时间 servlet 似乎只是处理来自 html/jsp 页面的信息。我现在正在做的是code+=("<option value=\"" + rs.getString(1) + "\">" + rs.getString(1) + " " + rs.getString(2) + "</option>");
。那是对的吗?如果是这样,我如何将其与 html/jsp 页面链接?或者甚至无法在加载时访问该 html 页面并使用 servlet 填充它?
采纳答案by Will Hartung
The classic pattern for this is:
这个的经典模式是:
Browser -- request --> Servlet -- forward --> JSP
The mechanism that the Servlet uses to pass information to the JSP is via putting values in to the actual request.
Servlet 用于将信息传递给 JSP 的机制是通过将值放入实际请求中。
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String id = req.getParameter("id");
String name = getNameFromDBForId(id);
req.setAttribute("name", name);
RequestDispatcher rd = getServletContext().getRequestDispatcher("/page.jsp");
rd.forward(request, response);
}
Then you can use JSP EL (Expression Language):
然后你可以使用 JSP EL(表达式语言):
<html>
<body>
<h1>Hello ${name}</h1>
</body>
</html>
The EL expression ${name}
looks for the name
key in several places, one of which is the request (you can look up the others), and replaces the value in the JSP.
EL 表达式在多个地方${name}
查找name
键,其中之一是请求(您可以查找其他地方),并替换 JSP 中的值。
This works for simple scalars, java beans, collections.
这适用于简单的标量、java bean、集合。
But this is the basic mechanism of how to get data from a Servlet in to a JSP. Look up the JSTL tags for example of iteration and conditional logic.
但这是如何从 Servlet 获取数据到 JSP 的基本机制。查找 JSTL 标记,例如迭代和条件逻辑。
回答by PermGenError
you should be using JSTL tags. scriptlets are discreadited and pretty hard for maintanence. check this linkfor JSTL SQL related tags
你应该使用 JSTL 标签。scriptlet 是不可靠的,而且很难维护。 检查此链接以获取 JSTL SQL 相关标签