0

I'm new to JSP/Servlet based web programming. I am currently following some tutorials of servlet and JSP but I found some of the example given doesn't make too much sense for me, for example, in one of the examples of servlet chapter, a servlet look like this:

// 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>");
  }
}

To me, the way of displaying the html content is ugly. So I am wondering whether there is a way to make servlet return an object (or a primitive data type) as response, and the front-end part (jsp) use this object to render html content on the browser. I did some research and found out using

request.setAttribute();

is one of implementation of sending an object as response back to client. So I wrote the following servlet, I just paste a snippet of it:

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

So basically this is JDBC is to extract all the pets' names whose age is 10, then store names in a ArrayList of String. I used setAttribute to store this ArrayList and make the index.jsp to handle this response. The index.jsp looks like this:

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

However, I got an error: An error occurred at line: 6 in the jsp file: /index.jsp Type mismatch: cannot convert from Object to ArrayList

So I'm wondering does anyone know:

  1. What's going wrong on this specific error.

  2. What is the best way to make JSP and servlet interact with each other? How the response from servlet be like? How JSP should handle this response?I don't want to write all the html markup in the servlet apparently.

Any hint/article/code example/blog will be greatly appreciated.

Wenfang Du
  • 8,804
  • 9
  • 59
  • 90
OD Street
  • 1,067
  • 3
  • 14
  • 21
  • You should get a different book. Its out of date. – developerwjk Dec 10 '15 at 22:49
  • In fact, click the `servlets` tag and go to the `info` page there. You'd probably be better off just with that page than that whole book. Like you said "To me, the way of displaying the html content is ugly." Absolutely, its not the right way to go. You already know more than the author of the book. – developerwjk Dec 10 '15 at 22:51
  • However, on the question about the mismatch error, that is very simple: Should be `ArrayList nameList = (ArrayList)request.getAttribute("nameList");` You have to typecast. But that won't fix the bigger problem of how the JSP and Servlet should be relating to each other. – developerwjk Dec 10 '15 at 22:53

0 Answers0