【问题标题】:Get Arraylist To Fill Out Option List(Model To Servlet To Jsp)获取 Arraylist 填写选项列表(模型到 Servlet 到 Jsp)
【发布时间】:2014-05-09 04:56:33
【问题描述】:

我有一个模型、servlet 和 jsp 页面。我想为选项列表提供数组列表中的所有选项,但由于某种原因,我得到了一个空指针异常。

谁能帮我找出我哪里出错了下面是我的代码:

JSP

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page import="java.util.ArrayList" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Customer Management</title>
</head>
<body>
    <form action="/customerManagment" method="post">
        First Name:<br>
        <input type="text" name="firstName"/><br>
        Last Name:<br>
        <input type="text" name="lastName"/><br>
        Email:<br>
        <input type="text" name="email"/><br>
        Phone:<br>
        <input type="text" name="phone"/><br>
        Phone Type:<br>

        Street Address:<br>
        <input type="text" name="streetAddress"/><br>
        Apartment Number:<br>
        <input type="text" name="apartmentNumber"/><br>
        City:<br>
        <input type="text" name="city"/><br>
        State:<br>
        <select>
            <option><%
            ArrayList<edu.witc.Assignment03.model.States> states = (java.util.ArrayList)request.getAttribute("states");
               for (edu.witc.Assignment03.model.States state : states) { 
                   state.getStates();
               }%></option>
        </select><br>

        <input type="submit" value="submit">
        </form>

小服务程序

import java.util.List;    
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//import javax.servlet.annotation.WebServlet;
//import javax.servlet.http.HttpServlet;
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;




import edu.witc.Assignment03.model.Customer;
import edu.witc.Assignment03.model.Phone;
import edu.witc.Assignment03.model.States;

/*
 * Not thread-safe. For illustration purpose only
 */
@WebServlet(name = "CustomerServlet", urlPatterns = { 
        "/customerManagement"})
public class CustomerServlet extends HttpServlet {
    private static final long serialVersionUID = -20L;

    private List<edu.witc.Assignment03.model.States> states = new ArrayList<States>();
    private List<edu.witc.Assignment03.model.Customer> customers = new ArrayList<Customer>();

    public void init() throws ServletException {
       States state = new States();
        states.add(state);

    }

 private void addCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to index
           throws IOException, ServletException {
    String url = "/customerManagement.jsp";
        request.setAttribute("customers", customers);
        request.getRequestDispatcher(url).forward(request,response);
    }

    private void editCustomer(HttpServletResponse response, HttpServletRequest request)//redirect to index
           throws IOException, ServletException {
        String url = "/customerManagement.jsp";
        request.setAttribute("customers", customers);
    request.getRequestDispatcher(url).forward(request,response);
    }

    private void sendCustomerList(HttpServletResponse response, HttpServletRequest request)//redirect to index
            throws IOException, ServletException {
        String url = "/index.jsp";
        request.setAttribute("customers", customers);
        request.getRequestDispatcher(url).forward(request,response);                                           
    }

    private Customer getCustomer(int customerId) {
        for (Customer customer : customers) {
            if (customer.getCustomerId() == customerId) {
                return customer;
            }
        }
        return null;
    }

    private void sendEditCustomerForm(HttpServletRequest request, 
            HttpServletResponse response) throws IOException, ServletException {

        String url = "/customerManagement.jsp";
        request.setAttribute("customers", customers);
        request.getRequestDispatcher(url).forward(request,response);
    }


    public void doGet(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {
        String uri = request.getRequestURI();
        if (uri.endsWith("/customer")) {
            sendCustomerList(response, request);
        } else if (uri.endsWith("/editCustomer")) {
            sendEditCustomerForm(request, response);
        }           
    }

    public void doPost(HttpServletRequest request, 
            HttpServletResponse response)
            throws ServletException, IOException {
        // update customer
        int customerId = 0;
        try {
            customerId = 
                    Integer.parseInt(request.getParameter("id"));
        } catch (NumberFormatException e) {
        }
        Customer customer = getCustomer(customerId);
        if (customer != null) {
            customer.setFirstName(request.getParameter("firstName"));
            customer.setLastName(request.getParameter("lastName"));
            customer.setEmail(request.getParameter("email"));
            customer.setPhone(request.getParameter("phone"));
            customer.setAddress(request.getParameter("address"));
            customer.setCity(request.getParameter("city"));
            customer.setState(request.getParameter("states"));
            customer.setZip(request.getParameter("zip"));
        }
        addCustomer(response, request);
    }
}

型号

package edu.witc.Assignment03.model;

import java.util.ArrayList;
import java.util.List;

public class States {

    private List<String> state = new ArrayList<>();{

    state.add("Alabama");
    state.add("Alaska"); 
    state.add("Arizona"); 
    state.add("Arkansas"); 
    state.add("California"); 
    state.add("Colorado"); 
    state.add("Connecticut"); 
    state.add("Delaware"); 
    state.add("Florida"); 
    state.add("Georgia"); 
    state.add("Hawaii"); 
    state.add("Idaho"); 
    state.add("Illinois"); 
    state.add("Indiana"); 
    state.add("Iowa"); 
    state.add("Kansas"); 
    state.add("Kentucky"); 
    state.add("Louisiana"); 
    state.add("Maine"); 
    state.add("Maryland"); 
    state.add("Massachusetts"); 
    state.add("Michigan"); 
    state.add("Minnesota"); 
    state.add("Mississippi"); 
    state.add("Missouri"); 
    state.add("Montana"); 
    state.add("Nebraska"); 
    state.add("Nevada"); 
    state.add("New Hampshire"); 
    state.add("New Jersey"); 
    state.add("New Mexico"); 
    state.add("New York"); 
    state.add("North Carolina"); 
    state.add("North Dakota"); 
    state.add("Ohio"); 
    state.add("Oklahoma"); 
    state.add("Oregon"); 
    state.add("Pennsylvania"); 
    state.add("Rhode Island"); 
    state.add("South Carolina"); 
    state.add("South Dakota"); 
    state.add("Tennessee"); 
    state.add("Texas"); 
    state.add("Utah"); 
    state.add("Vermont"); 
    state.add("Virginia"); 
    state.add("Washington"); 
    state.add("West Virginia"); 
    state.add("Wisconsin"); 
    state.add("Wyoming");
    }

    public List<String> getStates(){
        return this.state;
    }
}

空指针异常(点击客户按钮后)

Mar 29, 2014 2:42:50 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x86;C:\Program Files (x86)\Intel\OpenCL SDK\2.0\bin\x64;C:\Program Files\Lenovo\Bluetooth Software\;C:\Program Files\Lenovo\Bluetooth Software\syswow64;c:\Program Files (x86)\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\Tools\Binn\;c:\Program Files\Microsoft SQL Server\100\DTS\Binn\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\;C:\Program Files (x86)\Microsoft SQL Server\110\DTS\Binn\;C:\Program Files (x86)\nodejs\;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\;C:\Program Files (x86)\Windows Kits\8.0\Windows Performance Toolkit\;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\RailsInstaller\Git\cmd;C:\RailsInstaller\Ruby1.9.3\bin;C:\Users\esder_000\AppData\Roaming\npm;.
Mar 29, 2014 2:42:50 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Justin_EJ_Assignment03_15400579' did not find a matching property.
Mar 29, 2014 2:42:50 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Mar 29, 2014 2:42:50 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Mar 29, 2014 2:42:50 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 756 ms
Mar 29, 2014 2:42:50 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Mar 29, 2014 2:42:50 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.52
Mar 29, 2014 2:42:51 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Mar 29, 2014 2:42:51 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Mar 29, 2014 2:42:51 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 772 ms
Mar 29, 2014 2:42:55 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/Justin_EJ_Assignment03_15400579] threw exception [java.lang.NullPointerException] with root cause
java.lang.NullPointerException
    at org.apache.jsp.customerManagement_jsp._jspService(customerManagement_jsp.java:94)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
    at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
    at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

【问题讨论】:

  • 您在哪里得到空指针异常。也只需上传异常堆栈跟踪
  • 对不起!我在代码下方上传了异常
  • 浏览器中请求的 url 是什么?当空指针引发..
  • @Rembo 很抱歉,我不理解您的问题。

标签: java jsp jakarta-ee servlets arraylist


【解决方案1】:

看这里:

State:<br>
        <select>
            <option><%
            ArrayList<edu.witc.Assignment03.model.States> states = (java.util.ArrayList)request.getAttribute("states");
               for (edu.witc.Assignment03.model.States state : states) { 
                   state.getStates();
               }%></option>
        </select><br>

这里request.getAttribute("states"); 将为空,因为您还没有在您的servlet 中完成request.setAttribute("states", states);。导致java.lang.NullPointerException..


java.lang.NullPointerException 的可能机会:

  • 如果你直接运行jsp页面(ctrl+F11)。这里states 对象将不可用。
  • 如果states对象为null,那么在jsp中你有foreach循环来迭代states这将导致异常

你已经使用了两个ArrayList to hold onlystates`:

  1. States 类中: private List&lt;String&gt; state = new ArrayList&lt;&gt;();
  2. CustomerServlet servlet: private List&lt;edu.witc.Assignment03.model.States&gt; states = new ArrayList&lt;States&gt;();

一个ArrayList 就足够了。

最终解决方案

CustomerServlet 类的更改来自:

private List&lt;edu.witc.Assignment03.model.States&gt; states = new ArrayList&lt;States&gt;();

private edu.witc.Assignment03.model.States states = new States();

然后将其添加到请求中,以便 states 在 jsp、doGet() 或任何应将 states 添加到请求中的位置可用,例如:

 request.setAttribute("states", states);

并在您的 jsp 渲染选项中,例如:

State:<br>
        <select>
            <%
            edu.witc.Assignment03.model.States states = request.getAttribute("states");
            if(states!=null){   
            for (String state : states.getStates()) { 
                   out.println("<option>"+state+"</option>");
               }
             }else{
                 System.out.print("states is null");
             }
             %>
        </select><br>

注意:

最后但并非最不重要的一点是,请避免在 jsp 中使用 script-let 而使用 jstl to render easily

【讨论】:

  • 好的,所以我替换了服务器中的内容来设置属性,就像你说的那样,我仍然得到一个空指针
  • @user3457789 什么时候出现空指针异常?您在哪个网址提出请求?
  • @user3457789 我想你直接运行你的jsp?
  • 非常感谢@Rembo。这是一个非常详细的答案。我真的很感激。
猜你喜欢
  • 2014-05-10
  • 1970-01-01
  • 2013-09-12
  • 1970-01-01
  • 1970-01-01
  • 2011-05-20
  • 2013-11-15
  • 2021-08-03
  • 2013-11-08
相关资源
最近更新 更多