有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java获取Arraylist以填写选项列表(从模型到Servlet再到Jsp)

我有一个模型、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>

servlet

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)

共 (1) 个答案

  1. # 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对象为空,那么在jsp中您有foreach循环来迭代states,这将导致异常

    您使用了两个ArrayList to hold only状态`:

    1. States类中:private List<String> state = new ArrayList<>();
    2. CustomerServletservlet中: private List<edu.witc.Assignment03.model.States> states = new ArrayList<States>();

    其中一个ArrayList就足够了

    最终解决方案

    CustomerServlet类中的更改来自:

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

    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中的脚本let使用jstl to render easily