Request processing failed; nested exception is java.lang.NullPointerException with root cause java.lang.NullPointerException - spring

Here is a brief description of what I am doing.
The application has the form elements in JSP which redirects to the Controller class after pressing submit. The controller calls the service layer which in turn calls DAO and finally adds the records to the data base. The issue I am having is that in the Controller class, I can receive the request parameters (POST) but the thing is that there is an issue while calling the addStudent() of the service layer. The issue is with the Null Pointer Exception on object. Could you guys review the code and provide me suggestions?
Here is the full Stacktrace, throwing errors with pointing the object, i.s nullPointerException.
INFO: Server startup in 4385 ms
Apr 28, 2014 11:45:38 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [springDispatcher] in context with path [/StudentManagementSystem] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.vastika.controllers.SpringController.addStudent(SpringController.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:646)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
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.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2441)
at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2430)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Here are the codes
SpringController class
package com.vastika.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.vastika.student.model.StudentModel;
import com.vastika.student.services.StudentServiceImpl;
#Controller
#RequestMapping("/students/*")
public class SpringController {
private StudentServiceImpl studentService;
public void setStudentService(StudentServiceImpl studentService) {
this.studentService = studentService;
}
#RequestMapping(value = "/students/addstud", method = RequestMethod.POST)
public String addStudent(#RequestParam(value = "name") String name,
#RequestParam(value = "age") String age,
#RequestParam(value = "address") String address,
#RequestParam(value = "email") String email) {
StudentModel student = new StudentModel();
student.setName(name);
student.setAge(age);
student.setAddress(address);
student.setEmail(email);
if (studentService.addStudentService(student)) {
return "Student is added to the database";
}
return "Student is not added to the database";
}
}
StudentServiceImpl Class
package com.vastika.student.services;
import java.util.List;
import com.vastika.student.dao.StudentDaoImpl;
import com.vastika.student.model.StudentModel;
public class StudentServiceImpl implements IStudentService {
private StudentDaoImpl studentDao;
public void setStudentDao(StudentDaoImpl studentDao) {
this.studentDao = studentDao;
}
#Override
public boolean addStudentService(StudentModel student) {
if(studentDao.addStudentDao(student)){
return true;
}
return false;
}
#Override
public boolean delStudentService(int id) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean updateStudentService(StudentModel student) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean getStudentByIdService(int id) {
// TODO Auto-generated method stub
return false;
}
#Override
public List<StudentModel> getAllStudentsService() {
// TODO Auto-generated method stub
return null;
}
}
Model Class:
package com.vastika.student.model;
public class StudentModel {
private int studentId;
private String name;
private String age;
private String address;
private String email;
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
spring.xml file
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="student" class="com.vastika.student.model.StudentModel"/>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
<bean id="studentService" class="com.vastika.student.services.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean>
<bean id="studentDao" class="com.vastika.student.dao.StudentDaoImpl"/>
<bean id="studentController" class="com.vastika.controllers.SpringController">
<property name="studentService" ref="studentService"></property>
</bean>
</beans>
springdispatcher-servlet.xml file
<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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<context:component-scan base-package="com.vastika.controllers" />
<!-- <bean id="studentService" class="com.vastika.student.services.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean>
<bean id="studentDao" class="com.vastika.student.dao.StudentDaoImpl"/>
<bean id="studentModel" class="com.vastika.student.model.StudentModel"/> -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
web.xml file
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springDispatcher-servlet.xml;classpath:spring.xml</param-value>
</context-param>
<servlet>
<servlet-name>springDispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
-->
</web-app>
index.jsp file
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springDispatcher-servlet.xml;classpath:spring.xml</param-value>
</context-param>
<servlet>
<servlet-name>springDispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
-->
</web-app>

Check whether the Deployment Descriptor is 3.1 or not, I suppose you have 2.4 version as your Deployment Descriptor which is why the Apache Tomcat could not run.
Then check whether web.xml is placed under
Deployed Resources/WEB-INF/web.xml

Related

Convert Spring LocalSessionFactoryBean to Hibernate SessionFactory

I am trying to Integrate Spring with Hibernate. However, I am not able to get Hibernate's SessionFactory Object through Spring's LocalSessionFactoryBean.
I tried the following approaches:
1) Use either of org.springframework.orm.hibernate3 and org.springframework.orm.hibernate4 LocalSessionFactoryBean class
2) Use AbstractSessionFactoryBean class
3) Try with SessionFactory=LocalSessionFactoryBean.getObject() as well as SessionFactory=LocalSessionFactoryBean
Here's the Project Structure:
Not allowed to post images till I reach 10 credits, sad..
Here 's the BookService
package com.zzz.service;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.AbstractSessionFactoryBean;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import com.zzz.forms.BookForm;
public class BookService {
#Autowired
LocalSessionFactoryBean hibernateSessionFactory;
SessionFactory sessionFactory;
public LocalSessionFactoryBean getHibernateSessionFactory() {
return hibernateSessionFactory;
}
public void setHibernateSessionFactory(LocalSessionFactoryBean hibernateSessionFactory) {
this.hibernateSessionFactory = hibernateSessionFactory;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void storeBookDetails(BookForm bookForm){
System.out.println("Hibernae");
setSessionFactory((SessionFactory)hibernateSessionFactory.getObject());
Session session=sessionFactory.openSession();
session.beginTransaction();
session.save(bookForm);
session.getTransaction().commit();
session.close();
System.out.println("Hibernae");
}
}
Here's The Controller that leads to this service
package com.zzz.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.zzz.forms.BookForm;
import com.zzz.service.BookService;
#Controller
public class FirstPageController {
BookService bookService;
public BookService getBookService() {
return new BookService();
}
public void setBookService(BookService bookService) {
this.bookService = bookService;
}
#RequestMapping(value="/firstPage")
public ModelAndView showFirstPage()
{
return new ModelAndView("books/Book","BookForm",new BookForm());
}
#RequestMapping(value="/enterBookDetails")
public ModelAndView enterBookDetails(#ModelAttribute("BookForm") BookForm bookForm)
{
getBookService().storeBookDetails(bookForm);
System.out.println("BOOK DETAILS ARE AS FOLLOWWS");
System.out.println(bookForm.getBookId());
System.out.println(bookForm.getBookName());
return new ModelAndView("books/BookSubmitted","BookForm",bookForm);
}
}
Application Context:
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:hz="http://www.hazelcast.com/schema/spring"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.hazelcast.com/schema/spring
http://www.hazelcast.com/schema/spring/hazelcast-spring-3.2.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.zzz.controllers"></context:component-scan>
<mvc:annotation-driven/>
<bean id="myDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost/zz" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="hibernateSessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.zzz.forms"/>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
</value>
</property>
</bean>
</beans>
And The 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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>ZZZ</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:ApplicationContext.xml</param-value>
</context-param>
</web-app>
The NullPointer Looks like this
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.NullPointerException
com.zzz.service.BookService.storeBookDetails(BookService.java:38)
com.zzz.controllers.FirstPageController.enterBookDetails(FirstPageController.java:39)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
It seems that LocalSessionFactoryBean is not getting injected, but I cannot figure out the reason.
Any kind of help would be appreciated.
The NPE has nothing to do with your hibernate set-up. In your controller you create a new book service using new BookService() in your getBookService() method. This is incorrect. You need to define a bean for the book service in your spring configuration, inject that bean into your controller (either directly or using an annotation) and use that bean in your controller. You already defined a BookService property, so you are almost there.

Spring RESTful and Hibernate

I have a very simple database in postgres and i have used hibernate to "connect" to it. Everything works fine, i tested the database with hibernate and no problems so far.
Here is my DAO
#Repository("clientsBasicDao")
#Transactional
public class ClientsBasicDaoImpl implements ClientsBasicDao {
private Log log = LogFactory.getLog(ClientsBasicDaoImpl.class);
private SessionFactory sessionFactory;
private Session session;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
#Resource(name="sessionFactory")
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
session = sessionFactory.openSession();
}
#SuppressWarnings("unchecked")
#Transactional(readOnly=true)
public List<ClientsBasic> findAllClients() throws HibernateException{
return session.createQuery("from ClientsBasic").list();
}
public ClientsBasic findClientById(int id) throws HibernateException {
return (ClientsBasic) session.
getNamedQuery("ClientsBasic.findById").setParameter("id", id).uniqueResult();
}
public ClientsBasic findClientByEmail(String email) throws HibernateException{
return (ClientsBasic) session.
getNamedQuery("ClientsBasic.findByEmail").setParameter("email", email).uniqueResult();
}
#SuppressWarnings("unchecked")
public List<ClientsBasic> findDirectClients() throws HibernateException{
return session.getNamedQuery("ClientsBasic.findDirectClients").list();
}
#SuppressWarnings("unchecked")
public List<ClientsBasic> findIndirectClients() throws HibernateException{
return session.getNamedQuery("ClientsBasic.findIndirectClients").list();
}
public ClientsBasic save(ClientsBasic client) throws HibernateException {
Transaction tx = null;
tx = session.beginTransaction();
session.saveOrUpdate(client);
tx.commit();
log.info("Client saved with id: " + client.getClientId());
return client;
}
public void delete(ClientsBasic client) throws HibernateException {
Transaction tx = null;
tx = session.beginTransaction();
Set<Resources> res = client.getClientResources();
if(res.size() > 0){ //there are client access resources for this client
Iterator<Resources> it = res.iterator();
while(it.hasNext()){
Resources resource = it.next();
resource.getClientsBasics().remove(client);
}
}
session.delete(client);
tx.commit();
log.info("Client deleted with id: " + client.getClientId());
}
}
Now, i am trying to learn restful web services so after some tutorials i tried my own implementation. It works, except when i try to use the method that connects to the database.
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
//http://localhost:8080/TestProject/greeting
// or
//http://localhost:8080/TestProject/greeting?name=stackoverflow
#RequestMapping("/greeting")
public #ResponseBody String greeting(
#RequestParam(value="name", required=false, defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name)).toString();
}
//http://localhost:8080/TestProject/testing
#RequestMapping("/testing")
public #ResponseBody String home(){
return "Welcome, the server is now up and running!";
}
//http://localhost:8080/TestProject/client?id=1
#RequestMapping("/client")
public #ResponseBody String client( //FAILS HERE
#RequestParam(value="id", required=true) String id){
ClientServiceBackend cb = new ClientServiceBackend();
return cb.findClient(Integer.parseInt(id));
}
}
and here is the error
HTTP Status 500 - Handler processing failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
org.springframework.web.util.NestedServletException: Handler processing failed; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1284)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:965)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:931)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:822)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:807)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
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">
<display-name>test</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
and dispatcher:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.project.rest" />
<mvc:annotation-driven />
</beans>
like i said, i am trying to learn rest and this is my 2nd week with spring, so this is all kinda new to me, but i would expect this to work since the database is working fine!
NOTE: I am deploying this on Tomcat v7
can someone please give a hand here?
Thank you :-)
EDIT:
I added the hibernate jar to the tomcat classpath, and now the error is
The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'.

Initialization of collection throws LazyInitializationException

I have a problem with the access to a collection from JSP file. Application is based on MVC Spring framework. I put OpenSessionInViewFilter filter to my web.xml. When I want to access to URL with mentioned file, it throws me
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.app.cloud.hibernate.Product.availabilities, no session or session was closed
I use domain driven design in my app. When I changed fetch type in class Product from FetchType.LAZY to FetchType.EAGER, it worked.
stacktrace
SEVERE: Servlet.service() for servlet [spring] in context with path [] threw exception [org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.app.cloud.hibernate.Product.availabilities, no session or session was closed] with root cause
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.app.cloud.hibernate.Product.availabilities, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:380)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:372)
at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:119)
at org.hibernate.collection.PersistentSet.isEmpty(PersistentSet.java:169)
at org.apache.el.parser.AstEmpty.getValue(AstEmpty.java:55)
at org.apache.el.parser.AstNot.getValue(AstNot.java:44)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:1026)
at org.apache.jsp.WEB_002dINF.jsp.product.products_jsp._jspx_meth_c_005fwhen_005f0(products_jsp.java:321)
at org.apache.jsp.WEB_002dINF.jsp.product.products_jsp._jspx_meth_c_005fchoose_005f0(products_jsp.java:290)
at org.apache.jsp.WEB_002dINF.jsp.product.products_jsp._jspx_meth_c_005fforEach_005f0(products_jsp.java:233)
at org.apache.jsp.WEB_002dINF.jsp.product.products_jsp._jspx_meth_c_005fif_005f0(products_jsp.java:185)
at org.apache.jsp.WEB_002dINF.jsp.product.products_jsp._jspService(products_jsp.java:141)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
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.serviceJspFile(JspServlet.java)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
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.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:264)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:811)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:796)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.__invoke(StandardContextValve.java:123)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)
at org.apache.catalina.core.StandardHostValve.__invoke(StandardHostValve.java:171)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1686)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
web.xml
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>sessionFactoryBeanName</param-name>
<param-value>sessionFactory</param-value>
</init-param>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- Context parameters -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>WEB-INF/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jExposeWebAppRoot</param-name>
<param-value>false</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
</web-app>
spring-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven />
<tx:annotation-driven />
<context:component-scan base-package="com.app.cloud" />
<bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="spring-views" />
<property name="order" value="1" />
</bean>
<bean id="jspViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
<property name="order" value="2" />
</bean>
<!-- JDBC -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<!-- Hibernate -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
ProductService.java
#Transactional
public interface ProductService {
#Transactional
public void add(Product product);
#Transactional
public List<Product> getAll();
#Transactional
public Product get(Integer idProduct);
#Transactional
public void remove(Integer id);
#Transactional
public void edit(Product product);
}
ProductServiceImpl.java
#Service
#Transactional
public class ProductServiceImpl implements ProductService {
#Autowired
private ProductDAO productDAO;
#Transactional
public void add(Product product) {
productDAO.add(product);
}
#Transactional
public List<Product> getAll() {
return productDAO.getAll();
}
#Transactional
public void remove(Integer id) {
productDAO.remove(id);
}
#Transactional
public Product get(Integer idProduct) {
return productDAO.get(idProduct);
}
#Transactional
public void edit(Product product) {
productDAO.edit(product);
}
}
ProductDAO.java
public interface ProductDAO {
public void add(Product product);
public void edit(Product product);
public List<Product> getAll();
public Product get(Integer idProduct);
public void remove(Integer id);
}
ProductDAOImpl.java
#Repository
public class ProductDAOImpl implements ProductDAO {
#Autowired
private SessionFactory sessionFactory;
public void add(Product product) {
sessionFactory.getCurrentSession().save(product);
}
public List<Product> getAll() {
return sessionFactory.getCurrentSession().createQuery("from Product")
.list();
}
public void remove(Integer id) {
Product product = (Product) sessionFactory.getCurrentSession().load(
Product.class, id);
if (null != product) {
sessionFactory.getCurrentSession().delete(product);
}
}
public Product get(Integer idProduct) {
Product product = (Product) sessionFactory.openSession().get(
Product.class, idProduct);
return product;
}
#Override
public void edit(Product product) {
sessionFactory.getCurrentSession().update(product);
}
}
Product.java
#Entity
#Table(name = "product", catalog = "app")
public class Product implements java.io.Serializable {
private Integer idProduct;
#NotEmpty
#Length (min=1,max=70)
private String name;
private Set<Availability> availabilities = new HashSet<Availability>(0);
public Product() {
}
public Product(String name) {
this.category = category;
this.name = name;
this.lastUpdate = lastUpdate;
this.actionFlag = actionFlag;
}
public Product(String name,
Set<Availability> availabilities,
) {
this.name = name;
this.availabilities = availabilities;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id_product", unique = true, nullable = false)
public Integer getIdProduct() {
return this.idProduct;
}
public void setIdProduct(Integer idProduct) {
this.idProduct = idProduct;
}
#Column(name = "name", nullable = false, length = 70)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "product")
public Set<Availability> getAvailabilities() {
return this.availabilities;
}
public void setAvailabilities(Set<Availability> availabilities) {
this.availabilities = availabilities;
}
}
It's very classical error when working with Hibernate.
If you have any lazy-loading proxies your should replace them either with nulls or with real objects before returning from #Transactional context.
The Set or List that is lazy loaded is replaced by the Hibernate with the proxy. The proxy would load the collection first time it is accessed. But what if it is first accessed if you are outside the transactional context? The hibernate session that is referenced by the proxy doesn't exist so you have the error.
If you won't need the collection, set it to null or empty HashSet/ArrayList. If you would need it, call the size() or iterate through the element within transactional context. If you are not sure, provide the API for loading the connection. But don't return objects with uninitialized proxies.
Annotate your Controller as #Transactional. You wont see that error again, You bet!!
Note
Experts say that #Transactional is not to be used on Controller, But I didn't get an answer why?
You can try
#Proxy (lazy = false)
On top of both entity class. It works in my case.

Spring: How to define database config?

I try to execute simple request to MySql database via jdbcTemplate but I have an error when framework load and parse xml file whicj define my datasource:
<?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:util="http://www.springframework.org/schema/util"
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.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring_training"/>
<property name="username" value="root"/>
<property name="password" value="pass"/>
</bean>
</beans>
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">
<display-name>SpringTrainingTemplate</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml /WEB-INF/jdbc-config.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
and Controller that invoke it:
#Controller
public class HomeController {
#Autowired
private ExampleService exampleService;
#RequestMapping(value = "/details", method = RequestMethod.GET)
public String details(Model model) {
ApplicationContext context = new ClassPathXmlApplicationContext("jdbc-config.xml");
ExampleDao dao = (ExampleDao) context.getBean("ExampleDao");
List<Application> list = dao.getAllApplications();
model.addAttribute("application", list.get(0).getName());
model.addAttribute("descriptionOfApplication", list.get(0).getDescription());
return "details";
}
}
public class ExampleDao {
private String request = "select * from application";
private JdbcTemplate jdbcTemplate;
#Autowired
private DataSource dataSource;
public ExampleDao(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<Application> getAllApplications() {
List<Application> applications = this.jdbcTemplate.query(request, new RowMapper<Application>() {
#Override
public Application mapRow(ResultSet rs, int i) throws SQLException {
Application application = new Application();
application.setName(rs.getString("name"));
application.setType(rs.getString("type"));
application.setDescription(rs.getString("description"));
application.setDownloads(rs.getInt("downloads"));
return application;
}
});
return applications;
}
}
Whe I run it and input http://localhost:8080/details I have got an 500 exception with stacktrace with this message:
root cause
org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [jdbc-config.xml]; nested exception is java.io.FileNotFoundException: class path resource [jdbc-config.xml] cannot be opened because it does not exist
Can you explain me how to configure jdbc connection in rigth way or if my approach is correct where I should look for a solution of my issue? All help would be appreciated. Thanks.
Spring cannot find your jdbc-config.xml configuration file.
You can put it in your classpath instead of the WEB-INF folder and load it in your web.xml like this:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-config.xml,classpath:jdbc-config.xml</param-value>
</context-param>
A good practice is to create folders main and resources in your src folder and to add them in the classpath. Then you can put the spring config file in the src/resources folder.
class path resource [jdbc-config.xml] cannot be opened because it does
not exist
Is the file name correct, where is it located? the file specifying the db connection is not where you said it should be - on the classpath.

Spring web application- java.lang.NullPointerException with jdbcTemplate

I am writing a simple spring 3.0 restful webservice with jdbcTemplate
but i get a java.lang.NullPointerException each time i try to access a resource.
I have created a DAO like this
public interface MisCodeDao {
public void setDataSource(DataSource ds);
//the remaining method declarations
}
}
And my DAOImpl like this
public class MisCodeDAOImp implements MisCodeDao {
private JdbcTemplate jdbcTemplate;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public List<MisCode> findAll() throws MisCodeDAOException {
if(this.jdbcTemplate==null)
{
System.out.print("JDBC TEMPLATE IS NULL");
}
return (List<MisCode>) this.jdbcTemplate.query("SELECT misCode, misClass, codeDesc, active from miscode", new RowMapper<MisCode>() {
public MisCode mapRow(ResultSet resultSet, int row) throws SQLException {
MisCode miscode = new MisCode();
miscode.setMisCode(resultSet.getString("misCode"));
System.out.print(resultSet.getString("misCode"));
miscode.setMisClass(resultSet.getString("misClass"));
miscode.setCodeDesc(resultSet.getString("codeDesc"));
String charValueStr=resultSet.getString("active");
miscode.setActive(charValueStr.charAt(0));
return miscode;
}
});
}
Here is what my application-context.xml looks like
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util/spring-util-3.0.xsd">
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driver}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="misCodeDAO" class="com.tavia.bacponline.DaoImpl.MisCodeDAOImp">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
The full stack strace is here:
WARNING: StandardWrapperValve[bacponline]: PWC1406: Servlet.service() for servlet bacponline threw exception
java.lang.NullPointerException
at com.tavia.bacponline.DaoImpl.MisCodeDAOImp.findAll(MisCodeDAOImp.java:67)
at com.tavia.bacponline.controller.MisCodeController.getMisCodes(MisCodeController.java:45)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:174)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:421)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:409)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
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 com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
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:619)
Here is my controller:
#Controller
public class MisCodeController {
private Jaxb2Marshaller jaxb2Mashaller;
public void setJaxb2Mashaller(Jaxb2Marshaller jaxb2Mashaller) {
this.jaxb2Mashaller = jaxb2Mashaller;
}
private static final String XML_VIEW_NAME = "miscodes";
private MisCodeDAOImp miscodeImpl = new MisCodeDAOImp();
#RequestMapping(method=RequestMethod.GET, value="/miscodes")
public ModelAndView getMisCodes() throws MisCodeDAOException {
List<MisCode> miscodes = miscodeImpl.findAll();
MisCodeList list = new MisCodeList(miscodes);
return new ModelAndView(XML_VIEW_NAME, "miscodes", list);
}
}
And my web.xml looks like this
<?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">
<display-name>com.tavia.bacponline</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/bacponline-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>bacponline</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>bacponline</servlet-name>
<url-pattern>/service/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
</web-app>
Thanks
I may be missing something in your post... but here goes...
The Controller is an annotation based, please indicate the same to spring in the app context file.. also indicate the components to be scanned using
Rather than using
private MisCodeDAOImp miscodeImpl = new MisCodeDAOImp();
use the following for autowiring
#Autowire
private MisCodeDAOImp miscodeImpl;
Since you have already defined the bean in app context file, it should autowire.

Resources