My problem is quite similar to this one (How can I do Spring Security authentication from within a JSF form), but I've tried that solution and the problem still occurs.
index.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!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:h="http://java.sun.com/jsf/html">
<h:head>
<title>Info</title>
</h:head>
<h:body>
<h:form prependId="false">
<p>Usuario <h:inputText id="j_username" value="#{control.idUsuario}"/></p>
<p>Password <h:inputSecret id="j_password" value="#{control.password}"/></p>
<h:commandButton value="Entrar" action="#{control.login}" />
</h:form>
</h:body>
</html>
Control.java
#ManagedBean
#SessionScoped
public class Control implements Serializable {
private static final long serialVersionUID = 1L;
private String idUsuario;
private String password;
private UsuarioDAO usuarios;
private Usuario usuario;
public Control() {}
public String login() {
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext extenalContext = facesContext.getExternalContext();
RequestDispatcher dispatcher = ((ServletRequest)extenalContext.getRequest()).getRequestDispatcher("/j_spring_security_check");
try {
dispatcher.forward((ServletRequest)
extenalContext.getRequest(), (ServletResponse)extenalContext.getResponse());
} catch (ServletException | IOException e) {
e.printStackTrace();
}
facesContext.responseComplete();
return null;
}
public String getIdUsuario() {return idUsuario;}
public void setIdUsuario(String idUsuario) {this.idUsuario = idUsuario;}
public String getPassword() {return password;}
public void setPassword(String password) {this.password = password;}
public Usuario getUsuario() {return usuario;}
public void setUsuario(Usuario usuario) {this.usuario = usuario;}
public UsuarioDAO getUsuarios() {return usuarios;}
public void setUsuarios(UsuarioDAO usuarios) {this.usuarios = usuarios;}
}
applicationContext-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns= "http://www.springframework.org/schema/security"
xmlns:beans= "http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<http>
<intercept-url pattern="/faces/ok.xhtml" access="ROLE_ADMIN"/>
<intercept-url pattern="/faces/ko.xhtml" access="ROLE_USER"/>
<form-login
login-page="/faces/index.xhtml"
default-target-url="/login_success"
authentication-failure-url="/faces/failLogin.xhtml"
username-parameter="j_username"
password-parameter="j_password" />
<port-mappings>
<port-mapping http="8080" https="8443" /> <!-- Tomcat -->
</port-mappings>
</http>
<beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost:3306/BUsuariosSecurity" />
<beans:property name="username" value="root" />
<beans:property name="password" value="" />
</beans:bean>
<authentication-manager>
<authentication-provider>
<password-encoder hash="bcrypt" />
<jdbc-user-service data-source-ref="dataSource"
authorities-by-username-query="SELECT IdUsuario, Rol FROM TUsuarios WHERE IdUsuario = ?"
users-by-username-query="SELECT IdUsuario, PwUsuario, Habilitado FROM TUsuarios WHERE IdUsuario = ?" />
</authentication-provider>
</authentication-manager>
</beans:beans>
When I try to login with a valid user, it sends me to failLogin.xhtml
My DataBase: https://gyazo.com/3997921c1c9bc2787a25c9b0ff904f4b
What's my mistake?
Any help please?
The problem was that the passwords in the DB were not well encrypted, I tried to encrypt them with another website and I went all.
Related
I am using spring security in my website, but when I used custom login form (JSF form), and user entered bad credentials, authentication-failure-url is not working and user is not forwarded to failed.xhtml, but index.xhtml is appeared
I don't know the reason, please help:
applicationContext.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"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
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-4.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">
<context:component-scan base-package="com.myspring" />
<context:annotation-config />
<!-- beans configuration -->
<beans:bean id="userBo" class="com.myspring.user.bo.impl.UserBoImpl" />
<!-- security configuration -->
<http auto-config="true">
<intercept-url pattern="/login.xhtml" access="permitAll" />
<intercept-url pattern="/index.xhtml" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/authenticated.xhtml" access="hasRole('ROLE_USER')" />
<intercept-url pattern="/views/admin/**" access="hasRole('ROLE_USER')" />
<form-login login-page="/login.xhtml" default-target-url="/authenticated.xhtml"
authentication-failure-url="/failed.xhtml" />
<logout invalidate-session="true" delete-cookies="true" logout-success-url="/"/>
<csrf disabled="true" />
</http>
<authentication-manager alias="authenticationManager">
<authentication-provider>
<user-service>
<user name="user1" password="user1Pass" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
login.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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
</h:head>
<h:body>
<div style="">
<h:form id="loginFormId" prependId="false">
<div id="loginFieldsPnlId">
<div id="loginFieldUsrContId">
<h:outputText id="outTxtUserNameId" value="Username: "
name="outTxtUserNameNm"></h:outputText>
<h:inputText id="userName" required="true"
value="#{loginController.userName}"
requiredMessage="Please enter username"></h:inputText>
<h:outputLabel id="outLblUserNameId" for="userName"
name="outLblUserNameNm"></h:outputLabel>
</div>
<div id="loginFieldPassContId">
<h:outputText id="outTxtPasswordId" value="Password: "
name="outTxtPasswordNm"></h:outputText>
<h:inputSecret id="password" required="true"
value="#{loginController.password}"
requiredMessage="Please enter password" name="inTxtPasswordNm"></h:inputSecret>
<h:outputLabel id="outLblPasswordId" for="password"
name="outLblPasswordNm"></h:outputLabel>
</div>
</div>
<div id="loginBtnPanelId">
<h:commandButton id="btnLoginId" value="Login"
action="#{loginController.login}" styleClass="loginPanelBtn"></h:commandButton>
<h:commandButton id="btnCancelId" value="Cancel"
action="#{loginController.cancel}" styleClass="loginPanelBtn"
immediate="true" update="loginFormId"></h:commandButton>
</div>
</h:form>
</div>
<div>
<h:messages></h:messages>
</div>
</h:body>
</html>
and this is the loginController with login method:
package com.myspring.controllers;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
#ManagedBean
#SessionScoped
public class LoginController {
private String userName;
private String password;
#ManagedProperty(value="#{authenticationManager}")
private AuthenticationManager authenticationManager = null;
public String login() {
try {
Authentication request = new UsernamePasswordAuthenticationToken(this.getUserName(), this.getPassword());
Authentication result = authenticationManager.authenticate(request);
SecurityContextHolder.getContext().setAuthentication(result);
} catch (AuthenticationException e) {
e.printStackTrace();
return "failed";
}
return "success";
}
public String logout(){
SecurityContextHolder.clearContext();
return "loggedout";
}
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
public void setAuthenticationManager(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
public String cancel()
{
return "";
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
also I will add project structure:
Due to the fact that you are using JSF you are basically bypassing the login (and logout) functionality provided by Spring Security. Your LoginController is basically replacing that, due to that your sec:login-form and sec:legato are pretty much useless.
The solution is simple don't use JSF, you can still use Facelets to render your page, but simply include a normal form tag which posts to /login instead of an h:form tag and you can remove your LoginController.
Note: If your application is not the root application (i.e. mapped to /) you need to include the /context-path into your URL. So instead of /login use /context-path/login.
<!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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
</h:head>
<h:body>
<div style="">
<form id="loginFormId" method="post" action="/login">
<div id="loginFieldsPnlId">
<div id="loginFieldUsrContId">
<label>Username:<label>
<input type="text" id="username" name="username" />
</div>
<div id="loginFieldPassContId">
<label>Password:<label>
<input type="password" id="password" name="password" />
</div>
</div>
<div id="loginBtnPanelId">
<button>Login</button>
</div>
</form>
</div>
</h:body>
</html>
If you still want to use JSF and the LoginController then don't directly use the AuthenticationManager but forward the request to the /login URL that way Spring Security will take over after JSF has done the required validation.
I have trouble in spring security 3.1.
I'm going to use spring security openid-login with gmail, and I want to get user information using attribute-exchange. but if I use it, it is always called when user log-in my website.
How can i call only once at user sign-in my website?
I managed sign-in at openIdAuthFailureHandler, and I want to get user information in this bean...please help me!
(I found security:remember-me, but it doesn't work..)
security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
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.1.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<security:global-method-security
secured-annotations="enabled" proxy-target-class="true" />
<security:http auto-config="true" access-denied-page="/denied/accessDenied">
<security:intercept-url pattern="/admin/**"
access="ROLE_ADMIN" />
<security:intercept-url pattern="/reservation/**"
access="ROLE_USER, ROLE_ADMIN" />
<security:intercept-url pattern="/board/**"
access="ROLE_ADMIN, ROLE_USER" />
<security:openid-login login-page="/"
login-processing-url="/j_spring_openid_security_check.do"
authentication-success-handler-ref="customAuthenticationHandler"
authentication-failure-handler-ref="openIdAuthFailureHandler">
<security:attribute-exchange identifier-match="https://www.google.com/.*" >
<security:openid-attribute name="email" type="http://schema.openid.net/contact/email" required="true" />
<security:openid-attribute name="firstname" type="http://axschema.org/namePerson/first" required="true" />
</security:attribute-exchange>
</security:openid-login>
<security:logout logout-url="/j_spring_openid_security_logout.do"
logout-success-url="/" invalidate-session="true" />
<!-- <security:http-basic /> -->
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<!-- <security:user-service properties="/WEB-INF/resources/users.xml"
/> -->
<security:password-encoder ref="passwordEncoder" />
<security:jdbc-user-service id="userDetailsService"
data-source-ref="dataSource"
users-by-username-query="SELECT id as id, passwd as passwd, 1 as enabled FROM user WHERE id=?"
authorities-by-username-query="SELECT id as id, power as authority FROM user WHERE id=?" />
<!-- <security:password-encoder hash="sha-256"></security:password-encoder> -->
</security:authentication-provider>
</security:authentication-manager>
<bean id="customTokenRepository" class="com.jinyoung.reservation.openid.CustomTokenRepository" />
<bean id="openIdAuthFailureHandler" class="com.jinyoung.reservation.openid.OpenIDAuthenticationFailureHandler"/>
<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder" />
</beans>
OpenIDAuthenticationFailureHandler
public class OpenIDAuthenticationFailureHandler extends
SimpleUrlAuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException exception)
throws IOException, ServletException {
if (exception instanceof UsernameNotFoundException && exception.getAuthentication() instanceof OpenIDAuthenticationToken && ((OpenIDAuthenticationToken) exception.getAuthentication()).getStatus().equals(OpenIDAuthenticationStatus.SUCCESS)) {
DefaultRedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
request.getSession(true).setAttribute("USER_OPENID_CREDENTIAL", ((UsernameNotFoundException)exception).getExtraInformation());
OpenIDAuthenticationToken openIdAuth = (OpenIDAuthenticationToken)exception.getAuthentication();
request.getSession(true).setAttribute("USER_OPENID_CREDENTIAL_EXTRA", openIdAuth);
for(OpenIDAttribute attr : openIdAuth.getAttributes()) {
System.out.printf("AX Attribute: %s, Type: %s, Count: %d\n", attr.getName(), attr.getType(), attr.getCount());
for(String value : attr.getValues()) {
System.out.printf(" Value: %s\n", value);
}
}
redirectStrategy.sendRedirect(request, response, "/login/registrationOpenid");
// redirect to create account page
/*redirectStrategy.sendRedirect(request, response,
"/?fail=true");*/
} else {
super.onAuthenticationFailure(request, response, exception);
}
}
}
Ran in to a similar problem which I solved by having two different form targets (j_spring_openid_security_check_signup and j_spring_openid_security_check) for the signup/login page. One used when signing up and one when logging in. In spring-security.xml we use two different configs, one that asks for attributes and one that don't:
<!-- Configure attribute-exchange for signup -->
<!-- will only match /j_spring_openid_security_check_signup -->
<security:http auto-config="true" use-expressions="true" path-type="ant" pattern="/j_spring_openid_security_check_signup">
<security:openid-login
login-processing-url="/j_spring_openid_security_check_signup"
user-service-ref="userDetailsService"
authentication-failure-handler-ref="authenticationFailureHandler"
authentication-success-handler-ref="authenticationSuccessHandler">
<security:attribute-exchange identifier-match="https://www.google.com/.*" >
<security:openid-attribute name="email" type="http://schema.openid.net/contact/email" required="true" />
<security:openid-attribute name="firstname" type="http://axschema.org/namePerson/first" required="true" />
</security:attribute-exchange>
</security:openid-login>
</security:http>
<!-- Skip attribute-exchange at log-in -->
<!-- match everything else -->
<security:http auto-config="true" use-expressions="true" path-type="ant">
<security:openid-login
login-processing-url="/j_spring_openid_security_check"
user-service-ref="userDetailsService"
authentication-failure-handler-ref="authenticationFailureHandler"
authentication-success-handler-ref="authenticationSuccessHandler"
/>
</security:http>
Then in the authenticationSuccessHandler you will have access to attributes while signing in but not at log-in.
-------------------------------I solved!!!------------------------------------------
I modified spring-security-openid-3.1.1.RELEASE.jar, and I call attribute-change only once at user access my site first time. if one who want to know, give me e-mail kjy30532#gmail.com !
I searched some examples but i couldn't found any example. What I must do in loginController.login() method. How can I pass username and password text to spring-security?
Spring-security.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.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/pages/login.xhtml*" access="permitAll"/>
<intercept-url pattern="/**" access="hasRole('admin')" />
<form-login login-page='/pages/login.xhtml' default-target-url="/pages/index.xhtml"
authentication-failure-url="/pages/login.xhtml"/>
<logout logout-success-url="/pages/logout.xhtml" />
</http>
<!--Authentication Manager Details -->
<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="customUserDetailsService">
<password-encoder hash="md5"/>
</authentication-provider>
</authentication-manager>
My view login.xhtml
<?xml version='1.0' encoding='UTF-8' ?>
<!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:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>User Login</title>
</h:head>
<h:body>
<h:form id="loginFormId">
<p:outputPanel id="loginOutputPanelId">
<p:panelGrid id="loginInformationPanel" columns="2">
<h:outputText value="Username: "/>
<p:inputText value="#{loginController.userName}"/>
<h:outputText value="Password: "/>
<p:inputText value="#{loginController.password}"/>
</p:panelGrid>
<p:commandButton value="Login" actionListener="#{loginController.login()}"/>
</p:outputPanel>
</h:form>
</h:body>
Personally I use this way to set Spring-Security context values:
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
//....
//In your login method:
List<Authority> auths = new ArrayList<Authority>();
auths.add(new Authority("ROLE_USER")); //Role here, like "admin"
Authentication authentication = new UsernamePasswordAuthenticationToken(token, null, auths);
SecurityContextHolder.getContext().setAuthentication(authentication);
The Authority class is as follow:
import org.springframework.security.core.GrantedAuthority;
public class Authority implements GrantedAuthority{
private static final long serialVersionUID = 9170140593525051237L;
private String authority;
public Authority(String authority) {
super();
this.authority = authority;
}
#Override
public String getAuthority() {
return authority;
}
#Override
public String toString() {
return "Authority [authority=" + authority + "]";
}
}
I hope this helps
You can you Pricipal object to get the user details as shown below.
login(Principal principal){
if (principal instanceof UsernamePasswordAuthenticationToken) {
UsernamePasswordAuthenticationToken userDetails = (UsernamePasswordAuthenticationToken) principal;
userDetails.getName();
}
I trying find solution but noone work. i've some spring security configs and frontend written in JSF. I found some configs in intenter but together they dont wanna work
<http>
<intercept-url pattern="/index*" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/javax.faces.resource/**"
access="IS_AUTHENTICATED_ANONYMOUSLY" />
<intercept-url pattern="/**" access="ROLE_USER" />
<intercept-url pattern="/admin/*" access="ROLE_SUPERVISOR" />
<form-login login-page="/index.html" default-target-url="/home.html"
always-use-default-target="true" authentication-failure-url="/index.xhtml?login_error=1" />
<logout logout-url="/logout.html" />
</http>
and:
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="admin" authorities="ROLE_USER, ROLE_SUPERVISOR" />
<user name="anonim" password="anonim" authorities="" />
<user name="user" password="user" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
I'd like to make some custom class that will be like custom logger i found solution that will be similar these:
public class LoginBeenController {
private static final Logger LOGGER = Logger.getLogger(LoginBeenController.class);
private String login;
private String password;
#Autowired
private AuthenticationManager authenticationManager;
public LoginBeenController() {
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public void setLogin(String login) {
this.login = login;
}
public void setPassword(String password) {
this.password = password;
}
public String login(){
Authentication authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(
this.login, this.password));
if (authentication.isAuthenticated()) {
SecurityContextHolder.getContext().setAuthentication(
authentication);
}
return new String();
}
}
Here is prime form:
<h:form>
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="username" name='j_username' value="Username:" />
<p:inputText id="username" value="#{loginBeenController.login}" required="true" label="username" />
<h:outputLabel for="password" value="Password:" />
<h:inputSecret id="password" value='#{loginBeenController.password}' required="true" label="password" />
<f:facet name="footer">
<p:commandButton ajax='false' id="loginButton" value="Login" action="#{loginBeenController.login()}" />
</f:facet>
</h:panelGrid>
</h:form>
Ok I found solution i had to add only:
#Autowired
#Qualifier("authenticationManager")
AuthenticationManager authenticationManager;
You should be forwarding to Spring Security authentication URL instead of using the AuthenticationManager. Try this:
public String doLogin() throws ServletException, IOException {
FacesContext context = FacesContext.getCurrentInstance();
String springCheckUrl = this.buildSpringSecurityCheckUrl();
HttpServletRequest request = (HttpServletRequest) context
.getExternalContext().getRequest();
RequestDispatcher dispatcher = request
.getRequestDispatcher(springCheckUrl);
dispatcher.forward((ServletRequest) request,
(ServletResponse) context.getExternalContext.getResponse());
context.responseComplete();
return null;
}
private String buildSpringSecurityCheckUrl() {
StringBuilder springCheckUrl = new StringBuilder(
"/j_spring_security_check").append("?").append("j_username")
.append("=").append(this.userName.trim()).append("&")
.append("j_password").append("=")
.append(this.userPassword.trim());
return springCheckUrl.toString();
}
}
i currently hang up in the Spring and JSF Integration. I think i misconfigured something and i can not see what exactly. I get a NULL Pointer Exception because of the Service Tier is not going to be loaded by the JSF Bean. My configuration is the following:
Stacktrace
java.lang.NullPointerException
at com.speterit.auftragssystem.beans.MitarbeiterBean.getMitarbeiterList(MitarbeiterBean.java:27)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:484)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:161)
at org.apache.el.parser.AstValue.getValue(AstValue.java:159)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:189)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:106)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
at javax.faces.component.UIData.getValue(UIData.java:553)
at javax.faces.component.UIData.getDataModel(UIData.java:1293)
at javax.faces.component.UIData.setRowIndex(UIData.java:446)
at com.sun.faces.renderkit.html_basic.TableRenderer.encodeBegin(TableRenderer.java:77)
at javax.faces.component.UIComponentBase.encodeBegin(UIComponentBase.java:824)
at javax.faces.component.UIData.encodeBegin(UIData.java:936)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1661)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1666)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1666)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:389)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:127)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:117)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:135)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:335)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1001)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:585)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:679)
default.xhtml
<?xml version="1.0" encoding="UTF-8" ?>
<!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:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<h:head>
</h:head>
</head>
<h:body>
#{mitarbeiterBean.getServiceMitarbeiter() ne null ? "true" : "false"}<br />
<h:dataTable value="#{mitarbeiterBean.getMitarbeiterList()}" var="m">
<h:column>
<f:facet name="header">Vorname</f:facet>
#{m.vorname}
</h:column>
<h:column>
<f:facet name="header">Nachname</f:facet>
#{m.nachname}
</h:column>
<h:column>
<f:facet name="header">Geburtsdatum</f:facet>
#{m.geburtsdatum}
</h:column>
</h:dataTable>
</h:body>
The evaluation #{mitarbeiterBean.getServiceMitarbeiter() ne null ? "true" : "false"}<br /> is giving false when I execute the code without the datatable part.
MitarbeiterBean.java
package com.speterit.auftragssystem.beans;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import com.speterit.auftragssystem.data.model.Mitarbeiter;
import com.speterit.auftragssystem.data.service.IServiceMitarbeiter;
#ManagedBean(name = "mitarbeiterBean")
#RequestScoped
public class MitarbeiterBean implements Serializable
{
private static final long serialVersionUID = 1L;
public IServiceMitarbeiter serviceMitarbeiter;
public String vorname;
public String nachname;
public Date geburtsdatum;
public List<Mitarbeiter> getMitarbeiterList()
{
return getServiceMitarbeiter().retrieveAllMitarbeiter();
}
public void addMitarbeiter()
{
Mitarbeiter mitarbeiter = new Mitarbeiter(getVorname(), getNachname(),
getGeburtsdatum());
getServiceMitarbeiter().createMitarbeiter(mitarbeiter);
clearForm();
}
public void clearForm()
{
setVorname("");
setNachname("");
setGeburtsdatum(null);
}
public String getVorname()
{
return vorname;
}
public void setVorname(String vorname)
{
this.vorname = vorname;
}
public String getNachname()
{
return nachname;
}
public void setNachname(String nachname)
{
this.nachname = nachname;
}
public Date getGeburtsdatum()
{
return geburtsdatum;
}
public void setGeburtsdatum(Date geburtsdatum)
{
this.geburtsdatum = geburtsdatum;
}
public IServiceMitarbeiter getServiceMitarbeiter()
{
return serviceMitarbeiter;
}
public void setServiceMitarbeiter(IServiceMitarbeiter serviceMitarbeiter)
{
this.serviceMitarbeiter = serviceMitarbeiter;
}
}
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" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Hibernate -->
<beans:bean id="hibernateSessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<beans:property name="configLocation" value="classpath:hibernate.cfg.xml" />
<beans:property name="configurationClass"
value="org.hibernate.cfg.AnnotationConfiguration" />
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect
</beans:prop>
<beans:prop key="hibernate.c3p0.min_size">5</beans:prop>
<beans:prop key="hibernate.c3p0.max_size">20</beans:prop>
<beans:prop key="hibernate.c3p0.timeout">1800</beans:prop>
<beans:prop key="hibernate.c3p0.max_statements">50</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<beans:bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="hibernateSessionFactory" />
</beans:bean>
<!-- Model Declaration -->
<beans:bean id="Mitarbeiter" class="com.speterit.auftragssystem.data.model.Mitarbeiter"/>
<!-- DAO Declaration -->
<beans:bean id="DaoMitarbeiter" class="com.speterit.auftragssystem.data.dao.DaoMitarbeiter">
<beans:property name="sessionFactory" ref="SessionFactory" />
</beans:bean>
<!-- Service Declaration -->
<beans:bean id="ServiceMitarbeiter" class="com.speterit.auftragssystem.data.service.ServiceMitarbeiter">
<beans:property name="daoMitarbeiter" ref="DaoMitarbeiter" />
</beans:bean>
faces-config.xml
<?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>
<managed-bean>
<managed-bean-name>mitarbeiterBean</managed-bean-name>
<managed-bean-class>com.speterit.auftragssystem.beans.MitarbeiterBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>serviceMitarbeiter</property-name>
<value>#{ServiceMitarbeiter}</value>
</managed-property>
</managed-bean>
</faces-config>
IServiceMitarbeiter.java
package com.speterit.auftragssystem.data.service;
import java.util.List;
import com.speterit.auftragssystem.data.dao.IDaoMitarbeiter;
import com.speterit.auftragssystem.data.model.Mitarbeiter;
public interface IServiceMitarbeiter
{
public List<Mitarbeiter> retrieveAllMitarbeiter();
public Mitarbeiter retrieveMitarbeiter(long personalnummer);
public Mitarbeiter createMitarbeiter(Mitarbeiter mitarbeiter);
public Mitarbeiter updateMitarbeiter(Mitarbeiter mitarbeiter);
public IDaoMitarbeiter getDaoMitarbeiter();
public void setDaoMitarbeiter(IDaoMitarbeiter daoMitarbeiter);
}
ServiceMitarbeiter.java
package com.speterit.auftragssystem.data.service;
import java.util.List;
import org.springframework.transaction.annotation.Transactional;
import com.speterit.auftragssystem.data.dao.IDaoMitarbeiter;
import com.speterit.auftragssystem.data.model.Mitarbeiter;
#Transactional(readOnly = true)
public class ServiceMitarbeiter implements IServiceMitarbeiter
{
IDaoMitarbeiter daoMitarbeiter;
#Transactional(readOnly = true)
public List<Mitarbeiter> retrieveAllMitarbeiter()
{
return daoMitarbeiter.getAll();
}
#Transactional(readOnly = true)
public Mitarbeiter retrieveMitarbeiter(long personalnummer)
{
return daoMitarbeiter.getByPersonalnummer(personalnummer);
}
#Transactional(readOnly = false)
public Mitarbeiter createMitarbeiter(Mitarbeiter mitarbeiter)
{
return daoMitarbeiter.create(mitarbeiter);
}
#Transactional(readOnly = false)
public Mitarbeiter updateMitarbeiter(Mitarbeiter mitarbeiter)
{
return daoMitarbeiter.persistOrMerge(mitarbeiter);
}
public IDaoMitarbeiter getDaoMitarbeiter()
{
return daoMitarbeiter;
}
public void setDaoMitarbeiter(IDaoMitarbeiter daoMitarbeiter)
{
this.daoMitarbeiter = daoMitarbeiter;
}
}
I'm happy for every fast clue :) Because i got no idea anymore
With org.springframework.web.jsf.el.SpringBeanFacesELResolver your class needs to be a
simple Spring component. Remove #ManagedBean and add #Component annotations.
You've created another instance of MitarbeiterBean managed by JSF via #ManagedBean annotation and it is not the same bean that is managed by Spring so the serviceMitarbeiter field is not injected. Just forget about JSF managed beans and use Spring components in JSF.
Also replace javax.faces.bean sope annotations with Spring #Scope.
e.g. #RequestScoped -> #Scope("request")