I have a class StudentWithAddress which is getting binded with the values filled in a form. I have autowired a MessageSource in it. but i am getting NullPointerException while using it.
web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Spring Try App</display-name>
<servlet>
<servlet-name>front-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>front-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
front-dispatcher-servlet.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:p="http://www.springframework.org/schema/p"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop = "http://www.springframework.org/schema/aop"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- Now i will use annotation based controller and mapping. Therefore i wont be needing a
handler bean declaration and the controller bean declaration here.
<bean id="handlerMapping" class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean name="/helloMessagePage" class="com.manya.spring.HelloMessageController"/> -->
<aop:aspectj-autoproxy/>
<context:component-scan base-package="com.manya.spring.modelattribute, com.manya.spring"/>
<mvc:annotation-driven/>
<context:annotation-config/>
<bean class="org.manya.springmvc.aspect.LoggingAspect"/>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>/WEB-INF/strings.properties</value>
</list>
</property>
</bean>
<bean id="vieResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
StudentWithAddress.java :
package com.manya.spring.modelattribute;
import java.util.Date;
import javax.validation.constraints.Size;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
#Component
#Scope("prototype")
public class StudentWithAddress {
public StudentWithAddress()
{
System.out.println("from the constructor of the StudentWithAddress");
}
private String name;
#Autowired
private MessageSource messageSource;
//This tells the spring the size constraint on the hobby field.
#Size(min=2,max=15)
private String hobby;
private Date dob;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public void usingMessageSourse()
{
System.out.println(messageSource.getMessage(name, null, null));
}
}
ModelAtributeContinuedController.java :
package com.manya.spring.modelattribute;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping("/studentWithAddressAdmission")
public class ModelAttributeContinuedController {
#InitBinder
public void nameCustomeEditor(WebDataBinder binder)
{
binder.registerCustomEditor(String.class, "name", new CustomNameEditor());
}
#RequestMapping(value="/enterDetails", method=RequestMethod.GET)
public ModelAndView admissionForm()
{
ModelAndView mv = new ModelAndView("StudentWithAddressClassDetails");
return mv;
}
//the valid annotation tells spring that only when its auto data binding, it should put
//validation checks on the StudentWithAddress. if its not doing data binding, then the
//validation must not be done.
#RequestMapping(value="/studentClassDetails" ,method=RequestMethod.POST)
public ModelAndView details(#Valid #ModelAttribute("student1") StudentWithAddress student,BindingResult result)
{
//If any error was raised during data binding
//the following code will be executed.
if(result.hasErrors())
{
ModelAndView mv = new ModelAndView("StudentWithAddressClassDetails");
return mv;
}
ModelAndView mv = new ModelAndView("StudentWithAddressClassDetailsSubmitted");
student.usingMessageSourse();
return mv;
}
}
In the details() method of ModelAttributeContinuedController.java, when i am making call student.usingMessageSource(), I am getting following error.
java.lang.NullPointerException
at com.manya.spring.modelattribute.StudentWithAddress.usingMessageSourse(StudentWithAddress.java:61)
at com.manya.spring.modelattribute.ModelAttributeContinuedController.details(ModelAttributeContinuedController.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:871)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:777)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:978)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:881)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:650)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
I tried implementing the same functionality using MessageSourceAware, but there also i was getting same Exception.
Related
I am getting below error while creating spring maven rest webservice. When trying to call DAO class with bean name defined in application_config.xml, getting NullPointerException
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/riceAppService] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.ganeshTrading.riceAppService.controller.UserController.getAllUsers(UserController.java:46)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1099)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:670)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Here, is my code
UserController.java
#RestController
public class UserController {
private JdbcUserDAO jdbcUserDAO;
public JdbcUserDAO getJdbcUserDAO() {
return jdbcUserDAO;
}
public void setJdbcUserDAO(JdbcUserDAO jdbcUserDAO) {
this.jdbcUserDAO = jdbcUserDAO;
}
#RequestMapping("/")
#ResponseBody
public String welcome() {
return "Welcome to RestTemplate Example.";
}
#RequestMapping(value="/users", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public List<User> getAllUsers() {
System.out.println("jdbcUserDAO"+jdbcUserDAO);
List<User> userList = jdbcUserDAO.getAllUsers();
System.out.println(userList);
return userList;
}
}
UserDAO.java
public interface UserDAO {
public List<User> getAllUsers();
}
JdbcUserDAO.java
public class JdbcUserDAO implements UserDAO {
DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public List<User> getAllUsers() {
String sql = "select * from customer";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
System.out.println("getJdbcTemplate() "+jdbcTemplate);
List<User> userList = jdbcTemplate.query(sql, new UserMapper());
return userList;
}
}
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<context:annotation-config />
<mvc:annotation-driven />
<import resource="classpath:application_config.xml" />
<context:component-scan base-package="com.ganeshTrading.riceAppService" />
</beans>
application_config.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">
<bean id="jdbcUserDAO" class="com.ganeshTrading.riceAppService.dao.impl.JdbcUserDAO">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/ganeshricetrading"></property>
<property name="username" value="root"></property>
<property name="password" value="sql"></property>
</bean>
</beans>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns="xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="xmlns.jcp.org/xml/ns/javaee xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Archetype Created Web Application</display-name>
<servlet>
<servlet-name>appServlet</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>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
ApplicationConfiguration.java
#ComponentScan(basePackages = {"com.ganeshTrading.riceAppService"})
#Configuration
#EnableWebMvc
public class ApplicationConfiguration {
}
What is wrong with my code?
Although you have defined the jdbcUserDAO bean, you have not wired it into the UserController class. This causes a NullPointerException because the jdbcUserDAO field is null, which results in the exception when jdbcUserDAO.getAllUsers() is called. To solve this, annotate the jdbcUserDAO setter in the UserController with #Autowired, as in:
#RestController
public class UserController {
private JdbcUserDAO jdbcUserDAO;
public JdbcUserDAO getJdbcUserDAO() {
return jdbcUserDAO;
}
#Autowired
public void setJdbcUserDAO(JdbcUserDAO jdbcUserDAO) {
this.jdbcUserDAO = jdbcUserDAO;
}
#RequestMapping("/")
#ResponseBody
public String welcome() {
return "Welcome to RestTemplate Example.";
}
#RequestMapping(value="/users", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public List<User> getAllUsers() {
System.out.println("jdbcUserDAO"+jdbcUserDAO);
List<User> userList = jdbcUserDAO.getAllUsers();
System.out.println(userList);
return userList;
}
}
The #Autowired annotation tells Spring that a bean that matches the interface of the parameter for the setter (in this case, JdbcUserDAO) should be injected into the setter, which results in the jdbcUserDAO field being set to your JdbcUserDAO bean defined in application_config.xml.
You could also simplify your UserController and annotate the field (removing the getter and setter):
#RestController
public class UserController {
#Autowired
private JdbcUserDAO jdbcUserDAO;
#RequestMapping("/")
#ResponseBody
public String welcome() {
return "Welcome to RestTemplate Example.";
}
#RequestMapping(value="/users", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public List<User> getAllUsers() {
System.out.println("jdbcUserDAO"+jdbcUserDAO);
List<User> userList = jdbcUserDAO.getAllUsers();
System.out.println(userList);
return userList;
}
}
For more information, see Guide to Spring #Autowired.
It also looks like your application_config.xml is not being included in Spring's application context. To include this XML file, change your ApplicationConfiguration class to resemble the following:
#ComponentScan(basePackages = {"com.ganeshTrading.riceAppService"})
#Configuration
#EnableWebMvc
#ImportResource("classpath:/path/to/application_config.xml")
public class ApplicationConfiguration {
}
Note that classpath:/path/to/application_config.xml is an example and the actual location of your application_config.xml file should be used instead.
Hi,
I got this error and i can`t figure why? all of the defintions in there place and still i have this error while i trying to insert data to my DB.
the "tx:annotation-driven" is in the appconfig-data.xml
I call the add function from "UserController"
What could be the reason it does not work?
Error log:
יול 08, 2016 1:06:23 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [searcher] in context with path [/Searcher] threw exception [Request processing failed; nested exception is org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread] with root cause
org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread
at org.springframework.orm.hibernate5.SpringSessionContext.currentSession(SpringSessionContext.java:133)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:454)
at com.searcher.dao.EcommerceImp.add(EcommerceImp.java:28)
at com.searcher.controller.UserController.registration(UserController.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:317)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:127)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:115)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:112)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169)
at
Classes
** UserController.java"
package com.searcher.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.searcher.dao.RoleDAO;
import com.searcher.entity.RoleEntity;
import com.searcher.entity.UserEntity;
import com.searcher.service.SecurityService;
import com.searcher.service.UserService;
import com.searcher.validator.UserValidator;
#Controller
public class UserController {
#Autowired
private UserService userService;
#Autowired
private SecurityService securityService;
#Autowired
private UserValidator userValidator;
#Autowired
RoleDAO roleDAO;
#RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute("userForm", new UserEntity());
try {
// Creatinw Role Entity
RoleEntity roleUser = new RoleEntity();
RoleEntity roleAdmin = new RoleEntity();
roleUser.setName("ROLE_USER");
roleAdmin.setName("ROLE_ADMIN");
roleDAO.add(roleUser);
roleDAO.add(roleAdmin);
} catch (Exception e) {
// TODO Auto-generated catch block
throw e;
}
return "registration";
}
#RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(#ModelAttribute("userForm") UserEntity userForm, BindingResult bindingResult, Model model) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.add(userForm);
securityService.autologin(userForm.getName(), userForm.getPasswordConfirm());
return "redirect:/welcome";
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
if (error != null)
model.addAttribute("error", "Your username and password is invalid.");
if (logout != null)
model.addAttribute("message", "You have been logged out successfully.");
return "login";
}
#RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
public String welcome(Model model) {
return "welcome";
}
}
UserEntity.java
package com.searcher.entity;
import java.util.List;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name="user")
public class UserEntity {
#Id
#Column(name="User_Id")
#GeneratedValue
private long Id;
#Column(name="Name")
private String Name;
#Column(name="Password")
private String Password;
#Column(name="Password_Confirm")
private String passwordConfirm;
#Column(name="Phone")
private String Phone;
#Column(name="Email")
private String Email;
#ElementCollection(targetClass=RoleEntity.class)
private Set<RoleEntity> roles;
#ManyToMany
#JoinTable(name = "user_role", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
public Set<RoleEntity> getRoles() {
return roles;
}
public void setRoles(Set<RoleEntity> roles) {
this.roles = roles;
}
public String getPasswordConfirm() {
return passwordConfirm;
}
public void setPasswordConfirm(String passwordConfirm) {
this.passwordConfirm = passwordConfirm;
}
public long getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
#Override
public String toString(){
return "Id = " + Id + ", Name = " + Name + ", Password = " + Password + ", Phone = " + Phone + ", Email = " + Email;
}
}
RoleEntity
package com.searcher.entity;
import java.util.Set;
import javax.persistence.*;
#Entity
#Table(name = "role")
public class RoleEntity {
#Id
#GeneratedValue
#Column(name="Id")
private Long Id;
#Column(name="Name")
private String Name;
#ElementCollection(targetClass=UserEntity.class)
private Set<UserEntity> users;
public Long getId() {
return Id;
}
public void setId(Long id) {
this.Id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
this.Name = name;
}
#ManyToMany(mappedBy = "roles")
public Set<UserEntity> getUsers() {
return users;
}
public void setUsers(Set<UserEntity> users) {
this.users = users;
}
}
DAO
UserDAOImp
package com.searcher.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.searcher.entity.UserEntity;
#Repository
public class UserImp implements UserDAO{
private static final Logger logger = LoggerFactory.getLogger(UserDAO.class);
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void add(UserEntity user) {
this.sessionFactory.getCurrentSession().persist(user);
logger.info("UserEntity saved successfully, UserEntity Details="+user);
}
#Override
public void edit(UserEntity user) {
this.sessionFactory.getCurrentSession().update(user);
logger.info("UserEntity updated successfully, UserEntity Details="+user);
}
#Override
public void deleteById(int id) {
UserEntity userToDelete = getUserById(id);
this.sessionFactory.getCurrentSession().delete(userToDelete);
logger.info("UserEntity deleted successfully, UserEntity Details="+userToDelete);
}
#Override
public UserEntity getUserById(int id) {
UserEntity userReturn = (UserEntity)this.sessionFactory.getCurrentSession().get(UserEntity.class, id);
logger.info("UserEntity founded successfully, UserEntity Details="+userReturn);
return userReturn;
}
#Override
public UserEntity getUserByName(String name) {
try{
UserEntity userReturn =
(UserEntity)this.sessionFactory.getCurrentSession().createQuery("from user where Name ='" + name + "'");
if (userReturn != null){
logger.info("UserEntity founded successfully, UserEntity Details="+userReturn);
}
else{
logger.info("UserEntity Not found with Name= "+userReturn);
}
return userReturn;
}catch (Exception ex){
}
return null;
}
#SuppressWarnings({ "unchecked", "deprecation" })
#Override
public List<UserEntity> getAllUser() {
List<UserEntity> userList = this.sessionFactory.getCurrentSession().createQuery("from user").list();
logger.info("List<UserEntity> upload successfully, List<UserEntity> Details="+userList.toString());
return userList;
}
}
RoleDAOIMP
package com.searcher.dao;
import java.util.List;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.searcher.entity.RoleEntity;
#Repository
public class RoleImp implements RoleDAO {
private static final Logger logger = LoggerFactory.getLogger(RoleDAO.class);
#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
#Override
public void add(RoleEntity role) {
this.sessionFactory.getCurrentSession().persist(role);
logger.info("RoleEntity saved successfully, RoleEntity Details="+role);
}
#Override
public void edit(RoleEntity role) {
this.sessionFactory.getCurrentSession().update(role);
logger.info("RoleEntity updated successfully, RoleEntity Details="+role);
}
#Override
public void deleteById(int id) {
RoleEntity roleToDelete = getRoleById(id);
this.sessionFactory.getCurrentSession().delete(roleToDelete);
logger.info("RoleEntity deleted successfully, RoleEntity Details="+roleToDelete);
}
#Override
public RoleEntity getRoleById(int id) {
RoleEntity roleReturn = (RoleEntity)this.sessionFactory.getCurrentSession().get(RoleEntity.class, id);
logger.info("RoleEntity founded successfully, RoleEntity Details="+roleReturn);
return roleReturn;
}
#Override
public RoleEntity getRoleByName(String name) {
RoleEntity roleReturn =
(RoleEntity)this.sessionFactory.getCurrentSession().createNamedQuery("from role where Name =" + name);
logger.info("RoleEntity founded successfully, RoleEntity Details="+roleReturn);
return roleReturn;
}
#SuppressWarnings({ "unchecked", "deprecation" })
#Override
public List<RoleEntity> getAllRole() {
List<RoleEntity> roleList = this.sessionFactory.getCurrentSession().createQuery("from role").list();
logger.info("List<RoleEntity> upload successfully, List<RoleEntity> Details="+roleList.toString());
return roleList;
}
}
UserServiceImp
package com.searcher.service;
import java.util.HashSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.searcher.dao.RoleDAO;
import com.searcher.dao.UserDAO;
import com.searcher.entity.UserEntity;
#Service("userService")
public class UserServiceImp implements UserService{
#Autowired
private UserDAO userDAO;
#Autowired
private RoleDAO roleDAO;
//#Autowired(required=true)
#Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
public UserDAO getUserDAO() {
return userDAO;
}
public void setUserDAO(UserDAO userDAO) {
this.userDAO = userDAO;
}
public RoleDAO getRoleDAO() {
return roleDAO;
}
public void setRoleDAO(RoleDAO roleDAO) {
this.roleDAO = roleDAO;
}
public BCryptPasswordEncoder getbCryptPasswordEncoder() {
return bCryptPasswordEncoder;
}
public void setbCryptPasswordEncoder(BCryptPasswordEncoder bCryptPasswordEncoder) {
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
#Override
#Transactional
public void add(UserEntity user) {
try {
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
user.setRoles(new HashSet<>(roleDAO.getAllRole()));
this.userDAO.add(user);
} catch (Exception e) {
// TODO: handle exception
}
}
#Override
#Transactional
public void edit(UserEntity user) {
this.userDAO.edit(user);
}
#Override
#Transactional
public void deleteById(int id) {
this.userDAO.deleteById(id);
}
#Override
#Transactional
public UserEntity getUserById(int id) {
return this.userDAO.getUserById(id);
}
#Override
#Transactional
public UserEntity getUserByName(String name) {
return this.userDAO.getUserByName(name);
}
#Override
#Transactional
public List<UserEntity> getAllUser() {
return this.userDAO.getAllUser();
}
}
RoleServiceImpl
package com.searcher.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.searcher.dao.RoleDAO;
import com.searcher.entity.RoleEntity;
public class RoleServiceImp implements RoleService {
#Autowired
private RoleDAO roleDAO;
public RoleDAO getRoleDAO() {
return roleDAO;
}
public void setRoleDAO(RoleDAO roleDAO) {
this.roleDAO = roleDAO;
}
#Override
#Transactional
public void add(RoleEntity role) {
this.roleDAO.add(role);
}
#Override
#Transactional
public void edit(RoleEntity role) {
this.roleDAO.edit(role);
}
#Override
#Transactional
public void deleteById(int id) {
this.roleDAO.deleteById(id);
}
#Override
#Transactional
public RoleEntity getRoleById(int id) {
return this.roleDAO.getRoleById(id);
}
#Override
#Transactional
public RoleEntity getRoleByName(String name) {
return this.roleDAO.getRoleByName(name);
}
#Override
#Transactional
public List<RoleEntity> getAllRole() {
return (List<RoleEntity>)this.roleDAO.getAllRole();
}
}
This is the folowing configuration files:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>Searcher</display-name>
<!-- Location of Java #Configuration classes that configure the components that makeup this application -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appconfig-root.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>searcher</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>searcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
-->
<!--
<servlet-mapping>
<servlet-name>searcher</servlet-name>
<url-pattern>/welcome.jsp</url-pattern>
<url-pattern>/welcome.html</url-pattern>
<url-pattern>*.html</url-pattern>
</servlet-mapping>-->
</web-app>
appconfig-root.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<import resource="appconfig-mvc.xml"/>
<import resource="appconfig-data.xml"/>
<import resource="appconfig-security.xml"/>
<!-- Scans within the base package of the application for #Component classes to configure as beans -->
<context:component-scan base-package="com.searcher.*"/>
<!--<context:property-placeholder location="classpath:application.properties"/>-->
</beans>
appconfig-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="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.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.1.xsd">
<http auto-config="true">
<intercept-url pattern="/" access="hasRole('ROLE_USER')"/>
<intercept-url pattern="/welcome" access="hasRole('ROLE_USER')"/>
<form-login login-page="/login" default-target-url="/welcome" authentication-failure-url="/login?error" username-parameter="username" password-parameter="password"/>
<logout logout-success-url="/login?logout" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userDetailsServiceImpl">
<password-encoder ref="encoder"></password-encoder>
</authentication-provider>
</authentication-manager>
<beans:bean id="userDetailsServiceImpl" class="com.searcher.service.UserDetailsServiceImpl"></beans:bean>
<beans:bean id="encoder"
class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
<beans:constructor-arg name="strength" value="11"/>
</beans:bean>
</beans:beans>
appconfig-data.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Configure the data source bean -->
<!-- DataSource -->
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url"
value="jdbc:mysql://localhost:3306/SearcherDB" />
<beans:property name="username" value="root" />
<beans:property name="password" value="root" />
</beans:bean>
<!-- Hibernate 5 SessionFactory Bean definition -->
<beans:bean id="hibernate5AnnotatedSessionFactory"
class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>com.searcher.entity.RoleEntity</beans:value>
<beans:value>com.searcher.entity.UserEntity</beans:value>
</beans:list>
</beans:property>
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.format_sql">true</beans:prop>
<!-- <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop> -->
</beans:props>
</beans:property>
</beans:bean>
<!-- User -->
<beans:bean id="userDAO" class="com.searcher.dao.UserImp">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<beans:bean id="userService" class="com.searcher.service.UserServiceImp">
<beans:property name="userDAO" ref="userDAO"></beans:property>
</beans:bean>
<!-- Role -->
<beans:bean id="roleDAO" class="com.searcher.dao.RoleImp">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Configure the transaction manager bean -->
<beans:bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernate5AnnotatedSessionFactory" />
</beans:bean>
</beans>
appconfig-mvc.xml
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<mvc:annotation-driven/>
<mvc:resources mapping="/resources/**" location="/resources/"/>
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:validation</value>
</list>
</property>
</bean>
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass">
<value>org.springframework.web.servlet.view.JstlView</value>
</property>
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
You are using non transactional daos in your UserController.registration method:
roleDAO.add(roleUser);
roleDAO.add(roleAdmin);
Use RoleServiceImpl instead.
I'm trying to connect MySQL database with Spring. And I also want to use DataSource setter method with #Autowired. Every time I run the code, DataSource always return as null.
Error:
HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException
Can someone show me whats wrong with my code? Please find below my code.
CustomerController.java
package com.springapp.controller;
import com.springapp.beans.Customer;
import com.springapp.service.CustomerService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
public class CustomerController {
private CustomerService customerService;
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView index() {
ModelAndView mv = new ModelAndView("index");
return mv;
}
#RequestMapping(value = "/listCustomers", method = RequestMethod.GET)
public ModelAndView ListCustomer() {
ModelAndView mv = new ModelAndView("customers");
Customer customer = customerService.findCustomerById(1);
mv.addObject("customer", customer);
return mv;
}
}
Customer.java
package com.springapp.beans;
public class Customer {
private int id;
private String firstName;
private String lastName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
CustomerDAO.java
package com.springapp.dao;
import com.springapp.beans.Customer;
public interface CustomerDAO {
public Customer findCustomerById(int customerId);
}
CustomerService
package com.springapp.service;
import com.springapp.beans.Customer;
import com.springapp.dao.CustomerDAO;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class CustomerService implements CustomerDAO {
private DataSource dataSource;
#Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
#Override
public Customer findCustomerById(int customerId) {
String sql = "SELECT * FROM CUSTOMER WHERE CUST_ID = 1";
Customer customer = new Customer();
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
customer.setFirstName(rs.getString("first_name"));
customer.setLastName(rs.getString("last_name"));
}
rs.close();
ps.close();
return customer;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.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/testjavadb" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
</beans>
dispatcher-servlet.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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:component-scan base-package="com.springapp" />
<mvc:annotation-driven />
<bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
Error Log
HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException
type Exception report
message Request processing failed; nested exception is java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
Exception
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:973)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
com.springapp.controller.CustomerController.ListCustomer(CustomerController.java:28)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:497)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:214)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:690)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.54 logs.
In your CustomerController class, try changing this line:
private CustomerService customerService;
to:
#Autowired
private CustomerService customerService;
or you can auto-wire it via setter or constructor injection, if you like.
I am getting following exception,please help to resolve this ?
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.UserDAO com.controller.UserController.userDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.dao.UserDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
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(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
root cause
org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dao.UserDAO com.controller.UserController.userDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.dao.UserDAOImpl.sessionFactory; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:469)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
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(Unknown Source)
java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
java.lang.Thread.run(Unknown Source)
Respective java codes are as below -
UserDAO
package com.dao;
import java.util.List;
import com.entity.UserDetails;
public interface UserDAO {
public List<UserDetails> getUserProfileDetails();
public int saveUserDetails(UserDetails userDetails);
public UserDetails authenticateUser(String email,String password);
public void closeSessionObjects();
}
UserDAOImpl
package com.dao;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import com.dao.UserDAO;
import com.entity.UserDetails;
#Component
#Transactional(readOnly = true)
public class UserDAOImpl implements UserDAO {
private static Logger logger = Logger.getLogger(UserDAOImpl.class);
#Autowired
private SessionFactory sessionFactory;
Session session = null;
private void assignSessionLocalVariable(){
if(session == null || !session.isOpen()){
try{
session = sessionFactory.openSession();
}catch(Exception e){session = null;}
}
}
#Override
public List<UserDetails> getUserProfileDetails() {
List<UserDetails> details=null;
if(session!=null){
try{
Query query = session.createQuery("from user");
details = query.list();
}catch(Exception e)
{
logger.error("########### Exception occured ########## "+e+" ");
}
}
return details;
}
#Override
public int saveUserDetails(UserDetails userDetails){
int saved=1;
assignSessionLocalVariable();
try{
Transaction tx=session.beginTransaction();
session.save(userDetails);
tx.commit();
saved=0;
logger.info("#### Details saved successfuly #####");
}catch(Exception e){
logger.error("### Exception occured in UserDAOImpl class #### "+e+"");
}
return saved;
}
#Override
public UserDetails authenticateUser(String email, String pwd) {
// TODO Auto-generated method stub
System.out.println("##### UserDAOImple authenticateuser started #####");
assignSessionLocalVariable();
logger.info("### Authentication of the user in progress ####");
UserDetails users = null;
if(session!=null){
try{
Query qry = session.createQuery ("from user hu where hu.email = :email and hu.password = :password");
qry.setParameter ("email", email);
qry.setParameter ("password", pwd);
qry.setMaxResults(1);
users = (UserDetails)qry.uniqueResult();
}catch(Exception e){
users = null;
System.out.println("UserDAOImpl exception in getting unique result["+e+"] ");
logger.error("UserDAOImpl exception in getting unique result["+e+"]");
}
}//if(session!=null)
return users;
}
public void closeSessionObjects(){
if(null != session) session.clear();//close();
//if(null != sessionFactory) sessionFactory.close();
}
}
UsedDetails.java
package com.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="user",catalog="test")
public class UserDetails implements java.io.Serializable{
private int id;
private String firstName;
private String lastName;
private int age;
private Date creationTime;
private Date lastModTime;
private String password;
private String email;
public UserDetails(){}
public UserDetails(String email){
this.email=email;
}
#Id
#Column(name="ID", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id){
this.id = id;
}
#Column(name="FIRST_NAME")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name="LAST_NAME")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name="AGE")
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATION_TIME", nullable = false, length = 19)
public Date getCreationTime() {
return creationTime;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "LAST_MOD_TIME", nullable = false, length = 19)
public Date getLastModTime() {
return lastModTime;
}
public void setLastModTime(Date lastModTime) {
this.lastModTime = lastModTime;
}
#Column(name="PASSWORD")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name="EMAIL")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
UserController.java
package com.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.dao.UserDAO;
import com.entity.UserDetails;
#Controller
public class UserController {
private static Logger logger = Logger.getLogger(UserController.class);
String errForward = "user.error", forward = null;
#Autowired
UserDAO userDAO;
#Autowired
UserDetails ud=null;;
#RequestMapping("/register")
public ModelAndView registerPage() {
logger.info("## Registration page forward #####");
return new ModelAndView("user.registration");
}
#RequestMapping("/registerUser")
public ModelAndView registerUser(HttpServletRequest request) {
logger.info("### Inside registeration controller ####");
int isSave=0;
Date creation_time=null,lastModTime=null;
String fName=request.getParameter("fName");
fName=(fName.equals(""))?"":fName.trim();
String lName=request.getParameter("lName");
lName=(lName.equals(""))?"":lName.trim();
int age=Integer.parseInt(request.getParameter("age"));
age=(age==0)?0:age;
String email=request.getParameter("email");
email=(email.equals(""))?"":email.trim();
String pswd=request.getParameter("pswd");
pswd=(pswd.equals(""))?"":pswd.trim();
Date date=new Date();
//creation_time=dt.getDate();
ud.setFirstName(fName);
ud.setLastName(lName);
ud.setAge(age);
ud.setPassword(pswd);
ud.setEmail(email);
ud.setCreationTime(creation_time);
ud.setLastModTime(lastModTime);
try{
isSave=userDAO.saveUserDetails(ud);
if (isSave==0){
System.out.println("%%% Successfully saved the user ::::"+isSave);
logger.info("Successfully saved the data :::"+isSave);
forward="user.registrationUserSuccess";
}
}catch(Exception e){
logger.error("##### Error while saving use details #####"+e);
return new ModelAndView(forward);
}
return new ModelAndView(forward);
}
#RequestMapping("/login")
public ModelAndView addStudent(HttpServletRequest request) {
logger.info("### Login in progress ####");
String email=request.getParameter("email");
email=(email.equals(""))?"":email.trim();
String pswd=request.getParameter("pswd");
pswd=(pswd.equals(""))?"":pswd.trim();
String login=request.getParameter("login");
login = (null != login)?login:"";
logger.info("### User login for ::: ["+email+"]:::: ######");
HttpSession httpSession = request.getSession();
if(null!=login)ud= userDAO.authenticateUser(email, pswd);
if(null!=ud){
httpSession.setAttribute("isActiveUser", ud);
forward = "user.profile";
}else forward = errForward;
return new ModelAndView(forward);
}
}
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/j2ee" xmlns:web="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_ID" version="2.4">
<display-name>Spring User</display-name>
<servlet>
<servlet-name>User</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>User</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/jsp/home.jsp</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>60</session-timeout>
</session-config>
</web-app>
User-servlet.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/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd">
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="com.controller" />
<context:component-scan base-package="com.dao" />
<context:component-scan base-package="com.entity" />
<!-- title defining -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass">
<value>
org.springframework.web.servlet.view.tiles2.TilesView
</value>
</property>
</bean>
<!-- defining title file location -->
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
</bean>
<import resource="db-config.xml" />
</beans>
db-config.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:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<bean id="dbPropertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/configuration.properties</value>
</list>
</property>
</bean>
<!-- Database Properties -->
<bean id="dataSource"
class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"
p:driverClass="${jdbc.driver.className}"
p:jdbcUrl="${jdbc.url}"
p:user="${jdbc.username}"
p:password="${jdbc.password}"
/>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.hibernate.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<property name="packagesToScan" value="com.entity" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
When I try to run this code I am getting exception that I have posted. Autowired injection is not happening. What is the problem ?
Take a close look at the Exception, It says
nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.
It looks like you are not creating sessionFactory bean. Make sure you have sessionFactory added in you spring configuration
For Example :
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="${hibernate.config}"
/>
Can anyone explain this error? I get into this line of code.
List empresas = session.createQuery("from Empresas").list(); of EmpresasDAOImp.java
jul 10, 2014 1:17:32 AM org.apache.catalina.core.StandardWrapperValve invoke
Grave: El Servlet.service() para el servlet [springapp] en el contexto con ruta [/springapp] lanzó la excepción [Request processing failed; nested exception is org.hibernate.HibernateException: createQuery is not valid without active transaction] con causa raíz
org.hibernate.HibernateException: createQuery is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:348)
at com.sun.proxy.$Proxy19.createQuery(Unknown Source)
at com.altobri.conta.dao.EmpresasDAOImpl.listEmpresas(EmpresasDAOImpl.java:50)
at com.altobri.conta.service.EmpresasServiceImpl.listEmpresas(EmpresasServiceImpl.java:48)
at com.altobri.conta.controller.empresaListaController.list(empresaListaController.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:440)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:428)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
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.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
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.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
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:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:744)
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>Spring3MVC</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>springapp</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springapp</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
springapp-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
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:component-scan base-package="com.companyname.springapp.web" />
<context:component-scan base-package="com.springHibernate" />
<context:component-scan base-package="com.altobri.conta.*" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/empresas" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="annotatedClasses">
<list>
<value>com.altobri.conta.model.Empresas</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory">
</bean>
</beans>
empresaListaController.java
package com.altobri.conta.controller;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.ModelAndView;
import com.altobri.conta.model.Empresas;
import com.altobri.conta.service.*;
#Controller
public class empresaListaController {
#Autowired
private EmpresasService empresasService;
protected final Logger logger = Logger.getLogger(getClass());
#RequestMapping("/empresaLista")
// #RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
List<Empresas> empresas = empresasService.listEmpresas();
model.addAttribute("empresalist", empresas);
return "empresaLista";
}
}
EmpresasDAO
package com.altobri.conta.dao;
import com.altobri.conta.model.Empresas;
import java.util.List;
public interface EmpresasDAO {
void persistEmpresas(Empresas empresas);
Empresas findEmpresasById(int clave);
void updateEmpresas(Empresas empresas);
void deleteEmpresas(Empresas empresas);
public List<Empresas> listEmpresas();
}
EmpresasDAOImpl.java
package com.altobri.conta.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.altobri.conta.model.Empresas;
#Repository("empresasDAO")
public class EmpresasDAOImpl implements EmpresasDAO {
#Autowired
public SessionFactory sessionFactory;
#Override
#Transactional
public void persistEmpresas(Empresas empresas) {
sessionFactory.getCurrentSession().persist(empresas);
}
#Override
#Transactional
public Empresas findEmpresasById(int clave) {
return (Empresas) sessionFactory.getCurrentSession().get(
Empresas.class, clave);
}
#Override
#Transactional
public void updateEmpresas(Empresas empresas) {
sessionFactory.getCurrentSession().update(empresas);
}
#Override
#Transactional
public void deleteEmpresas(Empresas empresas) {
sessionFactory.getCurrentSession().delete(empresas);
}
#Override
#Transactional
public List<Empresas> listEmpresas() {
Session session = sessionFactory.getCurrentSession();
List empresas = session.createQuery("from Empresas").list();
// TODO Auto-generated method stub
return empresas;
}
}
Empresas.java
package com.altobri.conta.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "EMPRESAS")
public class Empresas {
#Id
#Column(name = "CLAVE", nullable = false)
private int clave;
#Column(name = "NOMBRE", nullable = false)
private String nombre;
public Empresas() {
}
public int getClave() {
return clave;
}
public void setClave(int clave) {
this.clave = clave;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
}
EmpresasService.java
package com.altobri.conta.service;
import java.util.List;
import com.altobri.conta.model.Empresas;
public interface EmpresasService {
void persistEmpresas(Empresas empresas);
Empresas findEmpresasById(int clave);
void updateEmpresas(Empresas empresas);
void deleteEmpresas(Empresas empresas);
public List<Empresas> listEmpresas();
}
EmpresasServiceImpl.java
package com.altobri.conta.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.altobri.conta.dao.EmpresasDAO;
import com.altobri.conta.model.Empresas;
#Service("empresasService")
public class EmpresasServiceImpl implements EmpresasService{
#Autowired
EmpresasDAO empresasDAO;
#Override
#Transactional
public void persistEmpresas(Empresas empresas) {
empresasDAO.persistEmpresas(empresas);
}
#Override
#Transactional
public void updateEmpresas(Empresas empresas) {
empresasDAO.updateEmpresas(empresas);
}
#Override
#Transactional
public Empresas findEmpresasById(int clave) {
return empresasDAO.findEmpresasById(clave);
}
#Override
#Transactional
public void deleteEmpresas(Empresas empresas) {
empresasDAO.deleteEmpresas(empresas);
}
#Override
#Transactional
public List<Empresas> listEmpresas() {
// TODO Auto-generated method stub
return empresasDAO.listEmpresas();
}
}
This
#Override
public List<Empresas> listEmpresas() {
// TODO Auto-generated method stub
return empresasDAO.listEmpresas();
}
is not annotated with #Transactional. Down that method stack, you try to invoke a method that requires you to be inside a transaction.
#Override
public List<Empresas> listEmpresas() {
Session session = sessionFactory.getCurrentSession();
List empresas = session.createQuery("from Empresas").list(); // needs to be called within a Transaction
return empresas;
}
Also, you are missing transaction annotation configuration
<tx:annotation-driven />
(Don't forget to add the appropriate tx namespace declarations.)