java.lang.NullPointerException exception in my controller file (using Spring Hibernate Maven) - spring

The problem happens when I run this part (#RequestMapping("/SearchStaff")) in my controller file. I can display my search form successfullt (the request mapping below SearchStaff).
The problem doesn't seemed to have anything to do with Hibernate. As I've commented the Hibernate stuff but I'm still getting it.
If I comment out this line
message = staffDAO.searchForStaff(search);
in my controller file, it goes through ok. But I don't see anything wrong with searchForStaff function. It's a very simple function that just returns the string "test" and run system.out.println("test").
Can you please help? thanks
But this is the error that I'm getting:
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.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
root cause
java.lang.NullPointerException
org.flinders.staffdirectory.controllers.SearchController.showSearchResults(SearchController.java:25)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:601)
org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:100)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:604)
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:565)
org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
My spring-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"
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.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="org.flinders.staffdirectory.controllers" />
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<tx:annotation-driven />
<bean
id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/spring.properties" />
<bean
id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean
id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="${hibernate.config}"
p:packagesToScan="org.flinders.staffdirectory"/>
<bean
id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"
p:viewClass="org.springframework.web.servlet.view.tiles2.TilesView" />
<bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles2.TilesConfigurer"
p:definitions="/WEB-INF/tiles.xml" />
<bean
id="staffDAO"
class="org.flinders.staffdirectory.dao.StaffDAO"
p:sessionFactory-ref="sessionFactory" />
<!-- <bean
id="staffService"
class="org.flinders.staffdirectory.services.StaffServiceImpl"
p:staffDAO-ref="staffDAO" />-->
</beans>
This is my controller file
package org.flinders.staffdirectory.controllers;
import java.util.List;
//import org.flinders.staffdirectory.models.database.SearchResult;
import org.flinders.staffdirectory.models.misc.Search;
import org.flinders.staffdirectory.dao.StaffDAO;
//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;
#Controller
public class SearchController {
//#Autowired
private StaffDAO staffDAO;
private String message;
#RequestMapping("/SearchStaff")
public ModelAndView showSearchResults(#ModelAttribute Search search) {
//List<SearchResult> searchResults =
message = staffDAO.searchForStaff(search);
//System.out.println(search.getSurname());
return new ModelAndView("search/SearchForm", "Search", new Search());
//return new ModelAndView("search/SearchResults", "searchResults", searchResults);
}
#RequestMapping("/SearchForm")
public ModelAndView showSearchForm() {
return new ModelAndView("search/SearchForm", "search", new Search());
}
}
my dao class
package org.flinders.staffdirectory.dao;
import java.util.List;
import org.hibernate.SessionFactory;
//import org.springframework.beans.factory.annotation.Autowired;
import org.flinders.staffdirectory.models.database.SearchResult;
import org.flinders.staffdirectory.models.misc.Search;
public class StaffDAO {
//#Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public String searchForStaff(Search search) {
/*String SQL = "select distinct telsumm_id as id, telsumm_parent_id as parentId, telsumm_name_title as title, (case when substr(telsumm_surname, length(telsumm_surname) - 1, 1) = ',' then substr(telsumm_surname, 1, length(telsumm_surname) - 1) else telsumm_surname end) as surname, telsumm_preferred_name as firstname, nvl(telsumm_tele_number, '-') as telephoneNumber, nvl(telsumm_role, '-') as role, telsumm_display_department as department, lower(telsumm_entity_type) as entityType from teldirt.teld_summary where (telsumm_search_surname is not null) and not (nvl(telsumm_tele_directory,'xxx') IN ('N','S','D')) and not (telsumm_tele_number IS NULL AND telsumm_alias IS NULL) and (telsumm_alias_list = 'Y' OR (telsumm_tele_directory IN ('A','B'))) and ((nvl(telsumm_system_id_end,sysdate+1) > SYSDATE and telsumm_entity_type = 'P') or (telsumm_entity_type = 'N')) and (telsumm_search_department NOT like 'SPONSOR%')";
if (search.getSurname().length() > 0) {
SQL += " and (telsumm_search_surname like '" + search.getSurname().toUpperCase() + "%')";
}
if (search.getSurnameLike().length() > 0) {
SQL += " and (telsumm_search_soundex like soundex(('%" + search.getSurnameLike().toUpperCase() + "%'))";
}
if (search.getFirstname().length() > 0) {
SQL += " and (telsumm_search_preferred_name like '" + search.getFirstname().toUpperCase() + "%' or telsumm_search_first_name like '" + search.getFirstname() + "%')";
}
if (search.getTelephoneNumber().length() > 0) {
SQL += " and (telsumm_tele_number like '" + search.getTelephoneNumber() + "%')";
}
if (search.getDepartment().length() > 0) {
SQL += " and (telsumm_search_department like '" + search.getDepartment().toUpperCase() + "%')";
}
if (search.getRole().length() > 0) {
SQL += " and (telsumm_search_role like '" + search.getRole().toUpperCase() + "%')";
}
SQL += " order by surname, firstname";
List<Object[]> list = (List<Object[]>) sessionFactory.getCurrentSession().createQuery(SQL).list();
for(int j=0;j<list.size();j++){
Object [] obj= (Object[])list.get(j);
for(int i=0;i<obj.length;i++)
System.out.println(obj[i]);
}*/
System.out.println("test");
return "test";
}
}
my pom.xml
<project
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.flinders.staffdirectory</groupId>
<artifactId>directory-maven</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>directory-maven Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<org.springframework.version>3.1.3.RELEASE</org.springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.8.Final</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.apache.tiles</groupId>
<artifactId>tiles-jsp</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
</dependencies>
<build>
<finalName>directory-maven</finalName>
</build>
</project>

StaffDAO is null . Any reason why you commented out its autowiring.
Also I see private SessionFactory sessionFactory; Autowired is also commented. Please try removing those comments.
//#Autowired

Related

Spring validation annotations (#Size, #NotEmpty, #Max...) not working in my MVC project

I'm trying to get my head around an MVC project. There is a form page that the user fills out and they end up in an object of the Employee class.
#RequestMapping("/ask")
public String askDetails(Model model) {
model.addAttribute("employee", new Employee());
return "ask-page";
}
Here is what the class part looks like. It can be seen that I set parameter validation above some of the fields.
import jakarta.validation.constraints.*;
...
public class Employee {
#Size(min = 2, message = "Name must be min 2 symbols")
private String name;
#NotBlank(message = "surname is required field")
private String surname;
#Max(value = 100,message = "max is required field")
private int salary;
....
}
Here's what the html page looks like with the form filled out. It can be seen that the form "errors" is used to catch errors.
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
...
<form:form action="show" modelAttribute="employee">
Name <form:input path="name"/>
<form:errors path="name" />
<br>
<br>
Surname <form:input path="surname"/>
<form:errors path="surname"/>
<br>
<br>
Salary <form:input path="salary"/>
<form:errors path="salary" />
...
Well, this is how the method looks like, which redirects to another page if all the fields in the form have been validated.
#RequestMapping("/show")
public String showDetails(#Valid #ModelAttribute("employee") Employee emp, BindingResult bindingResult) {
System.out.println("surname length = " + emp.getSurname().length());
System.out.println("name length = " + emp.getName().length());
System.out.println("bindingResult.hasErrors() = " + bindingResult.hasErrors());
if (bindingResult.hasErrors()) {
return "ask-page";
} else {
return "show-page";
}
The problem is that the annotations specified above the fields in the class do not work. Here is the output of the showDetails method, which shows that data is being entered that does not match the specified restrictions in the Size, Name annotations. You can also see that bindingResult indicates no errors.
...
surname length = 0
name length = 0
bindingResult.hasErrors() = false
Does anyone know why these annotations don't work?
In my view, validation should not pass and the user should be returned the original form with an error on incorrectly filled fields
UPD.
POM.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.pablinho.spring.mvc</groupId>
<artifactId>spring_mvc</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<name>spring_mvc Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>6.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>6.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.0.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>javax.servlet</groupId>-->
<!-- <artifactId>servlet-api</artifactId>-->
<!-- <version>2.5</version>-->
<!-- </dependency>-->
<!-- https://mvnrepository.com/artifact/javax.servlet/servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/jakarta.servlet/jakarta.servlet-api -->
<dependency>
<groupId>jakarta.servlet</groupId>
<artifactId>jakarta.servlet-api</artifactId>
<version>6.0.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.web</groupId>
<artifactId>jakarta.servlet.jsp.jstl</artifactId>
<version>2.0.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<!-- <dependency>-->
<!-- <groupId>org.hibernate</groupId>-->
<!-- <artifactId>hibernate-validator</artifactId>-->
<!-- <version>6.1.0.Final</version>-->
<!-- </dependency>-->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>8.0.0.Final</version>
</dependency>
<!-- https://mvnrepository.com/artifact/jakarta.validation/jakarta.validation-api -->
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>3.0.2</version>
</dependency>
</dependencies>
<build>
<finalName>spring_mvc</finalName>
</build>
</project>
UPD. Add web.xml, applicationContext.xml and conroller MyController.java
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"
id="WebApp_ID" version="3.1">
<display-name>spring-cource-mvc</display-name>
<absolute-ordering />
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
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:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.pablinho.spring.mvc" />
<mvc:annotation-driven/>
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/" />
<property name="suffix" value=".jsp" />
</bean>
</beans>
MyContoller.java
package com.pablinho.spring.mvc;
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 jakarta.validation.Valid;
#Controller
#RequestMapping("/")
public class MyController {
#RequestMapping("/ask")
public String askDetails(Model model) {
model.addAttribute("employee", new Employee());
return "ask-page";
}
#RequestMapping("/show")
public String showDetails(#Valid #ModelAttribute("employee") Employee emp, BindingResult bindingResult) {
System.out.println("surname length = " + emp.getSurname().length());
System.out.println("name length = " + emp.getName().length());
System.out.println("bindingResult.hasErrors() = " + bindingResult.hasErrors());
if (bindingResult.hasErrors()) {
return "ask=page";
} else {
return "show-page";
}
}
}

No qualifying bean of type [javax.sql.DataSource] found for dependency [javax.sql.DataSource]

when autowired the datasource ,the project will appear error,when i remove the datasource ,the project works normal. i have add the datasource beans in the spring,i do not know where is wrong
i put my project on git address is:
git#github.com:liwei-green/springMVC.git
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.spring</groupId>
<artifactId>springMVC</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>springMVC Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.30</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.7.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.1.RELEASE</version>
</dependency>
</dependencies>
<build>
<finalName>springMVC</finalName>
</build>
</project>
the spring
<?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-4.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context- 4.1.xsd">
<!-- 加载配置文件 -->
<!-- 扫描service自动注入为bean -->
<context:component-scan base-package="com.springdemo" />
<context:property-placeholder location="jdbc.properties" />
<context:annotation-config />
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>${jdbc.driver}</value>
</property>
<property name="url">
<value>${jdbc.url}</value>
</property>
<property name="username">
<value>${jdbc.username}</value>
</property>
<property name="password">
<value>${jdbc.password}</value>
</property>
</bean>
<beans>
the DemoController.java
package com.springdemo.controller;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.springdemo.entity.User;
import com.springdemo.service.UserService;
#Controller
public class DemoController {
#Autowired
private UserService userService;
/*加上
#Autowired
private DataSource dataSource
编译报错,没有这句编译正常*/
#Autowired
private DataSource dataSource;
#RequestMapping("login.do")
public ModelAndView index(HttpServletRequest request,
HttpServletResponse response) throws UnsupportedEncodingException {
request.setCharacterEncoding("UTF-8");
System.out.println(userService);
System.out.println(dataSource);
String userName=request.getParameter("userName");
String userAge=request.getParameter("userAge");
User user= userService.findById(3);
if(userName.equals(user.getName())){
return new ModelAndView("sys/success","user",user);
}else{
return new ModelAndView("sys/faild","user",user);
}
}
}
jdbc.properties
jdbc.driver = com.mysql.jdbc.Driver
jdbc.url=mysql://localhost:3306/maven?useUnicode=true&characterEncoding=UTF-8
jdbc.username = root
jdbc.password = 123456
#hibernate config
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.show_sql = true
hibernate.format_sql = false
hibernate.hbm2ddl.auto = update
hibernate.cache.use_second_level_cache = true
hibernate.cache.use_query_cache = true
hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory
hibernate.cache.provider_configuration_file_resource_path = ehcache.xml
enter image description here
The context config listener is missing in web.xml, so the beans in spring.xml are not init, you can add these to your web.xml,
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
BTW: spring.xml path is not correct in the web.xml, you can change to this.
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring.xml</param-value>
</context-param>

Spring: Error creating bean with name 'sessionFactory'

I am new to spring and keep getting the following errors and after hours I just cant find the problem. Any help would be appreciated!
My ApplicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" 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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<context:annotation-config />
<context:component-scan base-package="models" />
<context:component-scan base-package="repositories" />
<context:component-scan base-package="services" />
<context:component-scan base-package="controllers" />
<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/messages" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>models.entities.MessagesEntity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" />
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
My MessagesEntity.java:
package models.entities;
import javax.persistence.*;
import java.util.Date;
#Entity
#Table(name = "usermessages", schema = "messages", catalog = "`")
public class MessagesEntity {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name = "id")
private long id;
#Column(name = "message")
private String message;
#Column(name = "username")
private String username;
#Column(name = "senttime")
private Date sentTime;
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getSentTime() {
return sentTime;
}
public void setSentTime(Date time) {
this.sentTime = time;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MessagesEntity that = (MessagesEntity) o;
if (message != null ? !message.equals(that.message) : that.message != null)
return false;
if (username != null ? !username.equals(that.username) : that.username != null)
return false;
if (sentTime != null ? !sentTime.equals(that.sentTime) : that.sentTime!= null)
return false;
return true;
}
#Override
public int hashCode() {
int result = message != null ? message.hashCode() : 0;
result = 31 * result + (username != null ? username.hashCode() : 0);
result = 31 * result + (sentTime != null ? sentTime.hashCode() : 0);
return result;
}
}
And this is my pom.xml file:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>projects.web</groupId>
<artifactId>New_WebServer</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>New_WebServer Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<springframework.version>4.3.0.RELEASE</springframework.version>
<javax.javaee.version>7.0</javax.javaee.version>
<hibernate.version>4.3.6.Final</hibernate.version>
<mysql.connector.version>5.1.31</mysql.connector.version>
<joda-time.version>2.3</joda-time.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${springframework.version}</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>${javax.javaee.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<!-- Joda-Time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${joda-time.version}</version>
</dependency>
<!-- To map JodaTime with database type -->
<dependency>
<groupId>org.jadira.usertype</groupId>
<artifactId>usertype.core</artifactId>
<version>3.0.0.CR1</version>
</dependency>
</dependencies>
<build>
<finalName>New_WebServer</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
<configuration>
<webappDirectory>target</webappDirectory>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
I also created the following classes:
MessageRepositoryImpl.java
import models.entities.MessagesEntity;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import repositories.MessageRepository;
#Repository
public class MessageRepositoryImpl implements MessageRepository {
#Autowired
private SessionFactory sessionFactory;
#Override
public MessagesEntity getById(long id) {
return (MessagesEntity) sessionFactory.getCurrentSession().get(MessagesEntity.class, id);
}
}
MessageServiceImpl.java
import models.entities.MessagesEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import repositories.MessageRepository;
import services.MessageService;
#Service
public class MessageServiceImpl implements MessageService {
#Autowired
private MessageRepository messageRepo;
#Transactional
public MessagesEntity get(long id) {
return this.messageRepo.getById(id);
}
}
Any ideas?
seems you have given catalog = "`" incorrectly in MessagesEntity . Catalogs are "namespaces" that you define on the server side of the database.

Could not autowire dao, No qualifying bean of type [...] found for dependency

I am currently developing a small application data access, which is Hibernate 4 as orm, and spring for the dependencies management.
I am now at the dao layer, I want to test the insertion of a new entity in the database, but the problem I've had is at the injection interface "studentDao" in the test class.
This is my entity (Student)
#Entity
#Table(name = "student")
public class Student{
private Long studentId;
private String cin;
private String firstName;
private String lastName;
private Integer age;
private String phone;
private String mail;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "STUDENT_ID", unique= true, nullable = false)
public Long getStudentId() {
return studentId;
}
public void setStudentId(Long studentId) {
this.studentId = studentId;
}
#Column(name = "CIN", unique= true, nullable = false, length = 8)
public String getCin() {
return cin;
}
public void setCin(String cin) {
this.cin = cin;
}
.
.
.
}
this is the generic dao interface
public interface BaseDao<T, PK extends Serializable> {
PK create(T entity);
T getById(PK id);
List<T> getAll();
void createOrUpdate(T entity);
void update(T entity);
void delete(T entity);
}
and his implementaion
public abstract class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK> {
#Autowired
#Qualifier("sessionFactory")
private SessionFactory sessionFactory;
private Class<T> type;
public BaseDaoImpl(Class<T> type) {
this.type = type;
}
#SuppressWarnings("unchecked")
public T getById(PK id) {
return (id != null) ? (T) this.currentSession().get(this.type, id) : null;
}
#SuppressWarnings("unchecked")
public List<T> getAll() {
return currentSession().createCriteria(type).list();
}
#SuppressWarnings("unchecked")
public PK create(T entity) {
if (entity != null) {
return (PK) currentSession().save(entity);
}
return null;
}
public void createOrUpdate(T o) {
if(o != null){
currentSession().merge(o);
}
}
public void update(final T entity) {
if (entity != null) {
currentSession().merge(entity);
}
}
public void delete(final T entity) {
if (entity != null) {
currentSession().delete(entity);
}
}
protected Session currentSession() {
return sessionFactory.getCurrentSession();
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
student dao interface & class
public interface StudentDao extends BaseDao<Student, Long> {
}
#Repository("studentDao")
#Transactional
public class StudentDaoImpl extends BaseDaoImpl<Student, Long> implements StudentDao {
public StudentDaoImpl(Class<Student> type) {
super(Student.class);
}
}
spring configuration file (applicationContext.xml), it is in: src/main/resources
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
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-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/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<context:component-scan base-package="com.souhaieb.education.cursus" />
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<task:annotation-driven></task:annotation-driven>
<context:annotation-config></context:annotation-config>
<aop:aspectj-autoproxy proxy-target-class="true"/>
<context:property-placeholder location="classpath:persistence-mysql.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.pass}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.souhaieb.education.cursus.entities.Student</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
Finally, I wanted to test the insertion of a new student in the database, and for that I created the class MainTest to do
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(value = {"file*:applicationContext.xml"})
public class MainTest{
#InjectMocks
#Autowired
StudentDao studentDao;
#Test
public void testStudent(){
Student student = new Student();
student.setCin("05454445");
student.setFirstName("student1");
student.setLastName("student1");
student.setAge(27);
studentDao.create(student);
}
}
when running, here is the log
15:15:45.092 [main] INFO o.s.c.s.GenericApplicationContext - Refreshing org.springframework.context.support.GenericApplicationContext#12029d31: startup date [Wed Aug 13 15:15:45 GMT+01:00 2014]; root of context hierarchy
15:15:45.162 [main] ERROR o.s.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#3d7820f] to prepare test instance [com.souhaieb.education.cursus.MainTest#399ba8c1]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.souhaieb.education.cursus.MainTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.souhaieb.education.cursus.dao.StudentDao com.souhaieb.education.cursus.MainTest.studentDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.souhaieb.education.cursus.dao.StudentDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.mockito.InjectMocks(), #org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:292) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:384) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:331) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.11.jar:na]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:292) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) [junit-4.11.jar:na]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) [junit-4.11.jar:na]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) [junit-4.11.jar:na]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) [junit-4.11.jar:na]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) [junit-4.11.jar:na]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:309) [junit-4.11.jar:na]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) [.cp/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.souhaieb.education.cursus.dao.StudentDao com.souhaieb.education.cursus.MainTest.studentDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.souhaieb.education.cursus.dao.StudentDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.mockito.InjectMocks(), #org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:508) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:289) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
... 26 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.souhaieb.education.cursus.dao.StudentDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.mockito.InjectMocks(), #org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1103) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:963) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:480) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
... 28 common frames omitted
15:15:45.167 [Thread-0] INFO o.s.c.s.GenericApplicationContext - Closing org.springframework.context.support.GenericApplicationContext#12029d31: startup date [Wed Aug 13 15:15:45 GMT+01:00 2014]; root of context hierarchy
Changing '#ContextConfiguration(value = {"file*:applicationContext"})' to '#ContextConfiguration(locations = {"classpath:applicationContext"})' full stack trace of the error is:
16:32:40.117 [main] INFO o.s.b.f.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext]
16:32:40.125 [main] ERROR o.s.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener#65c95a57] to prepare test instance [com.souhaieb.education.cursus.MainTest#64a39f6]
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.DefaultTestContext.getApplicationContext(DefaultTestContext.java:101) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:331) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:213) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:290) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) [junit-4.11.jar:na]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:292) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:233) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238) [junit-4.11.jar:na]
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63) [junit-4.11.jar:na]
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236) [junit-4.11.jar:na]
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53) [junit-4.11.jar:na]
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229) [junit-4.11.jar:na]
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.junit.runners.ParentRunner.run(ParentRunner.java:309) [junit-4.11.jar:na]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:176) [spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) [.cp/:na]
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) [.cp/:na]
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext] cannot be opened because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:343) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:303) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:187) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:251) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.support.AbstractGenericContextLoader.loadBeanDefinitions(AbstractGenericContextLoader.java:253) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:122) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:250) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91) ~[spring-test-4.0.6.RELEASE.jar:4.0.6.RELEASE]
... 25 common frames omitted
Caused by: java.io.FileNotFoundException: class path resource [applicationContext] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:172) ~[spring-core-4.0.6.RELEASE.jar:4.0.6.RELEASE]
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:329) ~[spring-beans-4.0.6.RELEASE.jar:4.0.6.RELEASE]
... 37 common frames omitted
I removed the constructor from BaseDaoImpl and I add the setter of the attribute "type".
In the StudentDaoIml, I override the default constuctor where I initialized into the type (Student.class).
BaseDaoImpl.java:
public abstract class BaseDaoImpl<T, PK extends Serializable> implements BaseDao<T, PK> {
#Autowired
#Qualifier("sessionFactory")
private SessionFactory sessionFactory;
private Class<T> type;
#SuppressWarnings("unchecked")
public T getById(PK id) {
return (id != null) ? (T) this.currentSession().get(this.type, id) : null;
}
#SuppressWarnings("unchecked")
public List<T> getAll() {
return currentSession().createCriteria(type).list();
}
#SuppressWarnings("unchecked")
public PK create(T entity) {
if (entity != null) {
return (PK) currentSession().save(entity);
}
return null;
}
public void createOrUpdate(T o) {
if(o != null){
currentSession().merge(o);
}
}
public void update(final T entity) {
if (entity != null) {
currentSession().merge(entity);
}
}
public void delete(final T entity) {
if (entity != null) {
currentSession().delete(entity);
}
}
public void setType(final Class<T> typeToSet) {
type = typeToSet;
}
protected Session currentSession() {
return sessionFactory.getCurrentSession();
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
StudentDaoImlp.java:
#Repository("studentDao")
#Transactional
public class StudentDaoImpl extends BaseDaoImpl<Student, Long> implements StudentDao {
public StudentDaoImpl(){
setType(Student.class);
}
}
applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
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-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/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<context:component-scan base-package="com.souhaieb.education.cursus" />
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
<task:annotation-driven></task:annotation-driven>
<context:annotation-config></context:annotation-config>
<!-- <aop:aspectj-autoproxy proxy-target-class="true"/> -->
<context:property-placeholder location="classpath:persistence-mysql.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.user}" />
<property name="password" value="${jdbc.pass}" />
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>com.souhaieb.education.cursus.entities.Student</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="persistenceExceptionTranslationPostProcessor"
class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.souhaieb.education</groupId>
<artifactId>cursus</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>cursus</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java-version>1.7</java-version>
<org.springframework.version>4.0.6.RELEASE</org.springframework.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>test</scope>
</dependency>
<!-- Spring dependencies begin -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.1</version>
</dependency>
<!-- Mockito -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<!-- Jax WS Spring Integration -->
<dependency>
<groupId>org.jvnet.jax-ws-commons.spring</groupId>
<artifactId>jaxws-spring</artifactId>
<version>1.9</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- SLF4J -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.7</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.7.7</version>
</dependency>
<!-- Log Back -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
</dependency>
<!-- Apache Commons DBCP dependency (for database connection pooling) -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.0.1</version>
</dependency>
<!-- MySQL Connector Java dependency (JDBC driver for MySQL) -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.31</version>
</dependency>
<!-- Hibernate dependencies begin -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.6.Final</version>
<!--<exclusions>
<exclusion>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging-processor</artifactId>
</exclusion>
<exclusion>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
</exclusion>
<exclusion>
<groupId>org.jboss.spec.javax.transaction</groupId>
<artifactId>jboss-transaction-api_1.1_spec</artifactId>
</exclusion>
<exclusion>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
</exclusion>
<exclusion>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
</exclusion>
<exclusion>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
</exclusion>
</exclusions>-->
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
</dependencies>
<build>
<finalName>Cursus</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>${java-version}</source>
<target>${java-version}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
MaintTest.java:
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"/applicationContext.xml"})
public class MainTest{
private final static Logger logger = LoggerFactory.getLogger(MainTest.class);
#Autowired
StudentDao studentDao;
#Test
public void testStudent(){
Student student = new Student();
student.setStudentId(1L);
student.setCin("05454445");
student.setFirstName("student1");
student.setLastName("student1");
student.setAge(27);
Long id = studentDao.create(student);
logger.info("Student ID = "+id);
}
}

Spring3 + JSF Composite components

updated
im trying to use JSF composite componets in my spring3 aplication . Doing a simple test
/test (mapped to view views\test.xhtml)
im getting the following error:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is javax.faces.FacesException
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:656)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
causa raíz
javax.faces.FacesException
com.sun.faces.context.ExceptionHandlerImpl.handle(ExceptionHandlerImpl.java:141)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
org.springframework.faces.mvc.JsfView.renderMergedOutputModel(JsfView.java:85)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
causa raíz
java.lang.NullPointerException
com.sun.faces.application.ApplicationImpl.createComponent(ApplicationImpl.java:972)
org.springframework.faces.webflow.Jsf2FlowApplication.createComponent(Jsf2FlowApplication.java:68)
com.sun.faces.facelets.tag.jsf.CompositeComponentTagHandler.createComponent(CompositeComponentTagHandler.java:165)
com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.createComponent(ComponentTagHandlerDelegateImpl.java:488)
com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:157)
javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:98)
com.sun.faces.facelets.tag.ui.DefineHandler.applyDefinition(DefineHandler.java:103)
com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:178)
com.sun.faces.facelets.impl.DefaultFaceletContext$TemplateManager.apply(DefaultFaceletContext.java:395)
com.sun.faces.facelets.impl.DefaultFaceletContext.includeDefinition(DefaultFaceletContext.java:366)
com.sun.faces.facelets.tag.ui.InsertHandler.apply(InsertHandler.java:108)
javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:98)
javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:188)
javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:98)
com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93)
javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:98)
com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:86)
com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:308)
com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:367)
com.sun.faces.facelets.impl.DefaultFacelet.include(DefaultFacelet.java:346)
com.sun.faces.facelets.impl.DefaultFaceletContext.includeFacelet(DefaultFaceletContext.java:199)
com.sun.faces.facelets.tag.ui.CompositionHandler.apply(CompositionHandler.java:155)
com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93)
com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:86)
com.sun.faces.facelets.impl.DefaultFacelet.apply(DefaultFacelet.java:152)
com.sun.faces.application.view.FaceletViewHandlingStrategy.buildView(FaceletViewHandlingStrategy.java:769)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:100)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
org.springframework.faces.mvc.JsfView.renderMergedOutputModel(JsfView.java:85)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1047)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:817)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
this error disapears if i remove the composite component
this is my file tree
\
+src
| +main
| +java
| | \(...)
| \CustomResourceHandler.java
| +resources
| | +META-INF
| | +applicationContext.xml
| | \(...)
| \webapp
| +(...)
| +resources
| | \ui
| | \util
| | \hello.xhtml
| +WEB-INF
| | \views
| | \test.xhtml
| +faces-config.xml
| \web.xml
\pom.xml
hello.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:composite="http://java.sun.com/jsf/composite"
xmlns:h="http://java.sun.com/jsf/html">
<composite:interface>
</composite:interface>
<composite:implementation>
<h:outputText value="hello composite" />
</composite:implementation>
</html>
test.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:util="http://java.sun.com/jsf/composite/ui/util">
<util:hello/>
</html>
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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- holding properties for database connectivity /-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<context:component-scan base-package="........" />
<context:component-scan base-package="........"/>
<!-- map all requests to /resources/** to the container default servlet (ie, don't let Spring handle them) -->
<bean id="defaultServletHttpRequestHandler" class="org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler" />
<bean id="simpleUrlHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="urlMap">
<map>
<entry key="/resources/**" value-ref="defaultServletHttpRequestHandler" />
<entry key="/javax.faces.resource/**" value-ref="defaultServletHttpRequestHandler" />
</map>
</property>
</bean>
<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter" />
<mvc:annotation-driven/>
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="cache" value="false" />
<property name="viewClass" value="org.springframework.faces.mvc.JsfView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".xhtml" />
</bean>
<context:annotation-config/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"
p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
<property name="persistenceUnitName" value="....."></property>
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="${jpa.database}"
p:showSql="${jpa.showSql}"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory"/>
</beans>
faces-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.0" 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-facesconfig_2_0.xsd">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
<resource-handler>....***.CustomResourceHandler</resource-handler>
<locale-config>
</locale-config>
<resource-bundle>
<base-name>compass</base-name>
<var>txt</var>
</resource-bundle>
</application>
</faces-config>
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">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.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>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
CustomResourceHandler.java
import javax.faces.application.Resource;
import javax.faces.application.ResourceHandler;
import javax.faces.application.ResourceHandlerWrapper;
import javax.faces.application.ResourceWrapper;
import javax.faces.context.FacesContext;
import com.sun.faces.util.Util;
/**
* Custom JSF ResourceHandler.
*
* This handler bridges between Spring MVC and JSF managed resources. The handler takes
* care of the case when a JSF facelet is used as a view by a Spring MVC Controller and the
* view uses components like h:outputScript and h:outputStylesheet by correctly pointing the
* resource URLs generated to the JSF resource handler.
*
* The reason this custom handler wrapper is needed is because the JSF internal logic assumes
* that the request URL for the current page/view is a JSF url. If it is a Spring MVC request, JSF
* will create URLs that incorrectly includes the Spring controller context.
*
* This handler will strip out the Spring context for the URL and add the ".jsf" suffix, so the
* resource request will be routed to the FacesServlet with a correct resource context (assuming the
* faces servlet is mapped to the *.jsf pattern).
*
*
*/
public class CustomResourceHandler extends ResourceHandlerWrapper {
private ResourceHandler wrapped;
public CustomResourceHandler(ResourceHandler wrapped) {
this.wrapped = wrapped;
}
#Override
public ResourceHandler getWrapped() {
return this.wrapped;
}
#Override
public Resource createResource(String resourceName, String libraryName) {
return new CustomResource(super.createResource(resourceName, libraryName),resourceName);
}
#Override
public Resource createResource(String resourceName, String libraryName,
String contentType) {
return new CustomResource(super.createResource(resourceName, libraryName, contentType),resourceName);
}
private static class CustomResource extends ResourceWrapper {
private Resource wrapped;
private String resourceName;
private CustomResource(Resource wrapped,String resourceName) {
//super();
this.resourceName = resourceName;
this.wrapped = wrapped;
}
#Override
public Resource getWrapped() {
return this.wrapped;
}
#Override
public String getRequestPath() {
FacesContext context = FacesContext.getCurrentInstance();
// si no existe el recurso lo mapeamos igualmente
if (this.wrapped == null) {
return context.getExternalContext().getRequestContextPath() + "/resources/" + resourceName;
}
String path = super.getRequestPath();
String facesServletMapping = Util.getFacesMapping(context);
// if prefix-mapped, this is a resource that is requested from a faces page
// rendered as a view to a Spring MVC controller.
// facesServletMapping will, in fact, be the Spring mapping
if (Util.isPrefixMapped(facesServletMapping)) {
// remove the Spring mapping
path = path.replaceFirst("(" + facesServletMapping + ")/", "/");
// append .jsf to route this URL to the FacesServlet
path = path.replace(wrapped.getResourceName(), wrapped.getResourceName() + ".jsf");
}
return path;
}
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>****</groupId>
<artifactId>****/artifactId>
<version>0.0.1</version>
<packaging>war</packaging>
<name>****</name>
<properties>
<org.springframework.version>3.0.5.RELEASE</org.springframework.version>
<org.hibernate.version>3.5.1-Final</org.hibernate.version>
<maven.compiler.source>1.6</maven.compiler.source>
<maven.compiler.target>1.6</maven.compiler.target>
<com.sun.faces.version>2.1.1-b04</com.sun.faces.version>
<!-- 2.0.4-b09 -->
</properties>
<repositories>
<repository>
<!-- Crear este repositorio con nexus para hostear los jar de terceros -->
<id>terceros</id>
<name>Repositorio Local</name>
<url>http://127.0.0.1:8081/nexus/content/repositories/thirdparty</url>
</repository>
<repository>
<id>repository.jboss.org-public</id>
<name>JBoss repository</name>
<url>https://repository.jboss.org/nexus/content/groups/public</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>${com.sun.faces.version}</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>${com.sun.faces.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.webflow</groupId>
<artifactId>spring-faces</artifactId>
<version>2.3.2.RELEASE</version> <!-- no hay ${org.springframework.version} -->
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-asm</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${org.springframework.version}</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${org.hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>${org.hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>${org.hibernate.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<!-- Hosteado con Nexus -->
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<!-- Hosteado con Nexus -->
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
In test.xhtml your namespace for your composite component is wrong. Change it from:
xmlns:util="http://java.sun.com/jsf/composite/ui/util"
to:
xmlns:util="http://java.sun.com/jsf/composite/ui"
The problem is that JSF Composite doenst like my CustomResource, made a workaround that and its working now.
Might not be the most elegant solution tought.
CustomResourceHandler.java
import javax.faces.application.Resource;
import javax.faces.application.ResourceHandler;
import javax.faces.application.ResourceHandlerWrapper;
import javax.faces.application.ResourceWrapper;
import javax.faces.context.FacesContext;
import com.sun.faces.util.Util;
/**
* Custom JSF ResourceHandler.
*
* This handler bridges between Spring MVC and JSF managed resources. The handler takes
* care of the case when a JSF facelet is used as a view by a Spring MVC Controller and the
* view uses components like h:outputScript and h:outputStylesheet by correctly pointing the
* resource URLs generated to the JSF resource handler.
*
* The reason this custom handler wrapper is needed is because the JSF internal logic assumes
* that the request URL for the current page/view is a JSF url. If it is a Spring MVC request, JSF
* will create URLs that incorrectly includes the Spring controller context.
*
* This handler will strip out the Spring context for the URL and add the ".jsf" suffix, so the
* resource request will be routed to the FacesServlet with a correct resource context (assuming the
* faces servlet is mapped to the *.jsf pattern).
*
*
*/
public class CustomResourceHandler extends ResourceHandlerWrapper {
private ResourceHandler wrapped;
public CustomResourceHandler(ResourceHandler wrapped) {
this.wrapped = wrapped;
}
#Override
public ResourceHandler getWrapped() {
return this.wrapped;
}
#Override
public Resource createResource(String resourceName, String libraryName) {
Resource wrapped = super.createResource(resourceName, libraryName);
if (resourceName.endsWith(".xhtml")) {
return wrapped;
}
return new CustomResource(wrapped,resourceName);
}
#Override
public Resource createResource(String resourceName, String libraryName,
String contentType) {
Resource wrapped = super.createResource(resourceName, libraryName, contentType);
if (resourceName.endsWith(".xhtml")) {
return wrapped;
}
return new CustomResource(wrapped,resourceName);
}
private static class CustomResource extends ResourceWrapper {
private Resource wrapped;
private String resourceName;
private CustomResource(Resource wrapped,String resourceName) {
//super();
this.resourceName = resourceName;
this.wrapped = wrapped;
}
#Override
public Resource getWrapped() {
return this.wrapped;
}
#Override
public String getRequestPath() {
FacesContext context = FacesContext.getCurrentInstance();
// si no existe el recurso lo mapeamos igualmente
if (this.wrapped == null) {
return context.getExternalContext().getRequestContextPath() + "/resources/" + resourceName;
}
String path = super.getRequestPath();
String facesServletMapping = Util.getFacesMapping(context);
// if prefix-mapped, this is a resource that is requested from a faces page
// rendered as a view to a Spring MVC controller.
// facesServletMapping will, in fact, be the Spring mapping
if (Util.isPrefixMapped(facesServletMapping)) {
// remove the Spring mapping
path = path.replaceFirst("(" + facesServletMapping + ")/", "/");
// append .jsf to route this URL to the FacesServlet
path = path.replace(wrapped.getResourceName(), wrapped.getResourceName() + ".jsf");
}
return path;
}
}
}

Resources