I have a PhaseListener and does not work. But in the computer of my co-worker if it works.
I use netbeans 6.8 With Glassfish 2.1 and Windows 32 bits
The PhaseListener:
package mx.udg.cgti.seguridad.listener;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseListener;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import mx.udg.cgti.seguridadcore.negocio.ProcesosCNLocal;
public class SeguridadCorePhaseListener implements PhaseListener {
public SeguridadCorePhaseListener() {
}
public void beforePhase(PhaseEvent pe) {
System.out.println("beforePhase");
}
public void afterPhase(PhaseEvent pe) {
System.out.println("afterPhase");
if (pe.getPhaseId().equals(PhaseId.RESTORE_VIEW)) {
if (pe.getFacesContext() != null) {
String pagina = pe.getFacesContext().getViewRoot().getViewId();
if (!"/Inicio.xhtml".equalsIgnoreCase(pagina) && !"/Login.xhtml".equalsIgnoreCase(pagina) && pagina.contains(".xhtml")) {
loggedIn();
}
}
}
}
private void loggedIn() {
String pagina = "";
Long token = obtenToken();
if (token != null) {
String result = "";
result = lookupProcesosCNLocal().getSesionActiva(token);
if ("".equalsIgnoreCase(result)) {
result = null;
}
// System.out.println("RESULT " + result);
if (result == null) {
pagina = new String("sessionTimeout");
}
} else {
pagina = new String("sinSession");
}
// System.out.println(" PAGINA :- " + pagina + " TOKEN " + token);
if (!pagina.equalsIgnoreCase("")) {
// System.out.println("REGLAS DE NAVEGACION TRABAJANDO HACIA " + pagina);
FacesContext fc = FacesContext.getCurrentInstance();
NavigationHandler nh = fc.getApplication().getNavigationHandler();
nh.handleNavigation(fc, null, pagina);
fc.renderResponse();
}
}
private Long obtenToken() {
Long token = null;
HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
Object t = request.getAttribute("token");
if (t == null) {
Object obj=null;
if(session != null){
obj = session.getAttribute("token");
if(obj == null){
obj = request.getParameter("token");
}
}else{
obj = request.getParameter("token");
}
if (obj != null) {
if (obj != null && !"".equalsIgnoreCase(obj.toString())) {
token = Long.parseLong(obj.toString());
}
}
} else {
token = Long.parseLong(t.toString());
}
if (token != null) {
request.setAttribute("token", token);
if(session == null){
session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
}
session.setAttribute("token", token);
}
return token;
}
public PhaseId getPhaseId() {
return PhaseId.RESTORE_VIEW;
}
private ProcesosCNLocal lookupProcesosCNLocal() {
try {
Context c = new InitialContext();
return (ProcesosCNLocal) c.lookup("java:comp/env/ProcesosCN");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
}
faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<!-- =========== FULL CONFIGURATION FILE ================================== -->
<faces-config version="2.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">
<navigation-rule>
<from-view-id>/*</from-view-id>
<navigation-case>
<from-outcome>logear</from-outcome>
<to-view-id>/Login.xhtml</to-view-id>
<redirect>1</redirect>
</navigation-case>
<navigation-case>
<from-outcome>sessionTimeout</from-outcome>
<to-view-id>/LoginError.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>sinSession</from-outcome>
<to-view-id>/LoginError.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
<application>
<message-bundle>
mx.udg.cgti.seguridad.boundle.MiBoundle
</message-bundle>
</application>
<lifecycle>
<phase-listener>mx.udg.cgti.seguridad.listener.SeguridadCorePhaseListener</phase-listener>
</lifecycle>
<validator>
<validator-id>validaComboRequerido</validator-id>
<validator-class>mx.udg.cgti.seguridad.validator.ValidaComboRequerido</validator-class>
</validator>
<converter>
<converter-id>tipoUsuario</converter-id>
<converter-class>mx.udg.cgti.ln.convertidor.TipoUsuarioConverter</converter-class>
</converter>
<converter>
<converter-id>Usuario</converter-id>
<converter-class>mx.udg.cgti.ln.convertidor.UsuarioConverter</converter-class>
</converter>
<converter>
<converter-id>Rol</converter-id>
<converter-class>mx.udg.cgti.ln.convertidor.RolConverter</converter-class>
</converter>
<converter>
<converter-id>Permiso</converter-id>
<converter-class>mx.udg.cgti.ln.convertidor.PermisoConverter</converter-class>
</converter>
<converter>
<converter-id>UnidadOrganizacional</converter-id>
<converter-class>mx.udg.cgti.ln.convertidor.UnidadOrganizacionalConverter</converter-class>
</converter>
</faces-config>
Apparently you've another version of exactly the same class somewhere in the classpath which got precedence in classloading over the one included in the WAR.
That can be inside the /lib folder of the server itself, or inside the /lib or /lib/ext folders of the installed JRE which is used by the server.
Related
I am implementing forget password function. It will send a link to the user to reset his password. It looks something like this http://localhost:9080/BelsizeWeb/faces/login_pwchange.xhtml?id=yPvRp9xwUTXAY9fQpuNnuEBqT+twZ0rBraVKdcsJRi4=
While the user is still on this page, when the user click button to change and login, and if there is password mismatch, it will prompt with a faces message and the link on address bar should still contains id=yPvRp9xwUTXAY9fQpuNnuEBqT+twZ0rBraVKdcsJRi4=. But currently the link on address bar does not include the querystring.
I am using MyFaces 2.0, xhtml. Well, it hit null pointer exception because the querystring is null. I am using RequestScoped for Login_pwchange.java.
login_pwchange.xhtml
<f:metadata>
<f:event listener="#{pc_Login_pwchange.onPageLoadBegin}" type="preRenderView"></f:event>
<f:viewParam name="id" value="#{pc_Login_pwchange.w_login.token}" />
</f:metadata>
<h:body>
<h:form id="form1" enctype="multipart/form-data" prependId="false">
<p:commandButton ajax="false" type="submit" value="Change and Login"
id="login_pwchange_change" styleClass="commandButton"
action="#{pc_Login_pwchange.doLogin_pwchange_changeAction}"
style="width:150px" disabled="#{pc_Login_pwchange.w_login.disabled}">
<f:param name="id" value="#{pc_Login_pwchange.w_login.token}" />
</p:commandButton>
</h:form>
</h:body>
faces-config.xml
<navigation-rule>
<from-view-id>/login_pwchange.xhtml</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/index.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>failure</from-outcome>
<to-view-id>/login.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>xxxxxx</from-outcome>
<to-view-id>/login_pwchange.xhtml?faces-redirect=true&includeViewParams=true</to-view-id>
</navigation-case>
</navigation-rule>
RedirectLogin.java
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
boolean authorized = false;
boolean is_sysadmin = false;
String user_sys_id = null;
HttpSession session = null;
if (request instanceof HttpServletRequest) {
session = ((HttpServletRequest) request).getSession(false);
if (session != null) {
user_sys_id = (String) session.getAttribute("user_sys_id");
if (user_sys_id != null) {
authorized = true;
String _id = user_sys_id.substring(0, 8);
if (_id.equals("SYSADMIN")) {
is_sysadmin = true;
}
}
}
}
if (request.getCharacterEncoding() == null) {
request.setCharacterEncoding("UTF-8");
}
String _uri = ((HttpServletRequest) request).getRequestURI();
String _querystring = ((HttpServletRequest) request).getQueryString(); //can get for first time. when there is page submit, this becomes null
//Forget Password
//========================
if (!authorized && _uri.contains("login_pwchange.xhtml")) {
HashMap _m = isResetPasswordURL(_querystring);
request.setAttribute("userid", _m.get("USERID"));
request.setAttribute("request_datetime", _m.get("REQUEST_DATETIME"));
request.setAttribute("token", _m.get("TOKEN"));
//OK - continue
chain.doFilter(request, response);
return;
}
if (_uri.contains("login.xhtml")) {
//OK - continue
chain.doFilter(request, response);
return;
}
chain.doFilter(request, response);
return;
}
Login_pwchange.java
public String doLogin_pwchange_changeAction() {
W_login _w_l = getW_login();
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
request.setAttribute("token", _w_l.getToken());
Useraccount _ua = new Useraccount();
_ua = _ua.getUserAccount_ByUserid_NotClosed(_w_l.getUserid());
String _user_sys_id = _ua.getUsersysid();
_w_l.setUsersysid(_user_sys_id);
String _password = _w_l.getPassword();
if(isEmptyNull(_password)) {
_password = "";
}
String _password_retype = _w_l.getPassword_retype();
if(isEmptyNull(_password_retype)) {
_password_retype = "";
}
_ua = _w_l.getUserAccount_BackEnd_ByUsersysid(_user_sys_id);
Integer _min_length = _ua.getPwminlength();
Integer _max_length = _ua.getPwmaxlength();
Integer _password_length = new Integer(_password.length());
Integer _password_history = _ua.getPwhistory();
Integer _max_age = _ua.getPwmaxage();
String _userid = _ua.getUserid();
String _msg_key=null;
_w_l.setPassword(null);
_w_l.setPassword_retype(null);
// Password mismatch
if (!_password.equals(_password_retype)) {
showCommonMessage_ByKey("login_pwchange_message_password_mismatch");
return "xxxxxx";
}
Integer _status = _w_l.changePassword(_user_sys_id,_password);
if (_status!=null) {
return "success";
} else {
return "failure";
}
}
I am studying on developing JSF 2.2 component jar library. I have developed a simple MyDataTablecomponent for this purpose.
MyDataTableLib.jar contains 3 packages:
1) META-INF which contains following MyDataTableTag.taglib.xml file
<?xml version="1.0" encoding="UTF-8"?>
<facelet-taglib version="2.1" 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-jsptaglibrary_2_1.xsd">
<namespace>http:java.sun.com/MyDataTableTag</namespace>
<tag>
<tag-name>MyDataTableTag</tag-name>
<component>
<component-type>com.components.MyDataTable</component-type>
<renderer-type>com.renderer.MyRenderer</renderer-type>
</component>
<attribute>
<name>title</name>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
<attribute>
<name>binding</name>
<required>true</required>
<deferred-value>com.components.MyDataTable</deferred-value>
</attribute>
</tag>
</facelet-taglib>
2)com.componentswhich contains following MyDataTablecomponent
package com.components;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
#FacesComponent(value = MyDataTable.MY_TYPE)
public class MyDataTable extends UIComponentBase {
public static final String MY_FAMILY = "com.components.MyDataTable";
public static final String MY_TYPE = "com.components.MyDataTable";
public static final String MY_RENDERER_TYPE = "com.renderer.MyRenderer";
String Title, columnnames[], data[][];
DataBaseManagement db;
#Override
public String getFamily() {
return MY_FAMILY;
}
public MyDataTable() throws ClassNotFoundException, SQLException {
setRendererType(MY_RENDERER_TYPE);
db = new DataBaseManagement("jdbc:mysql://localhost:3306/fakulte", "root", "");
}
public String getTitle() {
return Title;
}
public void setTitle(String Title) {
this.Title = Title;
}
public String[] getColumnnames() {
return columnnames;
}
public void setColumnnames(String[] columnnames) {
this.columnnames = columnnames;
}
public String[][] getData() {
return data;
}
public void setData(String[][] data) {
this.data = data;
}
public void executeQuery(String query) throws SQLException {
ArrayList<HashMap<String, String>> result = db.getQuery(query);
Object cols[] = result.get(0).keySet().toArray();
columnnames = new String[cols.length];
data = new String[result.size()][cols.length];
for (int c = 0; c < cols.length; c++) {
columnnames[c] = cols[c].toString();
}
for (int r = 0; r < result.size(); r++) {
for (int c = 0; c < columnnames.length; c++) {
data[r][c] = result.get(r).get(columnnames[c]);
}
}
Title = db.getLastQueryTitle();
}
#Override
public Object saveState(FacesContext context) {
Object val[] = new Object[4];
val[0] = super.saveState(context);
val[1] = Title;
val[2] = columnnames;
val[3] = data;
return val;
}
#Override
public void restoreState(FacesContext context, Object state) {
Object val[] = (Object[]) state;
super.restoreState(context, val[0]);
Title = (String) val[1];
columnnames = (String[]) val[2];
data = (String[][]) val[3];
}
}
3) com.rendererwhich contains MyRendererrenderer class
package com.renderer;
import com.components.MyDataTable;
import java.io.IOException;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.render.FacesRenderer;
import javax.faces.render.Renderer;
#FacesRenderer(componentFamily = MyDataTable.MY_FAMILY,
rendererType = MyDataTable.MY_RENDERER_TYPE)
public class MyRenderer extends Renderer {
#Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
super.encodeBegin(context, component);
if (component != null) {
encodeTable(context.getResponseWriter(), (MyDataTable) component);
}
}
#Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
super.encodeEnd(context, component);
ResponseWriter out = context.getResponseWriter();
out.startElement("h3", component);
out.write("Sayfa Sonu-------");
out.endElement("h3");
}
private void encodeTable(ResponseWriter out, MyDataTable table) throws IOException {
if (table.getTitle() != null) {
out.startElement("h1", table);
out.write(table.getTitle());
out.endElement("h1");
}
if (table.getData() != null) {
out.startElement("table", table);
out.writeAttribute("border", "1", "border");
if (table.getColumnnames() != null) {
out.startElement("tr", table);
String col[] = table.getColumnnames();
for (int i = 0; i < col.length; i++) {
out.startElement("td", table);
out.write(col[i]);
out.endElement("td");
}
out.endElement("tr");
}
String data[][] = table.getData();
for (int r = 0; r < data.length; r++) {
out.startElement("tr", table);
for (int c = 0; c < data[r].length; c++) {
out.startElement("td", table);
out.write(data[r][c]);
out.endElement("td");
}
out.endElement("tr");
}
out.endElement("table");
}
}
}
When I include this jar library in another project as follows:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:t="http:java.sun.com/MyDataTableTag">
<head>
<title>TODO supply a title</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<h:form>
<h:inputText binding="#{Bean.input}"/>
<h:commandButton value="Execute query" action="#{Bean.executeQuery()}"/>
<t:MyDataTableTag title="Hello" binding="#{Bean.table}"/>
</h:form>
</body>
</html>
Expression Error: Named Object: com.components.MyDataTable not found.error message is thrown.
I am using NetBeans 8.0. I need help.
Thank you BalusC
I put new DataBaseManagement() in try-catch but no exception was thrown. I removed <rtexprvalue>and <deferred-value>attributes from tag lib.xmland nothing changed. Stack trace is as follows:
javax.faces.FacesException: Expression Error: Named Object: com.components.MyDataTable not found.
at com.sun.faces.application.ApplicationImpl.createComponentApplyAnnotations(ApplicationImpl.java:1933)
at com.sun.faces.application.ApplicationImpl.createComponentApplyAnnotations(ApplicationImpl.java:1968)
at com.sun.faces.application.ApplicationImpl.createComponent(ApplicationImpl.java:1151)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.createComponent(ComponentTagHandlerDelegateImpl.java:499)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:172)
at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
at javax.faces.view.facelets.DelegatingMetaTagHandler.applyNextHandler(DelegatingMetaTagHandler.java:137)
at com.sun.faces.facelets.tag.jsf.ComponentTagHandlerDelegateImpl.apply(ComponentTagHandlerDelegateImpl.java:190)
at javax.faces.view.facelets.DelegatingMetaTagHandler.apply(DelegatingMetaTagHandler.java:120)
at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
at com.sun.faces.facelets.compiler.NamespaceHandler.apply(NamespaceHandler.java:93)
at javax.faces.view.facelets.CompositeFaceletHandler.apply(CompositeFaceletHandler.java:95)
at com.sun.faces.facelets.compiler.EncodingHandler.apply(EncodingHandler.java:87)
at com.sun.faces.facelets.impl.DefaultFacelet.apply(DefaultFacelet.java:161)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.buildView(FaceletViewHandlingStrategy.java:980)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:99)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:647)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
I solved the problem.
Do not forget to put an empty faces-config.xml file (containing only
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="java.sun.com/xml/ns/javaee"; xmlns:xsi="w3.org/2001/XMLSchema-instance"; xsi:schemaLocation="java.sun.com/xml/ns/javaee java.sun.com/xml/ns/javaee/web-facesconfig_2_1.xsd";
version="2.1">
</faces-config>
) in your META-INF package.
I need to set sortBy for DataTable programmatically by bean. DataTable has single sort Mode, static columns, and custom lazy model to sort by custom expressions like = "#{contractor.companyName-MULTY_LANG}". I tried a lot of ways to do this and only one way works (code below), but works not correctly - Component showed without highlight ordered field. Can anybody answer how the correct way to set sortBy for DataTable programmatically?
#PostConstruct
public void init() {
final DataTable d = (DataTable) FacesContext.getCurrentInstance().getViewRoot().findComponent(TABLE_COMPONENT_KEY);
String tableSortByExpression = "#{contractor.companyName-MULTY_LANG}"; // expression from some column
SortMeta sm1 = new SortMeta();
for (UIComponent child : d.getChildren()) {
Column column = (Column)child;
ValueExpression columnSortByVe = column.getValueExpression("sortBy");
if (columnSortByVe != null) {
String columnSortByExpression = columnSortByVe.getExpressionString();
if (tableSortByExpression != null && tableSortByExpression.equals(columnSortByExpression)) {
d.setSortColumn(column);
d.setSortOrder("ASCENDING");
break;
}
}
}
}
I'll be appreciate for any help.
Primefaces 5.1. Tomcat 7. Mojarra 2.2.8
First of all extend org.primefaces.component.datatable.feature.SortFeature
public class CustomSortFeature extends SortFeature {
#SuppressWarnings("rawtypes")
#Override
public void encode(FacesContext context, DataTableRenderer renderer, DataTable table) throws IOException {
table.setFirst(0);
if(table.isLazy()) {
table.loadLazyData();
singleSort(context, table);
}
else {
if(table.isMultiSort())
multiSort(context, table);
else
singleSort(context, table);
if(table.isPaginator()) {
RequestContext requestContext = RequestContext.getCurrentInstance();
if(requestContext != null) {
requestContext.addCallbackParam("totalRecords", table.getRowCount());
}
}
//save state
Object filteredValue = table.getFilteredValue();
if(!table.isLazy() && table.isFilteringEnabled() && filteredValue != null) {
table.updateFilteredValue(context, (List) filteredValue);
}
}
renderer.encodeTbody(context, table, true);
}
}
Then try to extend org.primefaces.component.datatable.DataTableRenderer
#FacesRenderer(componentFamily = "org.primefaces.component", rendererType = "org.primefaces.component.DataTableRenderer")
public class CustomDataTableRenderer extends DataTableRenderer {
public List<DataTableFeatureKey> FEATURE = new ArrayList<DataTableFeatureKey>(){/**
*
*/
private static final long serialVersionUID = 1L;
{
add(DataTableFeatureKey.DRAGGABLE_COLUMNS);
add(DataTableFeatureKey.FILTER);
add(DataTableFeatureKey.PAGE);
add(DataTableFeatureKey.SORT);
add(DataTableFeatureKey.RESIZABLE_COLUMNS);
add(DataTableFeatureKey.SELECT);
add(DataTableFeatureKey.ROW_EDIT);
add(DataTableFeatureKey.CELL_EDIT);
add(DataTableFeatureKey.ROW_EXPAND);
add(DataTableFeatureKey.SCROLL);
add(DataTableFeatureKey.DRAGGABLE_ROWS);
}};
#Override
protected void preRender(FacesContext context, DataTable table){
table.setCaseSensitiveSort(false);
if(table.isLazy()) {
if(table.isLiveScroll())
table.loadLazyScrollData(0, table.getScrollRows());
else
table.loadLazyData();
}
boolean defaultSorted = (table.getValueExpression("sortBy") != null || table.getSortBy() != null);
if(defaultSorted && !table.isLazy()) {
table.setDefaultSortByVE(table.getValueExpression("sortBy"));
table.setDefaultSortOrder(table.getSortOrder());
table.setDefaultSortFunction(table.getSortFunction());
CustomSortFeature sortFeature = (CustomSortFeature) table.getFeature(DataTableFeatureKey.SORT);
if(table.isMultiSort())
sortFeature.multiSort(context, table);
else
sortFeature.singleSort(context, table);
table.setRowIndex(-1);
}
if(table.isPaginator()) {
table.calculateFirst();
}
Columns dynamicCols = table.getDynamicColumns();
if(dynamicCols != null) {
dynamicCols.setRowIndex(-1);
}
}
#Override
public void encodeEnd(FacesContext context, UIComponent component) throws IOException{
DataTable table = (DataTable) component;
if(table.shouldEncodeFeature(context)) {
for(Iterator<DataTableFeatureKey> it = FEATURE.iterator(); it.hasNext();) {
DataTableFeature feature = table.getFeature(it.next());
if(feature.shouldEncode(context, table)) {
feature.encode(context, this, table);
}
}
}
else {
preRender(context, table);
encodeMarkup(context, table);
encodeScript(context, table);
}
}
}
Furthermore, add render class to faces-config
<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">
<render-kit>
<renderer>
<component-family>org.primefaces.component</component-family>
<renderer-type>org.primefaces.component.DataTableRenderer</renderer-type>
<renderer-class>com.edtoktay.CustomDataTableRenderer</renderer-class>
</renderer>
</render-kit>
</faces-config>
Hope this helps
I am trying a small example on JSF and getting Evaluator exeption. Please find the details below and help.
Stacktrace
Error 500--Internal Server Error
javax.faces.el.EvaluationException: Cannot get value for expression '# {resumeBean.colorSupported}'
at org.apache.myfaces.el.ValueBindingImpl.getValue(ValueBindingImpl.java:405)
at javax.faces.component.html.HtmlSelectOneMenu.isDisabled(HtmlSelectOneMenu.java:130)
at org.apache.myfaces.shared_impl.renderkit.html.HtmlMenuRendererBase.isDisabled(HtmlMenuRendererBase.java:81)
at org.apache.myfaces.shared_impl.renderkit.html.HtmlMenuRendererBase.encodeEnd(HtmlMenuRendererBase.java:59)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:539)
at javax.faces.webapp.UIComponentTag.encodeEnd(UIComponentTag.java:498)
at javax.faces.webapp.UIComponentTag.doEndTag(UIComponentTag.java:366)
at jsp_servlet.__customize._jsp__tag3(__customize.java:289)
at jsp_servlet.__customize._jsp__tag1(__customize.java:199)
at jsp_servlet.__customize._jsp__tag0(__customize.java:158)
at jsp_servlet.__customize._jspService(__customize.java:124)
at weblogic.servlet.jsp.JspBase.service(JspBase.java:34)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283)
at weblogic.servlet.internal.ServletStubImpl.onAddToMapException(ServletStubImpl.java:394)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:309)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
at weblogic.servlet.internal.RequestDispatcherImpl.invokeServlet(RequestDispatcherImpl.java:533)
at weblogic.servlet.internal.RequestDispatcherImpl.forward(RequestDispatcherImpl.java:266)
at org.apache.myfaces.context.servlet.ServletExternalContextImpl.dispatch(ServletExternalContextImpl.java:419)
at org.apache.myfaces.application.jsp.JspViewHandlerImpl.renderView(JspViewHandlerImpl.java:211)
at org.apache.myfaces.lifecycle.RenderResponseExecutor.execute(RenderResponseExecutor.java:41)
at org.apache.myfaces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:132)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:140)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:227)
at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:125)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3244)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)
at weblogic.security.service.SecurityManager.runAs(SecurityManager.java:121)
at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2010)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:1916)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1366)
at weblogic.work.ExecuteThread.execute(ExecuteThread.java:209)
at weblogic.work.ExecuteThread.run(ExecuteThread.java:181)
Caused by: javax.faces.FacesException: java.lang.ClassNotFoundException: Class bytes found but defineClass()failed for: 'coreservlets.ResumeBean'
at org.apache.myfaces.shared_impl.util.ClassUtils.simpleClassForName(ClassUtils.java:165)
at org.apache.myfaces.shared_impl.util.ClassUtils.newInstance(ClassUtils.java:268)
at org.apache.myfaces.config.ManagedBeanBuilder.buildManagedBean(ManagedBeanBuilder.java:49)
at org.apache.myfaces.el.VariableResolverImpl.resolveVariable(VariableResolverImpl.java:314)
at org.apache.myfaces.el.ValueBindingImpl$ELVariableResolver.resolveVariable(ValueBindingImpl.java:570)
at org.apache.commons.el.NamedValue.evaluate(NamedValue.java:124)
at org.apache.commons.el.ComplexValue.evaluate(ComplexValue.java:140)
at org.apache.myfaces.el.ValueBindingImpl.getValue(ValueBindingImpl.java:386)
... 36 more
Caused by: java.lang.ClassNotFoundException: Class bytes found but defineClass()failed for: 'coreservlets.ResumeBean'
at weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClassLoader.java:268)
at weblogic.utils.classloaders.ChangeAwareClassLoader.findClass(ChangeAwareClassLoader.java:54)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at weblogic.utils.classloaders.GenericClassLoader.loadClass(GenericClassLoader.java:161)
at weblogic.utils.classloaders.ChangeAwareClassLoader.loadClass(ChangeAwareClassLoader.java:35)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:242)
at org.apache.myfaces.shared_impl.util.ClassUtils.classForName(ClassUtils.java:141)
at org.apache.myfaces.shared_impl.util.ClassUtils.simpleClassForName(ClassUtils.java:160)
... 43 more
Caused by: java.lang.UnsupportedClassVersionError: Bad version number in .class file
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at weblogic.utils.classloaders.GenericClassLoader.defineClass(GenericClassLoader.java:355)
at weblogic.utils.classloaders.GenericClassLoader.findLocalClass(GenericClassLoader.java:294)
at weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClassLoader.java:262)
... 53 more
ResumeBean.java
package coreservlets;
import javax.faces.model.*;
import javax.faces.event.*;
import java.io.*;
public class ResumeBean implements Serializable {
private String name = "";
private String jobTitle = "";
private String fgColor = "BLACK";
private String bgColor = "WHITE";
private SelectItem[] availableColorNames =
{ new SelectItem("BLACK"),
new SelectItem("WHITE"),
new SelectItem("SILVER"),
new SelectItem("RED"),
new SelectItem("GREEN"),
new SelectItem("BLUE") };
private SelectItem[] availableColorValues =
{ new SelectItem("#000000"),
new SelectItem("#FFFFFF"),
new SelectItem("#C0C0C0"),
new SelectItem("#FF0000"),
new SelectItem("#00FF00"),
new SelectItem("#0000FF") };
private boolean isColorSupported = true;
private boolean isUsingColorNames = true;
public String getName() { return(name); }
public void setName(String name) {
this.name = name;
}
public String getJobTitle() { return(jobTitle); }
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
public String getFgColor() { return(fgColor); }
public void setFgColor(String fgColor) {
this.fgColor = fgColor;
}
public String getBgColor() { return(bgColor); }
public void setBgColor(String bgColor) {
this.bgColor = bgColor;
}
public SelectItem[] getAvailableColors() {
if (isUsingColorNames) {
return(availableColorNames);
} else {
return(availableColorValues);
}
}
public boolean getColorSupported() { return(isColorSupported); }
public void toggleColorSupport(ActionEvent event) {
isColorSupported = !isColorSupported;
}
public String getColorSupportLabel() {
if (isColorSupported) {
return("Disable Color Customization");
} else {
return("Enable Colors Customization");
}
}
public boolean isUsingColorNames() {
return(isUsingColorNames);
}
public void setUsingColorNames(boolean isUsingColorNames) {
this.isUsingColorNames = isUsingColorNames;
}
public void changeColorMode(ValueChangeEvent event) {
boolean flag =
((Boolean)event.getNewValue()).booleanValue();
setUsingColorNames(!flag);
}
public String showPreview() {
if (isColorSupported && fgColor.equals(bgColor)) {
return("same-color");
} else {
return("success");
}
}
}
faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE faces-config PUBLIC
"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"
"http://java.sun.com/dtd/web-facesconfig_1_1.dtd">
<faces-config>
<managed-bean>
<managed-bean-name>resumeBean</managed-bean-name>
<managed-bean-class>coreservlets.ResumeBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
<managed-bean>
<managed-bean-name>colorBean</managed-bean-name>
<managed-bean-class>coreservlets.ColorBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/customize.jsp</from-view-id>
<navigation-case>
<from-outcome>same-color</from-outcome>
<to-view-id>/WEB-INF/results/same-color.jsp</to-view-id>
</navigation-case>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/WEB-INF/results/show-preview.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/customize-bg.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/WEB-INF/results/show-preview2.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
Application server : weblogic 9.2
JDK compiler used in eclipse : 1.5
Please help
I am developing jsf login and logout smaller web app.I see some problems.My logout method don't removed session and not working redirecting to login page.I have asked from stackoverflow.com.The Matt user answered Filter class to me.Then I researching Filter and page cache according Matt.I used to Filter's doFilter() method, in web.xml file etc..
Here is my code:
public class LoginFilter implements Filter {
#Override
public void init(FilterConfig config) throws ServletException {
}
#Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
UserController userController = (UserController) request.getSession().getAttribute("user");
if (userController == null || !userController.isLoggedIn()) {
response.sendRedirect(request.getContextPath() + "/login.jsf");
} else {
chain.doFilter(request, response);
}
}
#Override
public void destroy() {
}
}
And logout()
public String logout() {
FacesContext context = FacesContext.getCurrentInstance();
ExternalContext ec = context.getExternalContext();
final HttpServletRequest request = (HttpServletRequest) ec.getRequest();
request.getSession(false).invalidate();
return "logout";
}
And web.xml configuration:
<filter>
<filter-name>loginFilter</filter-name>
<filter-class>org.bis.logic.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>loginFilter</filter-name>
<url-pattern>*.jsf</url-pattern>
</filter-mapping>
After logging I rendering home page.
<body>
<!--
#{ session.invalidate();
response.sendRedirect("login.jsf");
} -->
<h:panelGrid rendered="#{userController.isLoggedIn()}">
Hello Mr . #{userController.user.name}
<br />
<h:form>
<p align="right">
<h:commandLink action="#{userController.logout()}"value="Logout" />
</p>
</h:form>
</h:panelGrid>
</body>
My userController managedBean class:
#ManagedBean(name = "userController")
#SessionScoped
public class UserController {
private User user;
public UserController() {
user = new User();
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public static void addErrorMessage(String msg) {
FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR,
msg, msg);
FacesContext.getCurrentInstance().addMessage(null, facesMsg);
}
public String authenticate() {
if (user.getName().equals("admin") && user.getPassword().equals("")) {
return "success";
} else
addErrorMessage(String
.format("Username and Password didn't match !!!"));
return "fail";
}
The page navigation xml:
<navigation-rule>
<from-view-id>/login.xhtml</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/home.xhtml</to-view-id>
<redirect />
</navigation-case>
<navigation-case>
<from-outcome>fail</from-outcome>
<to-view-id>/login.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/home.xhtml</from-view-id>
<navigation-case>
<from-action>#{userController.logout()}</from-action>
<from-outcome>logout</from-outcome>
<to-view-id>/index.xhtml</to-view-id>
<redirect />
</navigation-case>
</navigation-rule>
Your filter is running in an infinite redirect loop. The request on login.jsf will also invoke the filter. If the user is still not logged in, then it will redirect back to login.jsf which will in turn invoke the filter again, etcetera.
There are basically 2 ways to fix this:
Make sure that login.jsf is not covered by the URL pattern of the filter. Collect all secured pages (expect of login.jsf!) in a separate folder like /app, /secured, /pages, etc and map the filter on that URL pattern instead, e.g. /app/*.
Add an extra check which determines if the request is already requesting the login page and if so, then don't redirect to it again.
String loginURL = request.getContextPath() + "/login.jsf";
boolean loggedIn = userController != null && userController.isLoggedIn();
boolean loginRequest = request.getRequestURI().equals(loginURL);
if (loggedIn || loginRequest) {
chain.doFilter(request, response);
} else {
response.sendRedirect(loginURL);
}