JSP页面应该如何处理servlet发送的响应?那个servlet应该如何实现这个句柄呢?

时间:2015-12-10 22:47:54

标签: java jsp servlets

我是基于JSP / Servlet的Web编程的新手。我目前正在学习servlet和JSP的一些教程,但我发现给出的一些示例对我来说没有多大意义,例如,在servlet章节的一个示例中,servlet看起来像这样:

// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class
public class HelloForm extends HttpServlet {

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
            throws ServletException, IOException
  {
      // Set response content type
      response.setContentType("text/html");

      PrintWriter out = response.getWriter();
      String title = "Using GET Method to Read Form Data";
      String docType =
      "<!doctype html public \"-//w3c//dtd html 4.0 " +
      "transitional//en\">\n";
      out.println(docType +
                "<html>\n" +
                "<head><title>" + title + "</title></head>\n" +
                "<body bgcolor=\"#f0f0f0\">\n" +
                "<h1 align=\"center\">" + title + "</h1>\n" +
                "<ul>\n" +
                "  <li><b>First Name</b>: "
                + request.getParameter("first_name") + "\n" +
                "  <li><b>Last Name</b>: "
                + request.getParameter("last_name") + "\n" +
                "</ul>\n" +
                "</body></html>");
  }
}

对我而言,显示HTML内容的方式很难看。所以我想知道是否有办法使servlet返回一个对象(或原始数据类型)作为响应,并且前端部分(jsp)使用此对象在浏览器上呈现html内容。我做了一些研究,发现使用

request.setAttribute();

是将对象作为响应发送回客户端的实现之一。所以我写了下面的servlet,我只是粘贴它的片段:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // Driver manager and DB url:
    final String jdbcDriver = "com.mysql.jdbc.Driver";
    final String DBUrl = "jdbc:mysql://localhost/zoo";

    // DB credentials:
    final String userName = "username";
    final String password = "password";

    //DB Query:
    final String sql = "SELECT name FROM pet WHERE age=10;";

    //Response ArrayList:
    ArrayList<String> nameList = new ArrayList<String>();


    try {
        // Register a DB Driver:
        System.out.println("Registering Driver.......");
        Class.forName(jdbcDriver).newInstance();

        // Open a connection:
        System.out.println("Openning conncetion.......");
        Connection conn = DriverManager.getConnection(DBUrl, userName, password);

        // Execute a query:
        System.out.println("Executing query.......");
        Statement stmt = conn.createStatement();


        // Store the result in ResultSet:
        System.out.println("Loading the result......");
        ResultSet rs = stmt.executeQuery(sql);

        // Extract data from ResultSet:
        System.out.println("Extracting data.......");
        while (rs.next()) {
            nameList.add(rs.getString("name"));
        }

    } ...some catch statement

    request.setAttribute("nameList", nameList);
    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

所以基本上这就是JDBC提取所有年龄为10的宠物名称,然后将名称存储在String的ArrayList中。我使用setAttribute存储此ArrayList并使index.jsp处理此响应。 index.jsp看起来像这样:

<%@ page import="java.io.*,java.util.*"%>
<html>
<body>
<jsp:include page = "/GetPet" flush = "true" />
<%
ArrayList<String> nameList = request.getAttribute("nameList");
for (String name : nameList) {
    out.write("<p>" + name + "</p");
}

%>
</body>
</html>

然而,我收到一个错误:     jsp文件中的第6行:/index.jsp发生错误     类型不匹配:无法从Object转换为ArrayList

所以我想知道有没有人知道: 1.这个特定错误出了什么问题。

  1. 使JSP和servlet相互交互的最佳方法是什么? servlet的响应如何? JSP应该如何处理这个响应?我不想显然在servlet中编写所有的html标记。
  2. 任何提示/文章/代码示例/博客将不胜感激。谢谢你的到来!

0 个答案:

没有答案