user3457789
user3457789

Reputation: 21

Get Arraylist To Fill Out Option List(Model To Servlet To Jsp)

I have a model, servlet, and jsp page. I want to give the option list all of the options in the array list but for some reason I am getting a null pointer exception.

Can someone help me figure out where I am going wrong BELOW IS MY CODE:

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

Model

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

Null Pointer Exception(after the customer button is clicked)

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)

Upvotes: 0

Views: 1565

Answers (1)

Abhishek Nayak
Abhishek Nayak

Reputation: 3748

Look here:

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>

here request.getAttribute("states"); will be null, cause you have not done request.setAttribute("states", states); in your servlet. that cause the java.lang.NullPointerException..


Possible chances of java.lang.NullPointerException :

  • if you running directly the jsp page(ctrl+F11). Here states object will not available in request.
  • if states object is null, then in jsp you have foreach loop to iterate states this will cause exception

you have used two ArrayList to hold onlystates`:

  1. In States class: private List<String> state = new ArrayList<>();
  2. and in CustomerServlet servlet: private List<edu.witc.Assignment03.model.States> states = new ArrayList<States>();

where one ArrayList is sufficient.

Final solution

change in CustomerServlet class from:

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

to

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

then add it to request so that states will available in jsp, in doGet() or anywhere that should adds states to request like:

 request.setAttribute("states", states);

and in your jsp render option like:

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>

Note:

Last but not least please avoid script-lets in jsp instead use jstl to render easily

Upvotes: 1

Related Questions