从Servlet到JSP检索多行的问题?

时间:2016-11-04 08:09:52

标签: java jsp servlets

我是JSP和servlet的初学者。我正在构建这个应用程序,当我按下表单上的搜索时,它应该填充表单字段还显示表中的记录。现在,由于某种原因,我的JSP页面中只显示一条记录,并且有超过4条记录具有相同的电话号码。请你能帮助我吗?我无法弄清楚错误。

Servlet: -

package com.examples.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Surajitdas
 */
public class Search extends HttpServlet {
  private String mobilenumber;
  private String country;
    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet Search</title>");            
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet Search at " + request.getContextPath() + "</h1>");
            out.println("</body>");
            out.println("</html>");
        }
    }

    // <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
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int count =0;
        PrintWriter out = response.getWriter();
        try {
          //processRequest(request, response);
          Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
          Connection conn = null;
          PreparedStatement myStmt = null;
          ArrayList al = new ArrayList();
          ArrayList pid = new ArrayList();
          conn = DriverManager.getConnection("jdbc:sqlserver://MPESA\\SQL2012;user=realm;password=friend;database=ElmaTest");

          if(conn!=null)
          {
              out.println("Connection Succcesful");
              myStmt = conn
                    .prepareStatement("exec p_GetAccountCustomer ?,?,?,?,?,?,?");

                myStmt.setString(1, country);
                myStmt.setString(2, "99");
                myStmt.setString(3, mobilenumber);
                myStmt.setString(4, "");
                myStmt.setString(5, "0");
                myStmt.setString(6, "2001");
                myStmt.setString(7, "127.0.0.1"); 
               ResultSet rs= myStmt.executeQuery();
              while(rs.next())       
              {
                  count ++;
                  String  country = rs.getString("CustomerCountry");
                  String customerid = rs.getString("CustomerID");
                  String TitleofAccount = rs.getString("TitleofAccount");
                  String FirstName = rs.getString("FirstName");
                  String LastName = rs.getString("LastName");
                  String City = rs.getString("City");
                  String Address = rs.getString("Address");
                  String emailid = rs.getString("EmailID");
                  String typeofid = rs.getString("TypeOfID");
                  String Idnumber = rs.getString("IDNumber");
                  String branchid = rs.getString("BranchID");
                  String cardnumber = rs.getString("CardNumber");
                  String bankaccntid = rs.getString("BankAccountID");
                  String currencyid = rs.getString("CurrencyID");
                  String isspeciallimit = rs.getString("IsSpecialLimit");
                  String dailylimit = rs.getString("DayTransactionLimit");
                  al.add(rs.getString("CardNumber"));
                  al.add(bankaccntid);
                  al.add(currencyid);
                  al.add(rs.getString("DayTransactionLimit"));
                  al.add(isspeciallimit);
                  pid.add(al);


                  System.out.println("Count" + count);
                  System.out.println(country);
                  System.out.println(customerid);
                  System.out.println(TitleofAccount);
                  System.out.println(FirstName);
                  System.out.println(LastName);
                  System.out.println(City);

                  System.out.println(Address);
                  System.out.println(emailid);
                  System.out.println(typeofid);
                  System.out.println(Idnumber);
                  System.out.println(branchid);
                  System.out.println(cardnumber);


                  System.out.println(bankaccntid);
                  System.out.println(currencyid);
                  System.out.println(isspeciallimit);
   request.setAttribute("count", count);

  request.setAttribute("country", country);
  request.setAttribute("customerid", customerid);
  request.setAttribute("TitleofAccount", TitleofAccount);
  request.setAttribute("FirstName", FirstName);
  request.setAttribute("LastName", LastName);

  request.setAttribute("City", City);
  request.setAttribute("emailid", emailid);
  request.setAttribute("typeofid", typeofid);
  request.setAttribute("Idnumber", Idnumber);
  request.setAttribute("branchid", branchid);

  request.setAttribute("cardnumber", cardnumber);
  request.setAttribute("bankaccntid", bankaccntid);
  request.setAttribute("currencyid", currencyid);
  request.setAttribute("isspeciallimit", isspeciallimit);
   request.setAttribute("dailylimit", dailylimit);

  request.setAttribute("pid",pid);

  RequestDispatcher rd = request.getRequestDispatcher("CustomerDetails.jsp");
   rd.forward(request, response);








              }


          }
      } catch (ClassNotFoundException ex) {
          Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex);
      } catch (SQLException ex) {
          Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex);
      }

    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //processRequest(request, response);
        PrintWriter out = response.getWriter();
        mobilenumber = request.getParameter("mobilenumber");
        country = request.getParameter("country");

        doGet(request,response);
        //out.println(mobilenumber);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>



}

JSP页面: -

<%@page import="java.util.Iterator"%>
<%@page import="java.util.ArrayList"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HomePage</title>
<script src="JavaScript/SpryMenuBar.js" type="text/javascript"></script>
<link href="styles/SpryMenuBarVertical.css" rel="stylesheet" type="text/css" />
</head>

<body>
<ul id="MenuBar1" class="MenuBarVertical">
  <li><a href="#">Update Limit</a></li>
  </li>
  <li><a href="#">Delink Account</a></li>
  <li><a href="#">Edit CardNumber</a>

  </li>
  <li>
    <a href="#">Linked Accounts</a>
  </li>
  <li><a href="#">SMS Alerts</a>
  <li><a href="#">Join Account</a>


</ul>
<p>&nbsp;</p>
<p>&nbsp;</p>

<form  method="post" action="Search">
  <hr />
<hr />
  <p>
          Client Details
  <hr />
  <hr />
  </p>
  <p>Mobile Number:- 
    <label>
      <input type="text" name="mobilenumber" id="mobilenumber" /> 
    </label>

  </p>
<p>Country:- 
    <label>
      <input type="text" name="country" id="country"  /> 
    </label>

  </p>

    <input type="submit" formaction="Search" name="New" id="New" value="Search" />



</form>
</html>
<html>
    <form method ="get" action="Search">
  <p> Title:-
    <input type="text" name="Title" id="Title" value='<%=(request.getAttribute("TitleofAccount")==null)?"":request.getAttribute("TitleofAccount")%>' />
  </p>
  <p>Middle Name:- 
    <label>
      <input type="text" name="MiddleName" id="Middle Name" />
    </label>
  </p>
  <p>Address:- 
    <label>
      <input type="text" name="address" id="address" />
    </label>
  </p>
  <p>City:- 
    <label>
      <input type="text" name="City" id="City"value='<%=(request.getAttribute("City")==null)?"":request.getAttribute("City")%>'/>
    </label>
  </p>
  <p>Type of ID:- 
    <label>
      <input type="text" name="Idtype" id="Idtype" value='<%=(request.getAttribute("typeofid")==null)?"":request.getAttribute("typeofid")%>' />
    </label>
  </p>
  <p>Elma ID:- 
    <label>
      <input type="text" name="elmaid" id="elmaid" value='<%=(request.getAttribute("customerid")==null)?"":request.getAttribute("customerid")%>'/>
    </label>
  </p>
  <p>First Name:- 
    <label>
      <input type="text" name="firstname" id="firstname" value='<%=(request.getAttribute("FirstName")==null)?"":request.getAttribute("FirstName")%>' />
    </label>
  </p>
  <p>Last Name:- 
    <label>
      <input type="text" name="LastName" id="LastName" value='<%=(request.getAttribute("LastName")==null)?"":request.getAttribute("LastName")%>'/>
    </label>
  </p>
  <p>Registration Branch:- 
    <label>
      <input type="text" name="registrationbranch" id="registrationbranch" />
    </label>
  </p>
  <p>Email address:- 
    <label>
      <input type="text" name="emailid" id="emailid" value='<%=(request.getAttribute("emailid")==null)?"":request.getAttribute("emailid")%>' />
    </label>
  </p>
  <p>ID No:- 
    <label>
      <input type="text" name="idno" id="idno" />
    </label>
  </p>
  <hr />
<hr />
  <p>
          Account Details
  <hr />
  <hr />
  </p>

  <p>Bank A/C id :- 
    <label>
      <input type="text" name="accountid" id="accountid"value='<%=(request.getAttribute("bankaccntid")==null)?"":request.getAttribute("bankaccntid")%>' />
    </label>
  </p>
  <p>Transaction Limit:- 
    <label>
      <input type="text" name="transactionlimit" id="transactionlimit" />
    </label>
  </p>
  <p>Currency:- 
    <input type="text" name="currency" id="currency"value='<%=(request.getAttribute("currencyid")==null)?"":request.getAttribute("currencyid")%>'/>
  </p>
  <p>Daily Limit:- 
    <label>
      <input type="text" name="dailylimit" id="dailylimit" value='<%=(request.getAttribute("dailylimit")==null)?"":request.getAttribute("dailylimit")%>'/>
    </label>
  </p>
  <p>
    <input type="submit"formaction="Connectioncheck" name="Update" id="Update" value="Update" />
  </p>
  <p>&nbsp;</p>
  <hr />
  Account List
  <hr />



<table width="700px" align="center"
               style="border:1px solid #000000;">
            <tr>
                <td colspan=4 align="center"
                    style="background-color:teal">
                    <b>User Record</b></td>
            </tr>
            <tr style="background-color:lightgrey;">
                <td><b>Account No</b></td>
                <td><b>Card Number</b></td>
                <td><b>CurrencyID</b></td>
                <td><b>Daily Limit</b></td>
                <td><b>Status Limit</b></td>


            </tr>

             <%
               // Integer count = Integer.parseInt((String)session.getAttribute("count"));  
               int count =0; 
                String color = "#F9EBB3";
                if (request.getAttribute("pid") != null) {
                    ArrayList al = (ArrayList) request.getAttribute("pid");
                    System.out.println(al);
                    Iterator itr = al.iterator();
                    while (itr.hasNext()) {

                        if ((count % 2) == 0) {
                            color = "#eeffee";
                        }
                        count++;
                        ArrayList pList = (ArrayList) itr.next();
            %>
            <tr style="background-color:<%=color%>;">
                <td><%=pList.get(0)%></td>
                <td><%=pList.get(1)%></td>
                <td><%=pList.get(2)%></td>
                <td><%=pList.get(3)%></td>
                <td><%=pList.get(4)%></td>

            </tr>
            <%
                    }
                }
                if (count == 0) {
            %>
            <tr>
                <td colspan=4 align="center"
                    style="background-color:#eeffee"><b>No Record Found..</b></td>
            </tr>
            <%            }
            %>










        </table>  


  </form>
</html>

----服务器日志---

Warning:   StandardWrapperValve[Search]: Servlet.service() for servlet Search threw exception
java.lang.IllegalStateException: Cannot forward after response has been committed
    at org.apache.catalina.core.ApplicationDispatcher.doDispatch(ApplicationDispatcher.java:448)
    at org.apache.catalina.core.ApplicationDispatcher.dispatch(ApplicationDispatcher.java:428)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:378)
    at com.examples.servlets.Search.doGet(Search.java:163)
    at com.examples.servlets.Search.doPost(Search.java:200)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)

1 个答案:

答案 0 :(得分:1)

此代码,

request.setAttribute("pid",pid);  // and all the others
RequestDispatcher rd = request.getRequestDispatcher("CustomerDetails.jsp");
   rd.forward(request, response);

应该在while循环完成后

修改 我必须说你的代码有点混乱。你似乎把JSTL和sciptlets混在一起(不要使用sciptlets),你的服务中也有out.println