Spring web application- java.lang.NullPointerException with jdbcTemplate - spring

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.

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.

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

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

Spring Injection with Servlets: NoSuchBean

New to Spring, and working with Spring 3.2.5 trying to get injection to work with a servlet in a vanilla web app (i.e., it's not a Spring MVC web app - it's a pre-existing app I'm extending using the Spring framework). The container is Tomcat 7.0.47.
My problem is that I'm getting NoSuchBeanDefinitionException errors (No bean named 'MyServlet' is defined) when I hit the servlet. There are no errors at startup, so at least one of my beans (the ServiceImplementation bean) is getting successfully instantiated. The problem appears to be with finding the HttpRequestHandler-derived bean (MyServlet) when a new HTTP request comes in.
The full stack trace for the exception is:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'MyServlet' is defined
org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:570)
org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1114)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:279)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1121)
org.springframework.web.context.support.HttpRequestHandlerServlet.init(HttpRequestHandlerServlet.java:58)
com.random.webapp.MySpringServlet.init(Unknown Source)
javax.servlet.GenericServlet.init(GenericServlet.java:160)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
java.lang.Thread.run(Thread.java:662)
I followed this pattern for my setup:
http://andykayley.blogspot.com/2008/06/how-to-inject-spring-beans-into.html
...with one minor (I think) twist. I have a class derived from HttpRequestHandlerServlet so that I can override the init method with some application-specific stuff. The extension class looks like this:
public class MySpringServlet extends HttpRequestHandlerServlet
{
public void init() throws ServletException
{
super.init();
appSpecificInit();
}
}
The servlet I want injected looks like this:
public class MyServlet implements HttpRequestHandler
{
private IService _service = null;
public void setService( IService theService ) {
_service = theService;
}
#Override
public void handleRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
_service.DoSomething();
}
}
The implementation I want it injected with looks like this:
public class ServiceImplementation implements IService
{
#Override
public void DoSomething()
{
// some code goes here
}
}
These are the relevant entries in web.xml:
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml /WEB-INF/implementation.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.random.webapp.MySpringServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/myservlet/*</url-pattern>
</servlet-mapping>
</web-app>
This is the applicationContext.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="MyServlet" class="com.random.webapp.MyServlet">
<property name="Service" ref="ServiceImplementation" />
</bean>
</beans>
...and this is what implementation.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ServiceImplementation" class="com.random.webapp.ServiceImplementation">
</bean>
</beans>
I've been back and forth between the web.xml, applicationContext.xml, and implementation.xml files to double and triple check my configuration, and I don't see anything wrong with any of them, but I'm obviously missing something.
Anyone have any ideas?
The exception you are getting
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'MyServlet' is defined
occurs in the init() method of the HttpRequestHandlerServlet which tries to load a delegate HttpRequestHandler object from your context based on the name you give the HttpRequestHandlerServlet in your web.xml
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.random.webapp.MySpringServlet</servlet-class>
</servlet>
In the configuration above, that would be MyServlet. Although it appears you have it correct in
<bean id="MyServlet" class="com.random.webapp.MyServlet">
<property name="Service" ref="ServiceImplementation" />
</bean>
make sure you are loading the correct context file as declared here
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml /WEB-INF/implementation.xml</param-value>
</context-param>

#Autowired is not working with jersey and spring

When I am running test at that time #Autowired is working but when I run the web app and try to fetch data at that time its throwing null pointer exception.
this is my controller
In this BuyerRepo is always null
import com.retail.exception.InvalidIdException;
import com.retail.model.Buyer;
import com.retail.repository.BuyerRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
#Path("/buyer")
#Component
public class BuyerController {
#Autowired
private BuyerRepo buyerRepo;
#GET
#Produces("application/json")
public Buyer searchFields() throws InvalidIdException {
String buyerId = "51";
Buyer buyer;
try {
buyer = buyerRepo.getBuyer(Long.parseLong(buyerId));
} catch (NumberFormatException e) {
buyer = buyerRepo.getBuyer(buyerId);
}
return buyer;
}
}
In repository entity manager is always null
this is buyerRepository
import com.retail.exception.InvalidIdException;
import com.retail.model.Buyer;
import org.springframework.stereotype.Repository;
import javax.persistence.NoResultException;
#Repository
public class BuyerRepo extends AbstractRepository {
public Buyer getBuyer(String buyerName) throws InvalidIdException {
javax.persistence.Query buyerId = entityManager.createNativeQuery("select b.buyer_id from buyer b where b.name = :name").setParameter("name", buyerName);
Integer id;
try {
id = (Integer) buyerId.getSingleResult();
} catch (NoResultException e) {
return null;
}
return getBuyer(id);
}
public Buyer getBuyer(long buyerId) throws InvalidIdException {
Buyer buyer = entityManager.find(Buyer.class, buyerId);
if (buyer == null) throw new InvalidIdException("Invalid Article ID");
return buyer;
}
}
this is 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:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.retail"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost/retail"/>
<property name="username" value="retail_user"/>
<property name="password" value="password"/>
</bean>
<bean id="entityManagerOne" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.retail"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect"/>
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerOne"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
this is servlet-context.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:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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">
<mvc:annotation-driven />
<context:annotation-config />
<context:component-scan base-package="com.retail" />
</beans>
this is web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 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_5.xsd">
<servlet>
<servlet-name>retail</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.retail.web</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>retail</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
/WEB-INF/servlet-context.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>/WEB-INF/views/index.jsp</welcome-file>
</welcome-file-list>
</web-app>
You have to wire a interface instead of class. so there are two ways:
To let BuyerRepo to implement one interface
Useing #Inject or #Resource instead of #Autowired
I Have encountered this situation,
you need to add some jar file
gradle project:
compile group: 'org.glassfish.jersey.ext', name: 'jersey-spring3', version: '2.22.2'
maven project:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
<version>2.22.2</version>
</dependency>
another solution is web.xml file:
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>cn.ice</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
You can try using the SpringServlet instead of the jersey provided servlet container to achieve Jersey-Spring integration.
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
The documentation for this class states :
A servlet or filter for deploying root resource classes with Spring integration.
This class extends ServletContainer and initiates the WebApplication with a Spring-based
IoCComponentProviderFactory, SpringComponentProviderFactory, such that instances of resource and provider
classes declared and managed by Spring can be obtained.
Classes of Spring beans declared using XML-based configuration or auto-wire-based confguration will be
automatically registered if such classes are root resource classes or provider classes. It is not necessary to provide
initialization parameters for declaring classes in the web.xml unless a mixture of Spring-managed and Jersey-
managed classes is required.
The servlet supports configuration of child applicationContexts, see CONTEXT_CONFIG_LOCATION.
Looks like your buyerRepo has no public setter. It's also not possible to set it through the constructor. How about write a setter for it and put the #Autowired annotation on the setter instead. Like this:
#Repository
public class BuyerRepo extends AbstractRepository {
private BuyerRepo buyerRepo;
#Autowired
public void setBuyerRepo(BuyerRepo buyerRepo)
{
this.buyerRepo = buyerRepo;
}
//...Other code is omitted.
}

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.

Resources