java 从 Servlet 到 JSP 显示 MySQL 查询结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13410284/
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
Displaying MySQL Query Results from Servlet to JSP
提问by PeerPressure
I am trying to store the results of my query in a string, and print them to the bottom of my JSP page by passing that string to it. Right now, the JSP page displays fine initially, but nothing is happening when I click the button to post the command. Earlier when I accessed the servlet from an html page, and printed all my output to out using a PrintWriter, I got the results to display, but they would display on a separate page.
我试图将我的查询结果存储在一个字符串中,并通过将该字符串传递给它来将它们打印到我的 JSP 页面的底部。现在,JSP 页面最初显示正常,但是当我单击按钮发布命令时没有任何反应。早些时候,当我从 html 页面访问 servlet,并使用 PrintWriter 将所有输出打印出来时,我得到了要显示的结果,但它们会显示在单独的页面上。
1) Is it a good idea to store out in this way, or should I make it something different than a string?
1)以这种方式存储是个好主意,还是应该让它与字符串不同?
2) How do I get the results of the query to post to the JSP page?
2) 如何获取查询结果以发布到 JSP 页面?
databaseServlet.java
数据库Servlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
@SuppressWarnings("serial")
public class databaseServlet extends HttpServlet {
private Connection conn;
private Statement statement;
public void init(ServletConfig config) throws ServletException {
try {
Class.forName(config.getInitParameter("databaseDriver"));
conn = DriverManager.getConnection(
config.getInitParameter("databaseName"),
config.getInitParameter("username"),
config.getInitParameter("password"));
statement = conn.createStatement();
}
catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String out = "\n";
String query = request.getParameter("query");
if (query.toString().toLowerCase().contains("select")) {
//SELECT Queries
try {
ResultSet resultSet = statement.executeQuery(query.toString());
ResultSetMetaData metaData = resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
for(int i = 1; i<= numberOfColumns; i++){
out.concat(metaData.getColumnName(i));
}
out.concat("\n");
while (resultSet.next()){
for (int i = 1; i <= numberOfColumns; i++){
out.concat((String) resultSet.getObject(i));
}
out.concat("\n");
}
}
catch (Exception f) {
f.printStackTrace();
}
}
else if (query.toString().toLowerCase().contains("delete") || query.toLowerCase().contains("insert")) {
//DELETE and INSERT commands
try {
conn.prepareStatement(query.toString()).executeUpdate(query.toString());
out = "\t\t Database has been updated!";
}
catch (Exception l){
l.printStackTrace();
}
}
else {
//Not a valid response
out = "\t\t Not a valid command or query!";
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/dbServlet.jsp");
dispatcher.forward(request, response);
request.setAttribute("queryResults", out);
}
}
dbServlet.jsp
dbServlet.jsp
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- dbServlet.html -->
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>MySQL Servlet</title>
<style type="text/css">
body{background-color: green;}
</style>
</head>
<body>
<h1>This is the MySQL Servlet</h1>
<form action = "/database/database" method = "post">
<p>
<label>Enter your query and click the button to invoke a MySQL Servlet
<textarea name = "query" cols="20" rows="5"></textarea>
<input type = "submit" value = "Run MySQL Servlet" />
<input type = "reset" value = "Clear Command" />
</label>
</p>
</form>
<hr>
<%=
request.getAttribute("queryResults");
%>
</body>
</html>
回答by Shamis Shukoor
dispatcher.forward(request, response);
request.setAttribute("queryResults", out);
It should be like this
应该是这样的
request.setAttribute("queryResults", out);
dispatcher.forward(request, response);
Before the request is dispatched the attributes has to be set
在发送请求之前,必须设置属性
回答by Yogendra Singh
1) Is it a good idea to store out in this way, or should I make it something different than a string?
1)以这种方式存储是个好主意,还是应该让它与字符串不同?
NO. Don't mix the presentation logic in Java code. Leaverage your JSP for that purposeI would advice you to use JAVA objects and store the row wise values in one object instance. Put all the objects in a collection and use the same in JSP for display. Same goes with column names.
不。不要在 Java 代码中混合表示逻辑。为此目的离开您的 JSP我建议您使用 JAVA 对象并将行明智的值存储在一个对象实例中。将所有对象放在一个集合中,并在 JSP 中使用相同的对象进行显示。列名也是如此。
2) How do I get the results of the query to post to the JSP page?
2) 如何获取查询结果以发布到 JSP 页面?
In your current format of queryResults
, just print the results using =
operator or out.println
method in your JSP as:
在您当前的 格式中queryResults
,只需在 JSP 中使用=
运算符或out.println
方法将结果打印为:
<hr>
<%=request.getAttribute("queryResults"); %>
or
或者
<% out.println(request.getAttribute("queryResults"));%>
But if you decide t use collection as adviced in answer1, then get the collection back from the request, iterate and print the results, e.g. if you decide to use List<String[]>
where String[]
maps one row data then:
但是,如果您决定不按照 answer1 中的建议使用集合,则从请求中取回集合,迭代并打印结果,例如,如果您决定使用List<String[]>
whereString[]
映射一行数据,则:
<TABLE id="results">
<% List<String> columns = (List<String>)request.getAttribute("queryColumns");
List<String[]> results = (List<String[]>)request.getAttribute("queryResults");
out.println("<TR>");
for(String columnName: columns ){
out.println("<TD>"+columnName+"</TD>");
}
out.println("</TR>");
//print data
for(String[] rowData: results){
out.println("<TR>");
for(String data: rowData){
out.println("<TD>"+data+"</TD>");
}
out.println("</TR>");
}
%>
</TABLE>
回答by Thilo
1) Is it a good idea to store out in this way, or should I make it something different than a string?
1)以这种方式存储是个好主意,还是应该让它与字符串不同?
Since this is tabular data, I'd use something that preserves that structure, so that the JSP can piece it apart easily for customized formatting. Bold headers, putting it in an HTML table and stuff. Either some custom bean, or maybe just a List<String[]>
.
由于这是表格数据,我会使用保留该结构的内容,以便 JSP 可以轻松地将其拆分以进行自定义格式设置。大胆的标题,把它放在一个 HTML 表格和东西中。要么是一些自定义 bean,要么只是一个List<String[]>
.
2) How do I get the results of the query to post to the JSP page?
2) 如何获取查询结果以发布到 JSP 页面?
What you are doing now (request.setAttribute) should work. However, you need to set the attribute beforeyou forward the request.
你现在正在做的(request.setAttribute)应该可以工作。但是,您需要在转发请求之前设置该属性。
You could then print the String you now have like this:
然后,您可以像这样打印您现在拥有的字符串:
<%= request.getAttribute("queryResults") %>
Or if you go with a table-structure
或者,如果您使用表结构
<% List<String[]> rows = request.getAttribute("queryResults"); %>
and then loop over that.
然后循环过去。