How to create a sign-up page using JSF + Spring

Asked

Viewed 422 times

5

I am creating a user registration page but am finding the following error:

type Exception report

message Unable to create instance for class: managedBean.Cadastrobean.

Description The server encountered an Internal error that prevented it from fulfilling this request.

Exception

javax.servlet.Servletexception: Unable to create instance for the class: managedBean.CadasterBean. javax.faces.webapp.FacesServlet.service(Facesservlet.java:659) org.apache.Tomcat.websocket.server.WsFilter.doFilter(Wsfilter.java:52) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:330) org.springframework.security.web.access.intercept.Filtersecurityinterceptor.invoke(Filtersecurityinterceptor.java:118) org.springframework.security.web.access.intercept.Filtersecurityinterceptor.doFilter(Filtersecurityinterceptor.java:84) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(Exceptiontranslationfilter.java:113) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.Session.SessionManagementFilter.doFilter(Sessionmanagementfilter.java:103) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.Authentication.AnonymousAuthenticationFilter.doFilter(Anonymousauthenticationfilter.java:113) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(Securitycontextholderawarerequestfilter.java:54) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(Requestcacheawarefilter.java:45) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.Authentication.www.Basicauthenticationfilter.doFilter(Basicauthenticationfilter.java:150) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.Authentication.AbstractAuthenticationProcessingFilter.doFilter(Abstractauthenticationprocessingfilter.java:183) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.Authentication.logout.Logoutfilter.doFilter(Logoutfilter.java:105) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(Securitycontextpersistencefilter.java:87) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.Filterchainproxy.doFilterInternal(Filterchainproxy.java:192) org.springframework.security.web.Filterchainproxy.doFilter(Filterchainproxy.java:160) org.springframework.web.filter.Delegatingfilterproxy.invokeDelegate(Delegatingfilterproxy.java:237) org.springframework.web.filter.Delegatingfilterproxy.doFilter(Delegatingfilterproxy.java:167) root cause

com.sun.faces.mgbean.Managedbeancreationexception: Not possible create instance for class: managedBean.CadasterBean. com.sun.faces.mgbean.Beanbuilder.newBeanInstance(Beanbuilder.java:191) com.sun.faces.mgbean.Beanbuilder.build(Beanbuilder.java:100) com.sun.faces.mgbean.Beanmanager.createAndPush(Beanmanager.java:409) com.sun.faces.mgbean.Beanmanager.create(Beanmanager.java:269) com.sun.faces.el.Managedbeanelresolver.resolveBean(Managedbeanelresolver.java:257) com.sun.faces.el.Managedbeanelresolver.getValue(Managedbeanelresolver.java:117) com.sun.faces.el.Demuxcompositeelresolver. _getValue(Demuxcompositeelresolver.java:176) com.sun.faces.el.Demuxcompositeelresolver.getValue(Demuxcompositeelresolver.java:203) org.apache.el.parser.Astidentifier.getValue(Astidentifier.java:80) org.apache.el.parser.Astvalue.getValue(Astvalue.java:135) org.apache.el.ValueExpressionImpl.getValue(Valueexpressionimpl.java:184) com.sun.faces.facelets.el.TagValueExpression.getValue(Tagvalueexpression.java:109) javax.faces.Component.ComponentStateHelper.Eval(Componentstatehelper.java:194) javax.faces.Component.ComponentStateHelper.Eval(Componentstatehelper.java:182) javax.faces.Component.UIOutput.getValue(Uioutput.java:174) javax.faces.Component.UIInput.getValue(Uiinput.java:291) org.primefaces.util.ComponentUtils.getValueToRender(Componentutils.java:77) org.primefaces.Component.inputmask.Inputmaskrenderer.encodeMarkup(Inputmaskrenderer.java:99) org.primefaces.Component.inputmask.Inputmaskrenderer.encodeEnd(Inputmaskrenderer.java:57) javax.faces.Component.UIComponentBase.encodeEnd(Uicomponentbase.java:919) com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(Htmlbasicrenderer.java:312) com.sun.faces.renderkit.html_basic.GridRenderer.renderRow(Gridrenderer.java:185) com.sun.faces.renderkit.html_basic.GridRenderer.encodeChildren(Gridrenderer.java:129) javax.faces.Component.UIComponentBase.encodeChildren(Uicomponentbase.java:889) javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1856) javax.faces.render.Renderer.encodeChildren(Renderer.java:176) javax.faces.Component.UIComponentBase.encodeChildren(Uicomponentbase.java:889) javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1856) javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1859) javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1859) javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1859) com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(Faceletviewhandlingstrategy.java:456) com.sun.faces.application.view.MultiViewHandler.renderView(Multiviewhandler.java:133) com.sun.faces.lifecycle.Renderresponsephase.execute(Renderresponsephase.java:120) com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) com.sun.faces.lifecycle.Lifecycleimpl.render(Lifecycleimpl.java:219) javax.faces.webapp.FacesServlet.service(Facesservlet.java:647) org.apache.Tomcat.websocket.server.WsFilter.doFilter(Wsfilter.java:52) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:330) org.springframework.security.web.access.intercept.Filtersecurityinterceptor.invoke(Filtersecurityinterceptor.java:118) org.springframework.security.web.access.intercept.Filtersecurityinterceptor.doFilter(Filtersecurityinterceptor.java:84) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(Exceptiontranslationfilter.java:113) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.Session.SessionManagementFilter.doFilter(Sessionmanagementfilter.java:103)

java.lang.Classcastexception: java.lang.String cannot be cast to org.springframework.security.core.userdetails.User managedBean.UsuarioFace.getUsu(UsuarioFace.java:45) managedBean.UsuarioFace.(Usuarioface.java:34) managedBean.CadastroBean.(Cadastrobean.java:31) sun.reflect.Nativeconstructoraccessorimpl.newInstance0(Native Method) sun.reflect.Nativeconstructoraccessorimpl.newInstance(Unknown Source) sun.reflect.Delegatingconstructoraccessorimpl.newInstance(Unknown Source) java.lang.reflect.Constructor.newInstance(Unknown Source) java.lang.Class.newInstance(Unknown Source) com.sun.faces.mgbean.Beanbuilder.newBeanInstance(Beanbuilder.java:186) com.sun.faces.mgbean.Beanbuilder.build(Beanbuilder.java:100) com.sun.faces.mgbean.Beanmanager.createAndPush(Beanmanager.java:409) com.sun.faces.mgbean.Beanmanager.create(Beanmanager.java:269) com.sun.faces.el.Managedbeanelresolver.resolveBean(Managedbeanelresolver.java:257) com.sun.faces.el.Managedbeanelresolver.getValue(Managedbeanelresolver.java:117) com.sun.faces.el.Demuxcompositeelresolver. _getValue(Demuxcompositeelresolver.java:176) com.sun.faces.el.Demuxcompositeelresolver.getValue(Demuxcompositeelresolver.java:203) org.apache.el.parser.Astidentifier.getValue(Astidentifier.java:80) org.apache.el.parser.Astvalue.getValue(Astvalue.java:135) org.apache.el.ValueExpressionImpl.getValue(Valueexpressionimpl.java:184) com.sun.faces.facelets.el.TagValueExpression.getValue(Tagvalueexpression.java:109) javax.faces.Component.ComponentStateHelper.Eval(Componentstatehelper.java:194) javax.faces.Component.ComponentStateHelper.Eval(Componentstatehelper.java:182) javax.faces.Component.UIOutput.getValue(Uioutput.java:174) javax.faces.Component.UIInput.getValue(Uiinput.java:291) org.primefaces.util.ComponentUtils.getValueToRender(Componentutils.java:77) org.primefaces.Component.inputmask.Inputmaskrenderer.encodeMarkup(Inputmaskrenderer.java:99) org.primefaces.Component.inputmask.Inputmaskrenderer.encodeEnd(Inputmaskrenderer.java:57) javax.faces.Component.UIComponentBase.encodeEnd(Uicomponentbase.java:919) com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(Htmlbasicrenderer.java:312) com.sun.faces.renderkit.html_basic.GridRenderer.renderRow(Gridrenderer.java:185) com.sun.faces.renderkit.html_basic.GridRenderer.encodeChildren(Gridrenderer.java:129) javax.faces.Component.UIComponentBase.encodeChildren(Uicomponentbase.java:889) javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1856) javax.faces.render.Renderer.encodeChildren(Renderer.java:176) javax.faces.Component.UIComponentBase.encodeChildren(Uicomponentbase.java:889) javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1856) javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1859) javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1859) javax.faces.Component.UIComponent.encodeAll(Uicomponent.java:1859) com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(Faceletviewhandlingstrategy.java:456) com.sun.faces.application.view.MultiViewHandler.renderView(Multiviewhandler.java:133) com.sun.faces.lifecycle.Renderresponsephase.execute(Renderresponsephase.java:120) com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101) com.sun.faces.lifecycle.Lifecycleimpl.render(Lifecycleimpl.java:219) javax.faces.webapp.FacesServlet.service(Facesservlet.java:647) org.apache.Tomcat.websocket.server.WsFilter.doFilter(Wsfilter.java:52) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:330) org.springframework.security.web.access.intercept.Filtersecurityinterceptor.invoke(Filtersecurityinterceptor.java:118) org.springframework.security.web.access.intercept.Filtersecurityinterceptor.doFilter(Filtersecurityinterceptor.java:84) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(Exceptiontranslationfilter.java:113) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.Session.SessionManagementFilter.doFilter(Sessionmanagementfilter.java:103) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.Authentication.AnonymousAuthenticationFilter.doFilter(Anonymousauthenticationfilter.java:113) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(Securitycontextholderawarerequestfilter.java:54) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(Requestcacheawarefilter.java:45) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.Authentication.www.Basicauthenticationfilter.doFilter(Basicauthenticationfilter.java:150) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.Authentication.AbstractAuthenticationProcessingFilter.doFilter(Abstractauthenticationprocessingfilter.java:183) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.Authentication.logout.Logoutfilter.doFilter(Logoutfilter.java:105) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(Securitycontextpersistencefilter.java:87) org.springframework.security.web.Filterchainproxy$Virtualfilterchain.doFilter(Filterchainproxy.java:342) org.springframework.security.web.Filterchainproxy.doFilterInternal(Filterchainproxy.java:192) org.springframework.security.web.Filterchainproxy.doFilter(Filterchainproxy.java:160) org.springframework.web.filter.Delegatingfilterproxy.invokeDelegate(Delegatingfilterproxy.java:237) org.springframework.web.filter.Delegatingfilterproxy.doFilter(Delegatingfilterproxy.java:167)

Better describing: My application already uses the Spring Framework and works normally, but now I need to create a page for anyone to register. So in the Spring configuration I already put the page as permitAll .

But it turns out that when I access the page it returns me the error described. But when I soon on an any user already registered, and I try to access the page, access occurs normally.

My codes are as follows::

registry.xhtml

<h:body>
    <h:form id="formCadastroUsuario">
        <h:panelGrid id="panelUsuario" columns="2"
            style="margin-bottom:10px">

            <p:outputLabel for="cpf" value="CPF" />
            <p:inputMask id="cpf" value="#{cadastroBean.cpf}" mask="999.999.999-99" required="true" requiredMessage="Entre com um cpf"/>

            <h:outputLabel for="nascimento" value="Data Nascimento: " />
                            <p:calendar id="nascimento" value="#{cadastroBean.dataNascimento}" required="true" requiredMessage="Informe uma data." />

            <h:outputLabel for="pass" value="Senha" />
            <p:password id="pass" value="#{cadastroBean.novoUsuario.password}" redisplay="false" required="true"></p:password>

            <p:commandButton action="#{cadastroBean.inserirProprioUsuario}" value="Adicionar Usuário" ajax="false"/>
        </h:panelGrid>
</h:form>

java cadastre. (all getters and setters are created)

@ManagedBean(name="cadastroBean")
@SessionScoped
public class CadastroBean {

  private UsuarioDAO usuDAO = new UsuarioDAO();
  private Usuario usu;
  private Usuario novoUsuario = new Usuario();
  private String cpf;
  private Date dataNascimento;
  List<Usuario> listaUsuario = null;

  public String inserirProprioUsuario(){

    AlunoDAO alunoDAO = new AlunoDAO();
    System.out.println(cpf);
    System.out.println(dataNascimento);
    Aluno a = alunoDAO.buscaAlunoPorCpf(cpf);

    if (a != null){

        if(a.getDataNascimento().equals(getDataNascimento())) {

            if (usuDAO.getUsuarioPorMatricula(a.getMatricula()) == null){
                System.out.println("Não existe login com esse aluno");

                novoUsuario.setAluno(a);
                novoUsuario.setPassword(criptografarSenha(novoUsuario.getPassword()));


                usuDAO.inserirUsuario(novoUsuario);

                FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO,"Sucesso","Cadastro com sucesso: "+novoUsuario.getUsername());  
                FacesContext.getCurrentInstance().addMessage(null, msg);

                listaUsuario = null;
                novoUsuario = new Usuario();
            }else{
                FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO,"Aviso","Já existe um login cadastrado com essa matrícula.");  
                FacesContext.getCurrentInstance().addMessage(null, msg);
            }
        }else{
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO,"Aviso","Não existe aluno cadastrado com esse CPF.");  
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    }
    return "usuarios";
  }

security-app-context.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
                http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                http://www.springframework.org/schema/security 
                http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<global-method-security secured-annotations="enabled"
    jsr250-annotations="enabled" />
<http auto-config="true" use-expressions="true"
    access-denied-page="/negado.jsf">
    <intercept-url pattern="/login.jsf" access="permitAll" />
    <intercept-url pattern="/cadastroUsuario.jsf" access="permitAll" />
    <intercept-url pattern="/listaEditaisDisciplinas.jsf" access="isAuthenticated()" />
    <intercept-url pattern="/realizarInscricoes.jsf" access="isAuthenticated()" />
    <form-login login-page="/login.jsf" default-target-url="/realizarInscricoes.jsf"
        authentication-failure-url="/login.jsf" />
    <logout logout-success-url="/realizarInscricoes.jsf" />
</http>

<authentication-manager alias="authenticationManager">
    <authentication-provider>
        <password-encoder hash="sha-256"></password-encoder>
        <jdbc-user-service data-source-ref="dataSource"
            authorities-by-username-query="select username, tipoUsuario from usuario where username=?"
            users-by-username-query="SELECT username, password, ativo  FROM usuario WHERE username=?" />
    </authentication-provider>
</authentication-manager>

<beans:bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <beans:property name="url"
        value="jdbc:mysql://localhost:3306/monitoria" />
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <beans:property name="username" value="root" />
    <beans:property name="password" value="root" />
</beans:bean>

How to solve?

  • Weird, might show a little more of the error stack?

  • 1

    I’ll put the rest @fakarella

  • @falsarella the internet fell at the time I was posting. I put the whole stack.

  • What I don’t understand is that I don’t use the Usuarioface anywhere, and it misses it.

  • Looks like you have some filter set up. That’s where the user is used.

1 answer

1

Hail!

I still have no reputation for comment, so I’ll try to answer your question based on what you posted.

It seems the problem is access to org.springframework.security.core.userdetails.User, which is the authenticated user.

java.lang.Classcastexception: java.lang.String cannot be cast to org.springframework.security.core.userdetails.User managedBean.UsuarioFace.getUsu(UsuarioFace.java:45) managedBean.UsuarioFace. (UsuarioFace.java:34) managedBean.CadastroBean. (CadastroBean.java:31)

Works with authenticated users because there is a valid reference to User in context. Since it is an anonymous one, it is possible that this reference does not yet exist. You could post line 45 of the class UsuarioFace.java? Then I can see how this access/ conversion occurs.

To access the authenticated user via Spring Security context, I usually do something similar to this:

// AuthUtils
import org.springframework.security.core.Authentication;
(...)

public static Authentication getAuthenticationObject() {

    if ((SecurityContextHolder.getContext() == null)) {
        return null;
    }

    final Authentication authentication = 
            SecurityContextHolder.getContext().getAuthentication();

    if (authentication == null || authentication.getPrincipal() == null) {
        return null;
    }

    return authentication;

}

// recuperação do usuário autenticado
public static ApostadorUserDetails apostadorAutenticado() {
    final Authentication auth = AuthUtils.getAuthenticationObject();

    if(auth != null && auth.getPrincipal() instanceof ApostadorUserDetails) {
        return (ApostadorUserDetails) auth.getPrincipal();
    } else {
        return ApostadorUserDetails.apostadorAnonimo((AnonymousAuthenticationToken) auth);
    }
}

ApostadorUserDetails is a reference of my domain that implements org.springframework.security.core.userdetails.UserDetails. The static method apostadorAnonimo is an implementation of Null Object Pattern. This way no NPE or conversion errors occur.

See if it helps or leave a comment with more information I edit my reply.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.