IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

JSF Java Discussion :

Problème d'injection de service dans un bean avec spring


Sujet :

JSF Java

  1. #1
    Membre confirmé
    Profil pro
    Inscrit en
    Janvier 2011
    Messages
    92
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2011
    Messages : 92
    Par défaut Problème d'injection de service dans un bean avec spring
    Bonjour, je débute sous jsf 2, et j'ai quelques difficultés pour utiliser ma couche service dans un bean. J'ai voulu commencer par qqch de pas trop compliqué comme l'ajout d'un utilisateur mais j'obtiens l'erreur suivante :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    ATTENTION: Multiple JSF Applications found on same ClassLoader.  Unable to safely determine which FactoryManager instance to use. Defaulting to first match.
    17:42:16.974 ["http-apr-8080"-exec-4] DEBUG o.h.v.e.r.DefaultTraversableResolver - Found javax.persistence.PersistenceUtil on classpath.
    17:42:16.974 ["http-apr-8080"-exec-4] INFO  o.h.v.e.r.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
    17:42:16.976 ["http-apr-8080"-exec-4] DEBUG o.h.v.xml.ValidationXmlParser - No META-INF/validation.xml found. Using annotation based configuration only
    14 mai 2011 17:42:17 com.sun.faces.lifecycle.InvokeApplicationPhase execute
    ATTENTION: #{userBean.addUser}: java.lang.NullPointerException
    javax.faces.FacesException: #{userBean.addUser}: java.lang.NullPointerException
            at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
            at javax.faces.component.UICommand.broadcast(UICommand.java:315)
            at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
            at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
            at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
            at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
            at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
            at javax.faces.webapp.FacesServlet.service(FacesServlet.java:409)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
            at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
            at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
            at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
            at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
            at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
            at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
            at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
            at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
            at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
            at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
            at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
            at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:306)
            at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:322)
            at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1732)
            at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
            at java.lang.Thread.run(Thread.java:662)
    Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
            at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
            at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
            ... 26 more
    Caused by: java.lang.NullPointerException
            at fr.covoiturage.bean.user.UserBean.addUser(UserBean.java:74)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at org.apache.el.parser.AstValue.invoke(AstValue.java:262)
            at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
            at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
            at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
            ... 27 more
    La page index.xhtml contient le code suivant :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
     <ui:define name="content">
     
                    <h2>Add New User</h2>
                    <h:form>
     
                        <h:panelGrid columns="3">
     
    			Username :
                            <h:inputText id="username" value="#{userBean.username}"
                                         size="20" required="true"
                                         label="Username" >
                            </h:inputText>
     
                            <h:message for="username" style="color:red" />
     
                            Password :
                            <h:inputText id="password" value="#{userBean.password}"
                                         size="20" required="true"
                                         label="Password" >
                            </h:inputText>
                            <h:message for="password" style="color:red" />
                            First Name :
                            <h:inputText id="firstName" value="#{userBean.firstName}"
                                         size="20" required="true"
                                         label="First Name" >
                            </h:inputText>
                            <h:message for="firstName" style="color:red" />
                            Name :
                            <h:inputText id="name" value="#{userBean.name}"
                                         size="20" required="true"
                                         label="Name" >
                            </h:inputText>
                            <h:message for="name" style="color:red" />
     
                        </h:panelGrid>
     
                        <h:commandButton value="Submit" action="#{userBean.addUser}" />
     
                    </h:form>
                </ui:define>
    Et userBean fonctionne à moitié, si je ne saisis rien la validation m'afficher correctement le message d'erreur, par contre si je saisi correctement des valeurs j'obtiens l'erreur précédente.

    UserBean.java
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    package fr.covoiturage.bean.user;
     
    import fr.covoiturage.entite.user.User;
    import fr.covoiturage.entite.user.UserService;
    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.RequestScoped;
    import javax.inject.Inject;
    import javax.inject.Named;
    import javax.validation.constraints.NotNull;
    import javax.validation.constraints.Size;
     
    /**
     *
     * @author Gabz
     */
     
    //@Scope("request")
    //@Named("userBean")
    @ManagedBean(name="userBean")
    @RequestScoped
    public class UserBean implements Serializable {
     
        private static final long serialVersionUID = 1L;
        private Integer userId;
        @NotNull(message = "Vous devez saisir un nom")
        @Size(min = 1, max = 16, message = "Entre 1  et 16 caractères")
        private String username;
        @NotNull(message = "Vous devez saisir un nom")
        @Size(min = 6, max = 16, message = "Entre 6  et 16 caractères")
        private String password;
        @NotNull(message = "Vous devez saisir un nom")
        @Size(min = 1, max = 16, message = "Entre 1  et 16 caractères")
        private String firstName;
        @NotNull(message = "Vous devez saisir un nom")
        @Size(min = 1, max = 16, message = "Entre 1  et 16 caractères")
        private String name;
        private Date registrationDate;
     
        /** Creates a new instance of UserBean */
        public UserBean() {
        }
        @Inject
        @Named("userService")
        private UserService userService;
     
        public void setUserService(UserService userService) {
            this.userService = userService;
        }
     
        public UserService getUserService() {
            return userService;
        }
     
        //get all customer data from database
        public List<User> getUserList() {
            try {
                return userService.getAll();
            } catch (Exception e) {
                return new ArrayList<User>(0);
            }
     
        }
     
        public String addUser() {
     
            User user = userService.createUser(getFirstName(), getName(), getUsername(), getPassword());
            // User user = new User(getFirstName(), getName(), getUsername(), getPassword());
            System.out.println(user);
            userService.persist(user);
            clearForm();
            return "";
        }
     
        //clear form values
        private void clearForm() {
            setUsername("");
            setPassword("");
            setFirstName("");
            setName("");
        }
     
    // getter et setter
    }
    J'utilise JSF 2, Spring 3.0.5, JPA et Hibernate, et le tout fonctionne avec tomcat pour le moment (n'ayant pas réussi à utiliser glassfish avec jta...)
    Je rajoute mes fichiers de config, mais je ne sais pas où se situe l'erreur

    applicationContext.xml
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    <?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:task="http://www.springframework.org/schema/task"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:util="http://www.springframework.org/schema/util"
           xmlns:p="http://www.springframework.org/schema/p"
           xmlns:security="http://www.springframework.org/schema/security"
           xmlns:jee="http://www.springframework.org/schema/jee"
           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/util http://www.springframework.org/schema/util/spring-util-3.0.xsd
             http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
             http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-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/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd">
     
    <!-- enabling annotation driven configuration-->
        <context:annotation-config/>
     
        <context:component-scan base-package="fr.covoiturage.entite"/>
     
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
            <property name="driverClass" value="org.postgresql.Driver" />
            <property name="jdbcUrl" value="jdbc:postgresql://localhost:5432/covoiturage-uhp"/>
            <property name="user" value="arnaud"/>
            <property name="password" value="*******"/>
            <property name="maxPoolSize" value="20" />
            <property name="maxStatements" value="0" />
            <property name="minPoolSize" value="5" />
        </bean>
        <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
            <property name="jpaVendorAdapter">
                <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                    <property name="showSql" value="true"/>
                    <property name="generateDdl" value="true"/>
                    <property name="database" value="POSTGRESQL" />
                    <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect"/>
                    <!-- Specific properties for Hibernate are in persistence.xml file,
                    but also can be placed here and removed from persistence.xml file. -->
                </bean>
            </property>
            <!--<property name="loadTimeWeaver">
                <bean class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver"/>
            </property>-->
            <property name="dataSource" ref="dataSource" />
            <property name="persistenceUnitName" value="covoiturage"/>
        </bean>
     
        <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
     
        <bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
            <property name="entityManagerFactory" ref="entityManagerFactory" />
        </bean>
     
        <tx:annotation-driven />
     
        <security:authentication-manager alias="authenticationManager">
            <security:authentication-provider user-service-ref="userService">
                <security:password-encoder ref="passwordEncoder" hash="sha">
                    <security:salt-source ref="saltSource"/>
                </security:password-encoder>
            </security:authentication-provider>
        </security:authentication-manager>
     
        <bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"/>
        <bean id="saltSource" class="org.springframework.security.authentication.dao.ReflectionSaltSource">
            <property name="userPropertyToUse" value="username"/>
        </bean>
    </beans>
    beans.xml
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    <?xml version="1.0" encoding="UTF-8"?>
    <beans 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/beans_1_0.xsd">
    </beans>
    faces-config.xml
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <?xml version="1.0" encoding="UTF-8"?>
    <faces-config
        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"
        version="2.0">
       <application>
            <el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
        </application>
    </faces-config>
    web.xml
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    <?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>Site web covoiturage-uhp.fr</display-name>
     
        <!-- Add Support for Spring -->
        <listener>
            <listener-class>
    		org.springframework.web.context.ContextLoaderListener
            </listener-class>
        </listener>
        <listener>
            <listener-class>
    		org.springframework.web.context.request.RequestContextListener
            </listener-class>
        </listener>
        <filter>
            <filter-name>hibernateFilter</filter-name>
            <filter-class>
                org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter
            </filter-class>
        </filter>
     
        <!-- Change to "Production" when you are ready to deploy -->
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>
        </context-param>
        <context-param>
            <param-name>javax.faces.PROJECT_STAGE</param-name>
            <param-value>Development</param-value>
        </context-param>
          <!-- Welcome page -->
        <welcome-file-list>
            <welcome-file>index.xhtml</welcome-file>
        </welcome-file-list>
        <!-- JSF mapping -->
        <servlet>
            <servlet-name>Faces Servlet</servlet-name>
            <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        </servlet>
        <!-- Map these files with JSF -->
        <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>
        <!-- Session Config -->
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
     
     
    </web-app>
    Il y a aussi un sun-web.xml, généré avec netbeans sans que je le lui demande, et je ne sais pas si j'en ai besoin
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Application Server 9.0 Servlet 2.5//EN" "http://www.sun.com/software/appserver/dtds/sun-web-app_2_5-0.dtd">
    <sun-web-app error-url="">
      <context-root>/fr.covoiturage-uhp</context-root>
      <class-loader delegate="true"/>
      <jsp-config>
        <property name="keepgenerated" value="true">
          <description>Keep a copy of the generated servlet class' java code.</description>
        </property>
      </jsp-config>
    </sun-web-app>

  2. #2
    Membre confirmé
    Profil pro
    Inscrit en
    Janvier 2011
    Messages
    92
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2011
    Messages : 92
    Par défaut
    Je ne sais pas si cela change qqch, mais mes entités, couche service et dao sont dans un jar que j'ajoute aux librairies, et tomcat les trouve d'après le log qui défile.

    Voici aussi leur implémentation pour l'objet User : (j'utilise aussi des classes génériques)

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    package fr.covoiturage.entite.user;
     
    import fr.covoiturage.entite.security.Authority;
    import fr.covoiturage.entite.security.SecUserDetails;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Date;
    import java.util.List;
    import javax.inject.Inject;
    import javax.inject.Named;
    import org.springframework.transaction.annotation.Transactional;
    import org.slf4j.LoggerFactory;
    import org.slf4j.Logger;
    import org.springframework.dao.DataAccessException;
    import org.springframework.security.authentication.dao.SaltSource;
    import org.springframework.security.authentication.encoding.PasswordEncoder;
    import org.springframework.security.core.userdetails.UserDetails;
    import org.springframework.security.core.userdetails.UserDetailsService;
    import org.springframework.security.core.userdetails.UsernameNotFoundException;
    import org.springframework.stereotype.Service;
     
    /**
     *
     * @author Gabz
     */
    @Transactional
    @Service("userService")
    public class UserServiceImpl implements UserService, UserDetailsService {
     
        @Inject
        @Named("userDao")
        private UserDAO userDao;
        final Logger log = LoggerFactory.getLogger("ServiceLogger");
     
        public UserServiceImpl() {
        }
        @Inject
        @Named("passwordEncoder")
        private PasswordEncoder passwordEncoder;
        @Inject
        @Named("saltSource")
        private SaltSource saltSource;
     
        @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException, DataAccessException {
            log.debug("loadUserByUsername with Username {}", username);
     
            try {
                User user = userDao.findByUsername(username);
                if (user == null) {
                    log.error("loadUserByUsername failed, User with Username {} not found", username);
                    throw new UsernameNotFoundException("No user found with username: " + username);
                } else {
                    log.error("loadUserByUsername successful, found {}", user);
                    return new SecUserDetails(user);
                }
            } catch (DataAccessException dae) {
                log.error("loadUserByUsername failed, User with Username {} not found, cannot retrieve date from database {}", username, dae);
                throw new UsernameNotFoundException("No user found with username: " + username, dae);
            }
     
        }
     
        @Override
        public User createUser(String firstName, String name, String username, String password) {
            log.debug("create new User");
            User user = new User();
            user.setFirstName(firstName);
            user.setName(name);
            user.setUsername(username);
            user.setPassword(passwordEncoder.encodePassword(password, username));
            user.setAuthorities(defaultAuthorities(user));
            user.setRegistrationDate(new Date());
            user.setEnabled(Boolean.FALSE);
            user.setAccountLocked(Boolean.FALSE);
            user.setCredentialsExpired(Boolean.FALSE);
     
            if (user != null) {
                log.debug("create new User successful, idUser: {}", user.getId());
                return user;
            } else {
                log.error("create new User failed");
                return null;
            }
        }
     
        private Collection<Authority> defaultAuthorities(User user) {
            log.debug("setting Default Granted authorities for new User");
            ArrayList<Authority> authList = new ArrayList<Authority>(0);
            authList.add(new Authority(user, Authority.ROLE_USER));
            return authList;
        }
     
        @Override
        public void changePassword(User user, String password) {
            log.debug("changing password of {}", user);
            try {
                SecUserDetails secUser = (SecUserDetails) loadUserByUsername(user.getUsername());
                String encodedPassword = passwordEncoder.encodePassword(password, saltSource.getSalt(secUser));
                user.setPassword(encodedPassword);
                merge(user);
                log.error("changing password of {} successful", user);
            } catch (RuntimeException e) {
                log.error("changing password of {} failed", user, e);
            }
        }
     
        @Override
        public void persist(User transientUser) {
            log.debug("persist User");
            userDao.persist(transientUser);
            log.debug("persisted: {}", transientUser);
        }
     
        @Override
        public void remove(User persistentUser) {
            log.debug("remove User");
            userDao.remove(persistentUser);
            log.debug("removed: {}", persistentUser);
        }
     
        @Override
        public void remove(Integer userId) {
            log.debug("remove User with id: {}", userId);
            remove(findById(userId));
        }
     
        @Override
        public User merge(User detachedUser) {
            log.debug("merge User");
            User user = userDao.merge(detachedUser);
            log.debug("merged: {}", detachedUser);
            return user;
        }
     
        @Override
        @Transactional(readOnly = true)
        public User findById(Integer userId) {
            log.debug("findById User with id: {}", userId);
            User user = userDao.getById(userId);
            log.debug("found: {}", user);
            return user;
        }
     
        @Override
        @Transactional(readOnly = true)
        public List<User> findByFirstName(String firstName) {
            log.debug("findByFirstName User with firstName: {}", firstName);
            List<User> users = userDao.findByFirstName(firstName);
            log.debug("found: {} users", users.size());
            return users;
        }
     
        @Override
        @Transactional(readOnly = true)
        public List<User> findByName(String name) {
            log.debug("findByName User with name {}", name);
            List<User> users = userDao.findByName(name);
            log.debug("found: {} users", users.size());
            return users;
        }
     
        @Override
        @Transactional(readOnly = true)
        public User findByUsername(String username) {
            log.debug("findByUsername User with username: {}", username);
            User user = userDao.findByUsername(username);
            log.debug("found: {}", user);
            return user;
        }
     
        @Override
        @Transactional(readOnly = true)
        public List<User> getAll() {
            log.debug("getAll");
            List<User> users = userDao.getAll();
            log.debug("found: {} users", users.size());
            return users;
        }
     
        @Override
        @Transactional(readOnly = true)
        public List<User> search(String searchString) {
            log.debug("search with searchString: {}", searchString);
            List<User> users = userDao.search(searchString);
            log.debug("found: {} users", users.size());
            return users;
        }
     
        @Override
        public User findWithContactsById(Integer userId) {
            log.debug("findWithContactsById User with id: {}", userId);
            User user = userDao.findWithContactsById(userId);
            log.debug("found: {}", user);
            return user;
        }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    package fr.covoiturage.entite.user;
     
    import fr.covoiturage.entite.GenericEntityDaoJpa;
    import java.util.ArrayList;
    import java.util.List;
    import javax.inject.Named;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    import org.slf4j.LoggerFactory;
    import org.slf4j.Logger;
    import org.springframework.transaction.annotation.Transactional;
     
    /**
     *
     * @author Gabz
     */
    @Named("userDao")
    @Transactional
    public class UserDAOJpa extends GenericEntityDaoJpa<User> implements UserDAO {
     
        @PersistenceContext
        private EntityManager em;
        final Logger log = LoggerFactory.getLogger("DAOLogger");
     
        public UserDAOJpa() {
            super(User.class);
        }
     
        @Override
        @Transactional(readOnly = true)
        public List<User> findByFirstName(String firstName) {
            log.debug("getting User instance with firstName: {}", firstName);
            firstName = "%" + firstName + "%";
            try {
                Query query = em.createQuery("select u from User u where u.firstName like :firstName");
                query.setParameter("firstName", firstName);
                List<User> users = (List<User>) query.getResultList();
                log.debug("findByFirstName successful");
                return users;
            } catch (RuntimeException e) {
                log.error("findByFirstName failed", e);
                return new ArrayList<User>();
            }
        }
     
        @Override
        @Transactional(readOnly = true)
        public List<User> findByName(String name) {
            log.debug("getting User instance with name: {}", name);
            name = "%" + name + "%";
            try {
                Query query = em.createQuery("select u from User u where u.name like :name");
                query.setParameter("name", name);
                List<User> users = (List<User>) query.getResultList();
                log.debug("findByName successful");
                return users;
            } catch (RuntimeException e) {
                log.error("findByName failed", e);
                return new ArrayList<User>();
            }
        }
     
        @Override
        @Transactional(readOnly = true)
        public List<User> search(String searchString) {
            log.debug("Search User instances with search string: {}", searchString);
            searchString = "%" + searchString + "%";
            try {
                Query query = em.createQuery("select u from User u where u.firstName like :searchstring or u.name like :searchstring");
                query.setParameter("searchstring", searchString);
                List<User> users = (List<User>) query.getResultList();
                log.debug("search successful");
                return users;
            } catch (RuntimeException e) {
                log.error("search failed", e);
                return new ArrayList<User>();
            }
        }
     
        @Override
        public User findWithContactsById(Integer userId) {
            log.debug("getting User instance and its contacts list with userId: {}", userId);
            try {
                Query query = em.createQuery("select u from User u left join fetch u.contacts where u.id = :userId");
                query.setParameter("userId", userId);
                User user = (User) query.getSingleResult();
                log.debug("findWithContactsById successful");
                return user;
            } catch (RuntimeException e) {
                log.error("findByFirstName failed", e);
                return null;
            }
        }
     
        @Override
        public User findByUsername(String username) {
            log.debug("getting User instance with username: {}", username);
            try {
                Query query = em.createQuery("select u from User u where u.username = :username");
                query.setParameter("username", username);
                User user = (User) query.getSingleResult();
                log.debug("findByUsername successful");
                return user;
            } catch (RuntimeException e) {
                log.error("findByUsername failed", e);
                return null;
            }
        }
     
     
    }

  3. #3
    Membre confirmé
    Profil pro
    Inscrit en
    Janvier 2011
    Messages
    92
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2011
    Messages : 92
    Par défaut
    Personne pour me dépanner ? J'ai visiblement un problème d'injection du service "userService" dans "userBean", ce qui doit venir de la configuration mais je ne trouve pas de solution...

  4. #4
    Membre Expert
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Juin 2007
    Messages
    2 938
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Ingénieur développement logiciels

    Informations forums :
    Inscription : Juin 2007
    Messages : 2 938
    Par défaut
    Effectivement ton pb viendrait de ton service User, il doit être Null au moment de son appel. Peux tu nous montrer l'interface et la classe d'implementation de ce service?

  5. #5
    Membre confirmé
    Profil pro
    Inscrit en
    Janvier 2011
    Messages
    92
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2011
    Messages : 92
    Par défaut
    J'ai finalement résolu mon problème, j'utilise finalement @ManagedBean@SessionScope, il devait me manquer le jar pour la jsr 330, mais j'avais cru comprendre que cela était embarqué avec spring ou jee...

    A la limite je n'ai pas encore beaucoup de classes, donc si au final j'arrivais à faire fonctionner @Named et @Scope, je ferai les modif, mais là du boulot je n'ai pas accès à mes pom.xml

Discussions similaires

  1. Réponses: 3
    Dernier message: 21/11/2011, 10h54
  2. Injection de dépendance dans un Bean (MVC)
    Par clem_alain dans le forum Java EE
    Réponses: 8
    Dernier message: 08/02/2011, 10h58
  3. Réponses: 3
    Dernier message: 28/05/2010, 14h59
  4. Weblogic 10.0 : injection d'EJB dans managed bean JSF
    Par loic38_01 dans le forum Weblogic
    Réponses: 1
    Dernier message: 05/09/2008, 13h46
  5. Réponses: 3
    Dernier message: 06/06/2007, 15h21

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo