I want to use j_security_check authentication in order to validate the user credentials.
Basically what I am trying to achieve is when the user press submit then in case he is using wrong credentials then a message (p:growl) will show and if it’s successful then the dialog will closed.
There are many examples in the web but unfortunately I still can’t understand how to complete this puzzle :(
In my project I am using primefaces 4.0 & weblogic 10.3.2.0 (JAVA EE 5).
some code example:
<p:dialog id="dialog" widgetVar="dlg" resizable="false">
<h:form id="fLogin" prependId="false"
onsubmit="document.getElementById('fLogin').action = 'j_security_check';">
<h:panelGrid columns="2" cellpadding="5">
<h:outputLabel for="j_username" value="Username:" />
<p:inputText value="#{expBean.username}"
id="j_username" label="username"/>
<h:outputLabel for="j_password" value="Password:" />
<h:inputSecret value="#{expBean.password}"
id="j_password" label="password"/>
<p:commandButton id="submitButton"
value="Submit"
actionListener="#{expBean.run}" />
</h:panelGrid>
</h:form>
</p:dialog>
web.xml
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>main</web-resource-name>
<description/>
<url-pattern>main.jsf</url-pattern>
<http-method>POST</http-method>
</web-resource-collection>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>my-realm</realm-name>
</login-config>
<security-role>
<description/>
<role-name>MyRole</role-name>
</security-role>
exeBean:
public void run() {
FacesContext facesContext = FacesContext.getCurrentInstance();
}
Any guidelines and useful example will be much appreciated
Thanks
You were submitting the form by PrimeFaces ajax. That's why it fails. The j_security_check handler doesn't understand incoming JSF/PrimeFaces-flavored ajax requests and can't handle them appropriately by returning the desired XML response. It has to be a regular (synchronous) submit.
Turn off the ajax thing:
<p:commandButton ... ajax="false" />
By the way, your form declaration is clumsy. Just use <form> instead of <h:form>.
<form id="fLogin" action="j_security_check">
after experimenting some strategy, i choose not to use j_security_check and implement auth this way:
#ManagedBean
#ViewScoped
public class AuthBean implements Serializable
{
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(AuthBean.class);
#EJB
private PersistenceService service;
#ManagedProperty("#{user}")
private UserBean userBean;
private String email;
private String password;
private String originalURL;
#PostConstruct
public void init()
{
logger.debug("called");
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
originalURL = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);
if(originalURL == null)
{
originalURL = externalContext.getRequestContextPath();
}
else
{
String originalQuery = (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);
if(originalQuery != null)
{
originalURL += "?" + originalQuery;
}
}
logger.debug("originalURL: {}", originalURL);
}
public void login() throws IOException
{
logger.debug("called");
logger.debug("originalURL: {}", originalURL);
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext externalContext = context.getExternalContext();
HttpServletRequest request = (HttpServletRequest) externalContext.getRequest();
try
{
request.login(email, password);
}
catch(ServletException e)
{
JsfUtils.addErrorMessage(e, "authentication failed");
return;
}
Person person = service.queryOne(Person.class, "SELECT x FROM Person x WHERE x.email = ?1", email);
if(person == null)
{
JsfUtils.addErrorMessage("authorization failed");
return;
}
userBean.setPerson(person);
externalContext.redirect(originalURL);
}
public void logout() throws IOException
{
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
externalContext.invalidateSession();
externalContext.redirect(externalContext.getRequestContextPath());
}
// getters/setters
}
using this form inside /login.xhtml:
<h:form>
<p:panel header="#{bundle.login}">
<h:panelGrid columns="3">
<h:outputLabel for="email" value="#{bundle.email}" />
<h:outputLabel for="password" value="#{bundle.password}" />
<h:panelGroup />
<p:inputText id="email" value="#{authBean.email}" label="#{bundle.email}" size="32" />
<p:password id="password" value="#{authBean.password}" label="#{bundle.password}" feedback="false" size="32" />
<p:commandButton value="#{bundle.login}" action="#{authBean.login}" icon="ui-icon ui-icon-check" />
</h:panelGrid>
</p:panel>
</h:form>
and this login-config:
<login-config>
<auth-method>FORM</auth-method>
<realm-name>some-realm-name</realm-name>
<form-login-config>
<form-login-page>/login.jsf</form-login-page>
<form-error-page>/login.jsf</form-error-page>
</form-login-config>
</login-config>
Related
I am facing weird issue in jsf inputText. On browser it is showing the manage bean name and the variable name in input box (i.e. #{loginModel.userName}). the following is my jsf page code
<body>
<f:view>
<h:form>
<h:outputLabel value="Username"></h:outputLabel>
<h:inputText value="#{loginModel.userName}"></h:inputText>
<h:outputLabel value="Password"></h:outputLabel>
<h:inputSecret value="#{loginModel.password}"></h:inputSecret>
<h:commandButton value="Submit" action="#{loginModel.process}" ></h:commandButton>
</h:form>
</f:view>
</body>
My manage bean code is
public class LoginModel {
private String userName;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String process(){
System.out.println("Logged in user id is "+this.getUserName()+" and password to access is "+this.getPassword());
return "Submit";
}
}
and my faces-config.xml file
<managed-bean>
<managed-bean-name>loginModel</managed-bean-name>
<managed-bean-class>net.varun.dto.LoginModel</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
and following is my output on browser as well as i am getting null when i click on submit button
try the following code:
Change your h:commandButton for the primefaces process, partialSubmit and ajax
<body>
<f:view>
<h:form>
<h:outputLabel value="Username"></h:outputLabel>
<h:inputText value="#{loginModel.userName}"></h:inputText>
<h:outputLabel value="Password"></h:outputLabel>
<h:inputSecret value="#{loginModel.password}"></h:inputSecret>
<p:commandButton value="Submit" action="#{loginModel.process}" process="#form" partialSubmit="true" ajax="true" />
</h:form>
</f:view>
</body>
So you can put a breakpoint in your process method for see the update values.
In my custom component, I have
<composite:interface>
<composite:editableValueHolder name="val_pwd" targets="form:pwd"/>
<composite:attribute name="name" required="true"/>
.....
</composite:interface>
<composite:implementation>
<h:form id="form">
<h:panelGrid columns="3">
<h:outputText value="#{cc.attrs.namePrompt}" />
<h:inputText value="#{cc.attrs.name}" id="name"/>
<h:outputText value="#{cc.attrs.passwordPrompt}" />
<h:inputSecret value="#{cc.attrs.pwd}" id="pwd"/>
<h:commandButton value="#{cc.attrs.submitButtonValue}" action="#{cc.attrs.actionMethod}"/>
</h:panelGrid>
</h:form>
</composite:implementation>
I have a validator,
#FacesValidator("passwordVal")
public class PasswordValidator implements Validator {
public PasswordValidator() {
super();
}
#Override
public void validate(FacesContext facesContext, UIComponent uIComponent, Object object) throws ValidatorException {
if(object instanceof String){
String s = (String) object;
if(s.contains("#"))
throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error","Password cannot have #"));
}
}
}
In my JSF page, I have
<h:body>
<util:ccwithcustomval namePrompt="r_Name" passwordPrompt="r_pwd" name="#{person.name}"
pwd="#{person.pwd}" actionMethod="#{person.action}" submitButtonValue="r_submit">
<f:validateLength for="val_name" maximum="5"/>
<f:validator validatorId="passwordVal" for="val_pwd" />
</util:ccwithcustomval>
</h:body>
However, it fails with exception
InputComponent.xhtml #12,60 <f:validator> ADF_FACES-60085:Parent not an instance of
EditableValueHolder: javax.faces.component.UINamingContainer#4e18afaa
The problem is with my validator, if I comment it out the page displays
I have a view that display a list of users, from this view I can go to another view of "details" of any selected user. In the details view I need to select some values from 2 select list and then in the backed bean take these values, and add them to an user to finally store (update) the user in the database. These are my methods in the "user Bean".
With this method I get the user id from the "list of users view" and retrieve the user from the database to display its info on the details view.
public void getParam(){
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map<String, String> parameterMap = (Map<String, String>) externalContext.getRequestParameterMap();
Long param = Long.valueOf(parameterMap.get("id_usuario"));
System.out.println(param);
this.setU(controlador.getUser(param));
}
With this method I set the values from the select list to an object and then I add this object to the user, finally I save it on the database.
public void setPrivilegio(){
System.out.println("hola");
Privilegio pri=new Privilegio();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map parameterMap = externalContext.getRequestParameterMap();
Agrupacion agrupacion= (Agrupacion)parameterMap.get("agrup");
System.out.println(agrupacion.getNombre());
Rol rol = (Rol)parameterMap.get("rols");
System.out.println(rol.getNombre());
System.out.println(""+rol.getNombre()+" "+agrupacion.getNombre());
pri.setRol(rol);
pri.setAgrupacion(agrupacion);
pri.setActive(true);
this.getU().addPrivilegio(pri);
controlador.saveUsuario(this.getU());
}
This is my view:
<?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">
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<div class="container">
<h:panelGroup id="Usuarios">
<h:form id="FormUsuarios">
<h2>Detalles Usuario</h2>
<h:dataTable id="users" value="#{usuario.u}" styleClass="table table-striped table-bordered" headerClass="sorting_asc"
rowClasses="odd,even">
<h:column>
<f:facet name="header">#</f:facet>
#{usuario.u.id}
</h:column>
<h:column>
<f:facet name="header">Identificador</f:facet>
<h:inputText id="identificador" value="#{usuario.u.identificador}" />
</h:column>
<h:column>
<f:facet name="header">Nombre</f:facet>
<h:inputText id="nombres" value=" #{usuario.u.nombres}"/> <h:inputText id="apellidoP" value=" #{usuario.u.apellidoPaterno}"/> <h:inputText id="apellidoM" value=" #{usuario.u.apellidoMaterno}"/>
</h:column>
<h:column>
<f:facet name="header">Active</f:facet>
<h:selectBooleanCheckbox id="check" value="#{usuario.u.active}"></h:selectBooleanCheckbox>
</h:column>
</h:dataTable>
<h3>Asignar Privilegios</h3>
<h:selectOneMenu id="agrup" value="#{usuario.selected}" converter="omnifaces.SelectItemsConverter">
<f:selectItems value="#{agrupacion.agrupacion}" var="entity" itemLabel="#{entity.nombre}" itemValue="#{entity.id}"/>
</h:selectOneMenu>
<h:selectOneMenu id="rols" value="#{rol.selected}" converter="omnifaces.SelectItemsConverter">
<f:selectItems value="#{rol.roles}" var="rol" itemLabel="#{rol.nombre}" itemValue="#{rol.id}"/>
</h:selectOneMenu>
<h:commandButton value="Asignar" styleClass="btn-primary" actionListener="#{usuario.setPrivilegio}">
</h:commandButton>
<h3>Privilegios Asignados:</h3>
<h:dataTable id="privilegios" value="#{usuario.u.privilegios}" var="p" styleClass="table table-striped table-bordered" headerClass="sorting_asc"
rowClasses="odd,even">
<h:column>
<f:facet name="header">#</f:facet>
#{p.id}
</h:column>
<h:column>
<f:facet name="header">Roles</f:facet>
#{p.rol.nombre}
</h:column>
<h:column>
<f:facet name="header">Grupos</f:facet>
#{p.agrupacion.nombre}
</h:column>
<h:column>
<f:facet name="header">Active</f:facet>
<h:selectBooleanCheckbox id="checkbox" value="#{p.active}"></h:selectBooleanCheckbox>
</h:column>
</h:dataTable>
</h:form>
<script type="text/javascript" src="js/paging-bootstrap.js"></script>
<script type="text/javascript" src="js/contenidoc.datatable.init.js"></script>
</h:panelGroup>
</div>
</ui:composition>
When I click on my commandbutton called "Asignar" that calls the method setPrivilegio(), I get this error:
java.lang.NumberFormatException: null
at java.lang.Long.parseLong(Long.java:404)
at java.lang.Long.valueOf(Long.java:540)
at cl.uchile.sti.bean.UsuarioBean.getParam(UsuarioBean.java:114)
The tables in the view shows all the info, but when I want to call the method that add the selected items to the user and save it on the database (setPrivilegio) I get this error.
How is this caused and how can I solve it?
This is my full "user bean":
#ManagedBean(name = "usuario")
#ViewScoped
public class UsuarioBean {
private usuarioController controlador;
private Usuario u=new Usuario();
private Privilegio Selected=new Privilegio();
private Boolean active;
private long id_user;
#PostConstruct
public void init() {
controlador=new usuarioController();
}
public long getId_user() {
return id_user;
}
public void setId_user(long id_user) {
this.id_user = id_user;
}
public Privilegio getSelected() {
return Selected;
}
public void setSelected(Privilegio selected) {
Selected = selected;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public Usuario getU() {
getParam();
return u;
}
public void setU(Usuario u) {
this.u = u;
}
private List<Usuario> usuario;
public List<Usuario> getUsuario() {
usuario=UsuarioDAO.getAll();
return usuario;
}
public Usuario getById(long id_usuario){
return u;
}
public void setUsuario(List<Usuario> usuario) {
this.usuario = usuario;
}
public void saveUsuario(Usuario u){
controlador.saveUsuario(u);
}
public void getParam(){
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map<String, String> parameterMap = (Map<String, String>) externalContext.getRequestParameterMap();
Long param = Long.valueOf(parameterMap.get("id_usuario"));
System.out.println(param);
this.setU(controlador.getUser(param));
}
public void setPrivilegio(){
System.out.println("hola");
Privilegio pri=new Privilegio();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map parameterMap = externalContext.getRequestParameterMap();
Agrupacion agrupacion= (Agrupacion)parameterMap.get("agrup");
System.out.println(agrupacion.getNombre());
Rol rol = (Rol)parameterMap.get("rols");
System.out.println(rol.getNombre());
System.out.println(""+rol.getNombre()+" "+agrupacion.getNombre());
pri.setRol(rol);
pri.setAgrupacion(agrupacion);
pri.setActive(true);
this.getU().addPrivilegio(pri);
controlador.saveUsuario(this.getU());
}
}
this is the first view (list of users, from which i go to user details)
<?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">
<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<div class="container">
<h:panelGroup id="Usuarios">
<h:form id="FormUsuarios">
<h2>Listado de Usuarios</h2>
<h:graphicImage url="http://a.dryicons.com/images/icon_sets/simplistica/png/128x128/add.png" width="30" height="30"/>
<h:dataTable id="users" value="#{usuario.usuario}" var="o" styleClass="table table-striped table-bordered" headerClass="sorting_asc"
rowClasses="odd,even">
<h:column>
<f:facet name="header">#</f:facet>
#{o.id}
</h:column>
<h:column>
<f:facet name="header">Identificador</f:facet>
#{o.identificador}
</h:column>
<h:column>
<f:facet name="header">Nombre</f:facet>
#{o.nombres} #{o.apellidoMaterno} #{o.apellidoPaterno}
</h:column>
<h:column>
<f:facet name="header">Active</f:facet>
<h:selectBooleanCheckbox id="check" value="#{o.active}"></h:selectBooleanCheckbox>
</h:column>
<h:column>
<f:facet name="header">Detalles</f:facet>
<h:outputLink value="contenido/detalleUsuario.xhtml">
Detalle
<f:param name="id_usuario" value="#{o.id}" />
</h:outputLink>
</h:column>
</h:dataTable>
</h:form>
<script type="text/javascript" src="js/paging-bootstrap.js"></script>
<script type="text/javascript" src="js/contenidoc.datatable.init.js"></script>
</h:panelGroup>
</div>
</ui:composition>
Bad getter!
public Usuario getU() {
getParam();
return u;
}
The getter above is a very bad idea. You've said it yourself that the variable makes it into the usuario backing bean(this I doubt). It is just plain wrong to perform business logic inside a getter because of inconsistencies (like you're experiencing) and the fact that the getter is called multiple times during a request. There are more elegant and cleaner ways to pass and initialise parameters between JSF pages.
private Usuario u=new Usuario(); is also a bad idea. Why is this necessary when you have
this.setU(controlador.getUser(param));
All that should happen inside your #PostConstructor
#PostConstruct
public void init() {
controlador=new usuarioController();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
//Obtener parametros del request
Map<String, String> parameterMap = (Map<String, String>) externalContext.getRequestParameterMap();
Long param = Long.valueOf(parameterMap.get("id_usuario"));
System.out.println(param);
this.setU(controlador.getUser(param));
}
The getter should just be plain
public Usuario getU() {
return u;
}
The cause of this error is that parameterMap.get("id_usuario") is null. You should investigate how you pass this parameter from the UI to the backing bean.
I have a web application where the first page is a login page, and once I am logged correctly, the main page is displayed. The page has a tabbed menu and if the first time I click on one of the tabs, the main page is refreshed again instead of going to the requested page. This occurs only on the first clic. The other times, everything works fine.
I texted it with Firefox, Chrome and IE7, and this behavior only happened with IE7. Why could this be? Where the error could be? Because I don't know what piece of my code should I copy here to clarify my question.
PD: I use a Filter and the main page uses a bean to populate a table. I also tried <redirect/> tag in faces-cofig.xml, and it solved the problem. But the page always showed the "Invalid User" popup contained in the login page. And finally, I discarded it.
Update with some code
I think the problem isn't in the main page, because I replaced it by other pages and the behavior is the same... (Update 2) But with a simple html page it works fine.
login.xhtml:
<h:form id="login">
<h:outputText value="#{msg['login.user']}"/>
<h:inputText value="#{LogBean.name}" required="true"/>
<h:outputText value="#{msg['login.password']}"/>
<h:inputSecret value="#{LogBean.pass}" required="true"/>
<p:commandButton id="botonAccesoPrim"
value="#{msg['login.enter']}"
action="#{LogBean.checkLog}"
oncomplete="dlg1.show();">
</p:commandButton>
<p:dialog id="popup"
visible="#{LogBean.popup}"
widgetVar="dlg1"
modal="true">
<h:outputText value="Invalid User." />
</p:dialog>
LogBean:
public class LogBean {
private String name;
private String pass;
private String validate = "";
private String popup = "false";
//Getters, setters
public String checkLog() throws Exception {
if (correctLog(md5Final)) {
popup = "false";
validate= "success";
return validate;
}
else {
popup = "true";
validate = "fail";
return validate;
}
}
public boolean correctLog(String md5) throws SQLException {
boolean correct = false;
String sql = "SELECT ...";
String passBBDD = null;
cConexionOracle.conecta();
ResultSet result = OracleConnection.query(sql);
if (!(result.next()))
return correct;
else {
passBBDD = result.getString("pass");
if (md5.equals(passBBDD))
correct = true;
}
OracleConnection.desconect();
return correct;
}
public boolean isLogged () {
return name != null;
}
faces-config:
<managed-bean>
<managed-bean-name>LogBean</managed-bean-name>
<managed-bean-class>LogBeanClass</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>mainBean</managed-bean-name>
<managed-bean-class>MainBeanClass</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/HTML/login.xhtml</from-view-id>
<navigation-case>
<from-action>#{LogBean.checkLog}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/HTML/main.xhtml</to-view-id>
<redirect/>
</navigation-case>
<navigation-case>
<from-action>#{LogBean.checkLog}</from-action>
<from-outcome>fail</from-outcome>
<to-view-id>/HTML/login.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
FilterLogin:
public void doFilter (ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
if (req.getRequestURI().endsWith("login.jsf")) {
chain.doFilter(req, resp);
return;
}
HttpSession session = req.getSession(false);
if (session != null) {
LogBean BeanConnection = (LogBean) req.getSession().getAttribute("LogBean");
if (BeanConnection != null && BeanConnection.isLogged()) {
chain.doFilter(req, resp);
return;
}
}
resp.sendRedirect(req.getContextPath() + "/HTML/login.jsf");
}
web.xml
<filter>
<filter-name>Filter</filter-name>
<filter-class>FilterLogin</filter-class>
</filter>
<filter-mapping>
<filter-name>Filter</filter-name>
<url-pattern>/HTML/*</url-pattern>
</filter-mapping>
mainBean: (Update 2)
private ArrayList<mainClass> mainList = new ArrayList<mainClass>();
private String name;
//...
//Getters, setters.
#PostConstruct
public void populateMainList() {
String sql = null;
if (name == null) {
sql = "SELECT ...";
}
else
sql = "SELECT ... LIKE '%"+name+"%'";
OracleConnection.connect();
ResultSet result = OracleConnection.query(sql);
try {
while(result.next()){
mainClass main = new mainClass();
main.set...(result.getLong("someProperty"));
mainList.add(main);
}
} catch (SQLException e) {
e.printStackTrace();
}
OracleConnection.disconnect();
}
public ArrayList<mainClass> getMainList() throws SQLException {
return mainList;
}
main.xhtml
<h:inputText id="search" value="#{mainBean.name}"> </h:inputText>
<h:commandButton id ="SubmitSearch" action="#{mainBean.seachButton}"></h:commandButton>
<h:commandButton id ="new" value="New" action="#{sistemaBean.newButton}"> </h:commandButton>
<t:dataTable id="data" rows="1" value="#{mainBean.mainList}" var="item"
width="95%" border="0" align="center" cellpadding="0" cellspacing="0">
<t:column width="42%">
<f:facet name="header">
<h:outputText value="Name"/>
</f:facet>
<h:commandLink value="#{item.shortName}" action="#{detailledMainBean.mainDetail}">
<f:param name="idMain" value="#{item.idMain}"/>
</h:commandLink>
</t:column>
<t:column>
<f:facet name="header">
<h:outputText value="Description"/>
</f:facet>
<h:outputText value="#{item.description}"/>
</t:column>
</t:dataTable>
<t:dataScroller id="scroller" for="data"
paginator="false" paginatorMaxPages="5"
paginatorColumnClass="style"
immediate="true"
pageCountVar="pageCount" pageIndexVar="pageIndex"
disableFacetLinksIfFirstPage="true"
disableFacetLinksIfLastPage="true"
renderFacetLinksIfFirstPage="false"
renderFacetLinksIfLastPage="false"
paginatorRenderLinkForActive="false"
renderFacetsIfSinglePage="false"
displayedRowsCountVar="true">
<f:facet name="previous">
<t:outputText styleClass="style" value=" « Previous | "/>
<t:outputText styleClass="style" value="Page #{pageIndex} / #{pageCount}"/>
</f:facet>
<f:facet name="next">
<t:outputText styleClass="style" value=" | Next »"/>
</f:facet>
</t:dataScroller>
Thanks in advance.
IE7 and jsf 2 will give you various problems. We have not encountered this problem specifically but many others.
Our problems mostly boiled down to tables. JSF is pretty table centric and many components translates to html with one or several tables. For example we commonly had to use some extra css for aligns.
For some tables we had to set the table header width with javascript. Problem was IE7 broke the table because it couldn't determine header width.
Unsure if you can draw any clues from this. But I would advise you to think in terms of workarounds rather than "what's wrong with the code".
I'm new to primefaces. I trying some examples in primeface showcase
But;
After saveUser, on ajax method handleComplete(xhr, status, args) args don't have arguments that added in saveUser method.
EDIT : I just added #ManagedBean annotations because i'm using jsf 2.0
EDIT-2
in my pom;
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>2.2</version>
</dependency>
in my web.xml
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
in my .xhtml page
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui">
<h:head>
<script type="text/javascript">
function handleComplete(xhr, status, args) {
if(args.validationFailed) {
alert("Validation Failed");
} else {
alert("Save:" + args.saved);
alert("FirstName: " + args.user.firstname + ", Lastname: " + args.user.lastname);
}
}
</script>
</h:head>
<h:body>
<h:form>
<p:panel id="panel" header="New User">
<h:panelGrid columns="2">
<h:outputLabel for="firstname" value="Firstname: *" />
<p:inputText id="firstname" value="#{user.firstName}" required="true"/>
<h:outputLabel for="surname" value="Lastname: *" />
<p:inputText id="surname" value="#{user.surName}" required="true"/>
</h:panelGrid>
</p:panel>
<p:commandButton value="Save" actionListener="#{user.saveUser}" oncomplete="handleComplete(xhr, status, args)" />
</h:form>
</h:body>
</html>
in my bean;
#ManagedBean(name = "user")
public class User {
private String firstName = "";
private String surName = "";
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setSurName(String surName) {
this.surName = surName;
}
public String getSurName() {
return surName;
}
public void saveUser(ActionEvent actionEvent) {
// save user
RequestContext context = RequestContext.getCurrentInstance();
context.addCallbackParam("saved", true);
context.addCallbackParam("user", this);
}
}
EDIT -3
I can catch properties that carried with data in ajax response with this.PrimeFaces.ajax.RequestManager.requests[0].data it carries that data ;
"j_id2059540600_7ac21836=j_id2059540600_7ac21836&j_id2059540600_7ac21836%3Afirstname=qweq&j_id2059540600_7ac21836%3Asurname=asda&javax.faces.ViewState=8900392402396831372%3A-8139730777939772917&javax.faces.partial.ajax=true&javax.faces.source=j_id2059540600_7ac21836:j_id2059540600_7ac218a5&javax.faces.partial.execute=#all&j_id2059540600_7ac21836:j_id2059540600_7ac218a5=j_id2059540600_7ac21836:j_id2059540600_7ac218a5"
But i'm pretty sure there is another option. Just can't seet it.
Thanks for any help.
Solved! It was about scope problem of a form that contains a commandButton. Command buttons (i think..didnt read a formal document about it.) that in a form has a scope of its own form. Cant reach/update/modify elements in an form.