Spring3 + JSF Composite components - spring

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;
}
}
}

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 mapping found for HTTP request with URI [/] in DispatcherServlet with name 'appServlet'

In Spring Project,
WARN : org.springframework.web.servlet.PageNotFound - No mapping found
for HTTP request with URI [/] in DispatcherServlet with name
'appServlet'
ERRORs continues to occur. I don't know why these errors occur.
please help me...
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.sample.controller" use-default-filters="false" />
</beans:beans>
As you can see below, I have specified #Controller.
BoardController.java
package com.sample.controller;
import javax.inject.Inject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.sample.domain.BoardVO;
import com.sample.service.BoardService;
#Controller
#RequestMapping(value = "/")
public class BoardController {
#Inject
private BoardService service;
#RequestMapping(value = "/listAll", method = RequestMethod.GET)
public void listAll(Model model) throws Exception {
model.addAttribute("list", service.listAll());
}
#RequestMapping(value = "/regist", method = RequestMethod.POST)
public String registPOST(BoardVO board, RedirectAttributes rttr) throws Exception {
service.regist(board);
return "redirect:/listAll";
}
#RequestMapping(value = "/read", method = RequestMethod.GET)
public void read(#RequestParam("bno") int bno, Model model) throws Exception {
model.addAttribute(service.read(bno));
}
#RequestMapping(value = "/modify", method = RequestMethod.GET)
public void modifyGET(int bno, Model model) throws Exception {
model.addAttribute(service.read(bno));
}
#RequestMapping(value = "/modify", method = RequestMethod.POST)
public String modifyPOST(BoardVO board, RedirectAttributes rttr) throws Exception {
service.modify(board);
return "redirect:/listAll";
}
#RequestMapping(value = "/remove", method = RequestMethod.POST)
public String removePOST(#RequestParam("bno") int bno, RedirectAttributes rttr) throws Exception {
service.remove(bno);
return "redirect:/listAll";
}
}
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 https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<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/spring/appServlet/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>
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.myp</groupId>
<artifactId>controller</artifactId>
<name>SCH02</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<java-version>1.6</java-version>
<org.springframework-version>3.1.1.RELEASE</org.springframework-version>
<org.aspectj-version>1.6.10</org.aspectj-version>
<org.slf4j-version>1.6.6</org.slf4j-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
<exclusions>
<!-- Exclude Commons Logging in favor of SLF4j -->
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<!-- AspectJ -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>${org.aspectj-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${org.slf4j-version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.15</version>
<exclusions>
<exclusion>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
</exclusion>
<exclusion>
<groupId>javax.jms</groupId>
<artifactId>jms</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jdmk</groupId>
<artifactId>jmxtools</artifactId>
</exclusion>
<exclusion>
<groupId>com.sun.jmx</groupId>
<artifactId>jmxri</artifactId>
</exclusion>
</exclusions>
<scope>runtime</scope>
</dependency>
<!-- #Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.7</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${org.springframework-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.21</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<configuration>
<mainClass>org.test.int1.Main</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
This is just a warning not an error. In your controller, there is no mapping for the root context #RequestMapping(value = "/"). You can redirect to another view or create a home jsp.
// redirect
#GetMapping(value = "/")
public String redirect(Model model) throws Exception {
return "redirect:/listAll";
}
// or home.jsp
#GetMapping(value = "/")
public String home() throws Exception {
return "home";
}
EDIT: use-default-filters="false" disable scanning of #Controller. You should remove it otherwise your controller is not register in Spring context.
<context:component-scan base-package="com.sample.controller" />

When I put #Autowire annotaion for JAX WS class it gives null pointer exception error in spring boot

I write a JAX-WS service for my web application and when I call to the web service it gives the null pointer exception(Autowire not working)... I us tomcat 8.5.11 as a server...
When I remove the #WebService annotaion the autowire works fine.... But when i add it it doesn't work... What is the error... Is it error becomes with my dependencies...
This is my Dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
</dependency>
<!--handle servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!--<Email Dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
<version>1.4.3.RELEASE</version>
<exclusions>
<exclusion>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--Add mysql dependency-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.3</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.1</version>
</dependency>
<!--jasper-->
<dependency>
<groupId>net.sf.jasperreports</groupId>
<artifactId>jasperreports</artifactId>
<version>3.7.6</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.10</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.ws/jaxws-rt -->
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>2.2.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.jvnet.staxex/stax-ex -->
<dependency>
<groupId>org.jvnet.staxex</groupId>
<artifactId>stax-ex</artifactId>
<version>1.7.8</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.stream.buffer/streambuffer -->
<dependency>
<groupId>com.sun.xml.stream.buffer</groupId>
<artifactId>streambuffer</artifactId>
<version>1.5.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.sun.xml.bind/jaxb-libs -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-libs</artifactId>
<version>1.0.6</version>
</dependency>
My Model is annotated with #Entity annotation..I'm not put it here...
My repository is
package lk.slsi.repository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import java.util.List;
import lk.slsi.domain.CustomsPermit;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
#Repository
#Qualifier("PermitRepository")
public interface PermitRepository extends CrudRepository < CustomsPermit, Long > {
#Query("select a from CustomsPermit a where a.dtIssue = :dtIssue")
List < CustomsPermit > getPermitByDate(#Param("dtIssue") String dtIssue);
}
My WS class is
package lk.slsi.repository;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jws.WebService;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import lk.slsi.domain.CustomsPermit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
/**
*
* #author lankadeva.ghg
*/
#WebService
#Component
public class permitRepoImpl extends SpringBeanAutowiringSupport {
#Autowired
#Qualifier("PermitRepository")
private PermitRepository permitRepository;
public static void marshaling() throws JAXBException {
try {
JAXBContext jaxbContext = JAXBContext.newInstance(CustomsPermit.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
} catch (JAXBException ex) {
Logger.getLogger(permitRepoImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
public List < CustomsPermit > getPermitByDate(String dtIssue) {
try {
System.out.println("autowire is " + permitRepository);
marshaling();
} catch (JAXBException ex) {
Logger.getLogger(permitRepoImpl.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("exception : autowire is " + permitRepository);
return (List < CustomsPermit > ) ex;
}
return permitRepository.getPermitByDate(dtIssue);
}
}
The Autowire doesn't works in here...When I go on debug mode it gives null as a value
This is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app version="3.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-app_3_0.xsd">
<display-name>SLSIonNationalSingleWindow</display-name>
<servlet-mapping>
<servlet-name>permitRepoImplService</servlet-name>
<url-pattern>/permitRepoImplService</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>/view/index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>spring-web</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:slsi-servlet-config.xml</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>permitRepoImplService</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-web</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
This is my applicationconfig.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.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">
<!-- Scan Config -->
<context:component-scan base-package="lk.slsi" />
<!--<mvc:annotation-driven/>-->
<mvc:default-servlet-handler/>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/view/" />
<property name="suffix" value=".jsp" />
</bean>
<!--<bean id = "permitRepository" class="lk.slsi.repository.PermitRepository"
autowire="byName" autowire-candidate="true">
</bean>-->
</beans>
What is the error in my dependency injection....
Can you try adding this dependency : jaxws-spring library that integrates the two frameworks:
<dependency>
<groupId>org.jvnet.jax-ws-commons.spring</groupId>
<artifactId>jaxws-spring</artifactId>
<version>1.9</version>
</dependency>
Refer this link for more :
https://examples.javacodegeeks.com/enterprise-java/jws/jax-ws-spring-integration-example/

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>

when injecting Spring service bean to JSF ManagedBean it shows me a NullPointerException

Tomcat 8 ,JSF , Spring
When i try to inject a spring service to jsf managed bean it shows the NullPointerException
check.xhtml
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
>
<h:head> </h:head>
<h:body>
<p:dataTable var="check" value="#{checkBean.checks}">
<p:column headerText="Name">
<h:outputText value="#{check.name}" />
</p:column>
<p:column headerText="URL">
<h:outputText value="#{check.url}" />
</p:column>
</p:dataTable>
</h:body>
</html>
CheckBean
#Setter
#ManagedBean
public class CheckBean implements Serializable {
private static final long serialVersionUID = 1L;
#ManagedProperty("#{checkService}")
private CheckService checkService;
private List<Check> checks;
private Check check = new Check();
public void save()
{
checkService.save(check);
}
public List<Check> getChecks() {
System.out.println(checkService==null);
//checks=checkService.findAll();
return checks;
}
}
CheckService
#Getter
#Setter
#Service
public class CheckService implements CheckServiceInterface {
#Autowired
private CheckRepository checkRepository;
public List<Check> findAll()
{
//return checkRepository.findAll();
List<Check> l=new ArrayList<Check>();
Check c =new Check();
c.setName("aa");
c.setUrl("www.exemple.com");
l.add(c);
return l;
}
public void save(Check check) {
checkRepository.save(check);
}
}
faces-config.xml
<?xml version="1.0"?>
<faces-config version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<application>
<el-resolver>
org.springframework.web.jsf.el.SpringBeanFacesELResolver
</el-resolver>
</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">
<display-name>Crud</display-name>
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
<param-value>0</param-value>
</context-param>
<context-param>
<param-name>javax.faces.FACELETS_SKIP_COMMENTS</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</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-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>selectChecks.xhtml</welcome-file>
</welcome-file-list>
</web-app>
SpringConfiguration
#Configuration
#ComponentScan
#EnableTransactionManagement
#EnableJpaRepositories("com.crud.repositories")
public class SpringConfiguration {
#Bean
public DataSource dataSource() {
BasicDataSource ds = new org.apache.commons.dbcp.BasicDataSource();
ds.setDriverClassName("com.mysql.jdbc.Driver");
ds.setUrl("jdbc:mysql://127.0.0.1:3306/test");
ds.setUsername("crud");
ds.setPassword("crud");
return ds;
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
lef.setDataSource(dataSource);
lef.setJpaVendorAdapter(jpaVendorAdapter);
lef.setPackagesToScan("com.crud.entities");
return lef;
}
#Bean
public JpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setShowSql(false);
hibernateJpaVendorAdapter.setGenerateDdl(true);
hibernateJpaVendorAdapter.setDatabase(Database.MYSQL);
return hibernateJpaVendorAdapter;
}
#Bean
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager();
}
}
MyWebAppInitializer
public class MyWebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
// TODO Auto-generated method stub
AnnotationConfigWebApplicationContext rootContext=new AnnotationConfigWebApplicationContext();
rootContext.register(SpringConfiguration.class);
container.addListener(new ContextLoaderListener(rootContext));
}
}
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>CrudTest</groupId>
<artifactId>Crud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>javax.faces</artifactId>
<version>2.2.9</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>5.3</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>2.1.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.7.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.7.Final</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.6</version>
</dependency>
<!--********************************************************************************************** -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>javax.el-api</artifactId>
<version>3.0.1-b04</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.sun.el</groupId>
<artifactId>el-ri</artifactId>
<version>1.0</version>
</dependency>
<!--********************************************************************************************** -->
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframewok</groupId>
<artifactId>spring-framework-bom</artifactId>
<version>4.2.5.RELEASE</version>
<type>bom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<finalName>JavaServerFaces</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
</project>

Resources