0
votes

I dont know what is wrong in my listContacts in controller map.put("contactList", contactService.listContact()); Can somebody help me?

SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/test] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause java.lang.NullPointerException at pl.ivmx.contact.controller.ContactController.listContacts(ContactController.java:26) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:436) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:424) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778) at javax.servlet.http.HttpServlet.service(HttpServlet.java:621) at javax.servlet.http.HttpServlet.service(HttpServlet.java:722) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722)

package pl.ivmx.contact.controller;

import java.util.Map;    
import pl.ivmx.contact.dao.ContactDAO;
import pl.ivmx.contact.form.Contact;
import pl.ivmx.contact.service.ContactService;    
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ContactController {

    @Autowired
    private ContactService contactService;

    @RequestMapping("/contact")
    public String listContacts(Map<String, Object> map) {
        map.put("contact", new Contact());
        map.put("contactList", contactService.listContact());       

        return "/contact";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("contact") Contact contact,
            BindingResult result) {

        contactService.addContact(contact);

        return "redirect:/contact";
    }

    @RequestMapping("/delete/{contactId}")
    public String deleteContact(@PathVariable("contactId") Integer contactId) {

        contactService.removeContact(contactId);

        return "redirect:/contact";
    }   
}

package pl.ivmx.contact.dao;

import java.util.List;

import pl.ivmx.contact.form.Contact;

public interface ContactDAO {

    public void addContact(Contact contact);
    public List<Contact> listContact();
    public void removeContact(Integer id);
}

package pl.ivmx.contact.dao;

import java.util.List;

import pl.ivmx.contact.form.Contact;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

@Repository
public class ContactDAOImpl implements ContactDAO {

    @Autowired
    private SessionFactory sessionFactory;

    public void addContact(Contact contact) {
        sessionFactory.getCurrentSession().save(contact);
    }

    public List<Contact> listContact() { 
        return  sessionFactory.getCurrentSession().createQuery("from Contact").list();      
    }

    public void removeContact(Integer id) {
        Contact contact = (Contact) sessionFactory.getCurrentSession().load(
                Contact.class, id);
        if (null != contact) {
            sessionFactory.getCurrentSession().delete(contact);
        }

    }
}

package pl.ivmx.contact.service;

import java.util.List;

import pl.ivmx.contact.form.Contact;

public interface ContactService {

    public void addContact(Contact contact);
    public List<Contact> listContact();
    public void removeContact(Integer id);
}

package pl.ivmx.contact.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pl.ivmx.contact.dao.ContactDAO;
import pl.ivmx.contact.form.Contact;

@Service
public class ContactServiceImpl implements ContactService {

    @Autowired
    private ContactDAO contactDAO;

    @Transactional
    public void addContact(Contact contact) {
        contactDAO.addContact(contact);
    }

    @Transactional
    public List<Contact> listContact() {
        return contactDAO.listContact();
    }

    @Transactional
    public void removeContact(Integer id) {
        contactDAO.removeContact(id);
    }  
}

package pl.ivmx.contact.form;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="CONTACTS")
public class Contact {

    @Id
    @Column(name="ID")
    @GeneratedValue
    private Integer id;

    @Column(name="FIRSTNAME")
    private String firstname;

    @Column(name="LASTNAME")
    private String lastname;

    @Column(name="EMAIL")
    private String email;

    @Column(name="TELEPHONE")
    private String telephone;


    public String getEmail() {
        return email;
    }
    public String getTelephone() {
        return telephone;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }
    public String getFirstname() {
        return firstname;
    }
    public String getLastname() {
        return lastname;
    }
    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }
    public void setLastname(String lastname) {
        this.lastname = lastname;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
}

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>WEB-INF/applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener> 

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>


    <welcome-file-list>
        <welcome-file>/pages/index.jsp</welcome-file>
    </welcome-file-list>

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:security="http://www.springframework.org/schema/security"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <context:annotation-config />
    <context:component-scan base-package="pl.ivmx.contact" />  

<!--    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="messages_en.properties" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean> -->


    <import resource="commonContext.xml" />

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <bean id="userTestDao" class="pl.ivmx.dao.impl.UserTestDaoImpl">
    <!--     <property name="dataSource" ref="dataSource" />   -->
        <property name="sessionFactory" ref="sessionFactory" />             
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >

    <!--    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> -->
        <property name="dataSource" ref="dataSource" />                 
         <property name="configLocation" value="META-INF/hibernate.cfg.xml" />    
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
    <!--    <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>      
            </props>
        </property>         
        <property name="annotatedClasses">
            <list>
                <value>pl.ivmx.model.UserTest</value>
            </list>
        </property>    -->     
    </bean>    


    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"                                 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd 
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

<!--  <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />    -->

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <bean id="urlMapping"
        class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">

        <property name="urlMap">
            <map>
                <entry key="/index.do"> <ref bean="index" /></entry>
                <entry key="/registration.do"> <ref bean="registration" /></entry>
                <entry key="/usertestlist.do"> <ref bean="usertest" /></entry>  
                <entry key="/contact.do"> <ref bean="contact" /></entry>        
            </map>
        </property>
    </bean>

    <bean id="index" class="pl.ivmx.web.IndexController"/>

        <bean id="registrationValidator" class="pl.ivmx.validation.RegistrationValidator" />  
        <bean id="registration" class="pl.ivmx.web.RegistrationFormController" >                 
            <property name="commandName"><value>userTest</value></property> 
            <property name="commandClass"><value>pl.ivmx.model.UserTest</value></property> 
            <property name="validator"><ref local="registrationValidator"/></property>  
            <property name="formView"><value>registration</value></property> 
            <property name="successView"><value>registrationsuccess</value></property> 
            <property name="userTestDao"><ref bean="userTestDao"/></property>               
        </bean>     

        <bean id="usertest" class="pl.ivmx.web.UserTestController">                  
             <property name="userTestDao"><ref bean="userTestDao"/></property>          
        </bean>     

    <bean id="contact" class="pl.ivmx.contact.controller.ContactController">
    </bean>

    <bean id="contactService" class="pl.ivmx.contact.service.ContactServiceImpl">
    </bean>
    <bean id="contactDAO" class="pl.ivmx.contact.dao.ContactDAOImpl">
    </bean>

</beans>
4

4 Answers

2
votes

It looks like a NullPointerException thrown in the method here:

@RequestMapping("/contact")
public String listContacts(Map<String, Object> map) {
    map.put("contact", new Contact());
    map.put("contactList", contactService.listContact());       

    return "/contact";
}

I would debug and check that contactService has been autowired correctly.

The null pointer is line 26, if that is the line containing contactService.listContact() then contactService is null. If it is the line above then the map is null.

I am not sure but try adding:

<context:component-scan base-package="pl.ivmx.contact" />

to the dispatcher-servlet.xml as well, it could be that the annotation isnt getting processed

1
votes

you are returning "/contact" there in the method as a view to be shown:

@RequestMapping("/contact")
public String listContacts(Map<String, Object> map) {
    map.put("contact", new Contact());
    map.put("contactList", contactService.listContact());       

    return "/contact"; // <---- here!
}

This means that you should have a view named /contact defined somewhere, but I don't see it. You need to have a view that corresponds with the value you're defining.

You probably want to return a value like "contact" instead of "/contact" and then have contact.jsp in the webapp/WEB-INF/views folder (assuming you use maven standard directory layout).

0
votes

I don't see anything obvious ... could sessionFactory be null? Should be easy to find, tho. Step through the code in the debugger.

0
votes

I think you are missing to add the contactService bean to your applicationContext.xml try adding the below to tags

<bean id="contactService" class="pl.ivmx.contact.service.ContactServiceImpl">
<property name="contactDAO" ref="contactDAO" />
</bean>

<bean id="contactDAO" class="pl.ivmx.contact.dao.ContactDAOImpl" />