0

I tried to change my Spring MVC Form Controller to Annotation Controller but i've got some problems.

When i deploy my app on my glassfish server, i've got the following error when i would like acces to hello.htm

Avertissement: StandardWrapperValve[dispatcher]: PWC1406: Servlet.service() for servlet dispatcher threw exception
java.lang.NullPointerException
at hibernateTest.web.InventoryController.getClient(InventoryController.java:38)
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:668)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:770)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at     com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)

This is my web.xml :

<?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_2_5.xsd" 
     id="WebApp_ID" 
     version="2.5">

<context-param> 
    <param-name>contextConfigLocation</param-name>
    <param-value>
        /WEB-INF/dispatcher-servlet.xml, /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>*.htm</url-pattern>
</servlet-mapping>

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

dispatcher-servlet.xml :

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
  default-autowire="byName">

<context:component-scan base-package="hibernateTest.web" />

<context:annotation-config/>

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
      p:prefix="/WEB-INF/jsp/" 
      p:suffix=".jsp" />

<bean id="propertyConfigurer" 
      class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:jdbc.properties</value>
        </list>
    </property>
</bean> 

InventoryController :

import com.mysql.jdbc.Constants;
import hibernateTest.service.ProductManager;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class InventoryController { 

protected final Log logger = LogFactory.getLog(getClass()); 

private ProductManager productManager; 

public void setProductManager(ProductManager productManager) {
    this.productManager = productManager;
} 

@RequestMapping(value="/hello.htm",method = RequestMethod.GET)
public String getClient(ModelMap model) {

    logger.info("returning hello view"); 
    model.addAttribute("products", this.productManager.getProducts());
    return "hello"; 
}
 }

SimpleProductManager :

import hibernateTest.domain.Product; 
import hibernateTest.repository.ProductDao;
 import java.util.List; 
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

@Service()
public class SimpleProductManager implements ProductManager { 

protected final Log logger = LogFactory.getLog(getClass()); 

private ProductDao productDao; 

public void increasePrice(int percentage) {

    List<Product> products = productDao.getProductList();

    if (products != null) {

        for (Product product : products) {

            double newPrice = product.getPrice().doubleValue() * (100 + percentage)/100;
            product.setPrice(newPrice);
            productDao.saveProduct(product);

        }

    }

} 

public void createProduct(String description, Double price) {

    Product prod = new Product();

    prod.setDescription(description);
    prod.setPrice(price);

    logger.info("Class SimpleProductManager - Description set to " + description);
    logger.info("Class SimpleProductManager - Price set to " + price);

    productDao.insertProduct(prod);

}

public List<Product> getProducts() {

    return productDao.getProductList();

} 

public void setProductDao(ProductDao productDao) {

    this.productDao = productDao;

} 
}

JdbcProductDao :

import hibernateTest.domain.Product;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List; 

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.stereotype.Repository;

@Repository
public class JdbcProductDao extends JdbcDaoSupport implements ProductDao { 

/** Logger for this class and subclasses */
protected final Log logger = LogFactory.getLog(getClass()); 

public List<Product> getProductList() {

    logger.info("Getting products!");

    List<Product> products = getJdbcTemplate().query(
            "select id, description, price from products", 
            new ProductMapper());

    return products;

} 

public void saveProduct(Product prod) {

    logger.info("Saving product: " + prod.getDescription());

    int count = getJdbcTemplate().update(
            "update products set description = ?, price = ? where id = ?",
            new Object[]{prod.getDescription(), prod.getPrice(), prod.getId()});

    logger.info("Rows affected: " + count);

}    

public void insertProduct(Product prod) {

    logger.info("Inserting product: " + prod.getDescription());

    getJdbcTemplate().update(
            "insert into products (description, price) values (?, ?)",
            new Object[]{prod.getDescription(), prod.getPrice()});

    logger.info("Inserting product " + prod.getDescription() + "ok");

}
private static class ProductMapper implements ParameterizedRowMapper<Product> { 

    public Product mapRow(ResultSet rs, int rowNum) throws SQLException {

        Product prod = new Product();

        prod.setId(rs.getInt("id"));
        prod.setDescription(rs.getString("description"));
        prod.setPrice(new Double(rs.getDouble("price")));

        return prod;

    } 

} 

}

Thanks for helping !

1
  • 1
    It looks like you need to @Autowire product manager in InventoryController Commented Nov 15, 2012 at 14:21

2 Answers 2

1

You need to tell the controller what ProductManager is by Autowiring it.

@autowired private ProductManager productManager;

Sign up to request clarification or add additional context in comments.

10 Comments

same thing with ProductDAO. It also needs to be autowired. Spring doesn't know to inject these objects without instruction
@autowired ProductDAO in SimpleProductManager class ?
yes, you need to tell Spring that you want that class to be autowired s well @autowired private ProductDao productDao;
Ok, i have put @Autowired private ProductManager productManager in my InventoryController class and @Autowired private ProductDao productDao in my SimpleProductManager class but i've got these errors on deploying the app Error creating bean with name 'inventoryController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private hibernateTest.service.ProductManager hibernateTest.web.InventoryController.productManager; And the same error for SimpleProductManager
But it works if i only @autowired private ProductManager productManager
|
0

bean should be declared in spring context config XML.

 <bean id="productDao" class="JdbcProductDao"/>

And pay attention to

<context:component-scan base-package="hibernateTest.web" />

Make sure packages contains annotation config all included.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.