java - 从 Servlet 检索多行到 JSP 时出现问题?

标签 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)

最佳答案

这段代码,

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

应该在 while 循环完成之后

编辑 我必须说你的代码有点乱。您似乎将 JSTL 与 sciptlet 混合在一起(不要使用 sciptlet),并且您的 Serlts 中还有 out.println

关于java - 从 Servlet 检索多行到 JSP 时出现问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40417905/

相关文章:

java - 关于 SWT 应用程序中 html 页面的对话框

java - 每当我需要使用 c3Po 池获取连接时,是否有必要在每个类中调用 getConnection() ?

Spring 和 Jersey rest api 返回 404

javascript - 如何使用 javascript 获取 itemLabel 表单 JSP 的值

java - 将对象绑定(bind)到 JSP 页面上的控件

Java 抛出 servlet 和 stacktrace 问题

java - 在 Java Servlet 中使用 final static 常量是个好主意吗?

java - Servlet Gson().toJson 死循环

java - Android Xml Pull Parser 尝试解析 xml 文件时发生异常

java - LuaJ 迭代强制 Java 对象中的对象数组