Java/J2EE/JavaServer Faces
Содержание
- 1 Change Bean Property
- 2 Common static utility methods that help in implementing JSF tags
- 3 Converts UISelectMany submitted value to converted value
- 4 Gathers all select items from specified component"s children
- 5 Hello World JSF
- 6 JavaServer Faces
- 7 jsf jpa war
- 8 Jsf Utility
- 9 Simple utility class for CSS style formatting
Change Bean Property
<source lang="java">
//This example is from Jakub Czeczotka <jakub.czeczotka> //web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.ru/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.ru/xml/ns/j2ee http://java.sun.ru/xml/ns/j2ee/web-app_2_4.xsd"> <display-name> ChangeBeanProperty </display-name> <description> Change a property of a simple bean </description> <listener> <listener-class> org.apache.myfaces.webapp.StartupServletContextListener </listener-class> </listener> <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>*.jsf</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>
</web-app>
//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.ru/dtd/web-facesconfig_1_1.dtd">
<faces-config>
<managed-bean> <managed-bean-name>simpleBean</managed-bean-name> <managed-bean-class>eu.czeczotka.SimpleBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean>
</faces-config> //SimpleBean.java package eu.czeczotka;
import java.util.logging.Logger;
/**
* Simple bean for the ChangeBeanProperty project * * @author Jakub Czeczotka */
public class SimpleBean {
private Logger logger = Logger.getLogger ("eu.czeczotka.SimpleBean"); private String property = "initial value"; public String getProperty () { return this.property; } public void setProperty (String property) { logger.info ("changing property value from \"" + this.property + "\" to \"" + property + "\""); this.property = property; }
}
//index.jsp <% response.sendRedirect("changeBeanProperty.jsf"); %> //changeBeanProperty.jsp <%@ taglib uri="http://java.sun.ru/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.ru/jsf/html" prefix="h" %> <%-- ChangeBeanProperty - author Jakub Czeczotka --%> <html> <head>
<title>ChangeBeanProperty</title>
</head> <body>
<f:view> <h:form>
Change a property of a simple bean
<h:inputText value="#{simpleBean.property}" /> <h:commandButton type="submit" value="change value" action="#" /> </h:form> </f:view>
</body> </html>
</source>
Common static utility methods that help in implementing JSF tags
<source lang="java">
/**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/jsf/branches/sakai_2-5-4/widgets/src/java/org/sakaiproject/jsf/util/TagUtil.java $ * $Id: TagUtil.java 9278 2006-05-10 23:29:21Z ray@media.berkeley.edu $ ********************************************************************************** * * Copyright (c) 2003, 2004 The Sakai Foundation. *
- Licensed under the Educational Community License, Version 1.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
- http://www.opensource.org/licenses/ecl1.php
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
* **********************************************************************************/
import java.io.Serializable; import java.util.HashMap; import javax.faces.application.Application; import javax.faces.ruponent.UIComponent; import javax.faces.context.FacesContext; import javax.faces.el.MethodBinding; import javax.faces.el.ValueBinding; import javax.faces.event.ActionEvent; import javax.faces.event.ValueChangeEvent; import javax.faces.webapp.UIComponentTag; /**
* Common static utility methods that help in implementing JSF tags. */
public class TagUtil {
/** This class is meant for static use only */ private TagUtil() { } /** * Set a string value on a component - used by tags setProperties() method. * Handles value bindings. */ public static void setString(UIComponent component, String name, String value) { if (value == null) { return; } if (UIComponentTag.isValueReference(value)) { setValueBinding(component, name, value); } else { component.getAttributes().put(name, value); } } /** * Set a string value on a component - used by tags setProperties() method. * Handles value bindings. */ public static void setObject(UIComponent component, String name, String value) { if (value == null) { return; } if (UIComponentTag.isValueReference(value)) { setValueBinding(component, name, value); } else { component.getAttributes().put(name, value); } } /** * Set an integer value on a component - used by tags setProperties() * method. Handles value bindings. */ public static void setInteger(UIComponent component, String name, String value) { if (value == null) { return; } if (UIComponentTag.isValueReference(value)) { setValueBinding(component, name, value); } else { component.getAttributes().put(name, Integer.valueOf(value)); } } /** * Set a Map value on a component - used by tags setProperties() method. * Handles value bindings. */ public static void setMap(UIComponent component, String name, String value) { if (value == null) { return; } if (UIComponentTag.isValueReference(value)) { setValueBinding(component, name, value); } else { component.getAttributes().put(name, new HashMap()); } } /** * Set a double value on a component - used by tags setProperties() method. * Handles value bindings. */ public static void setDouble(UIComponent component, String name, String value) { if (value == null) { return; } if (UIComponentTag.isValueReference(value)) { setValueBinding(component, name, value); } else { component.getAttributes().put(name, Double.valueOf(value)); } } /** * Set a boolean value on a component - used by tags setProperties() method. * Handles value bindings. */ public static void setBoolean(UIComponent component, String name, String value) { if (value == null) { return; } if (UIComponentTag.isValueReference(value)) { setValueBinding(component, name, value); } else { component.getAttributes().put(name, Boolean.valueOf(value)); } } /** * Set a ValueBinding on a component - used by tags setProperties() method. */ public static void setValueBinding(UIComponent component, String name, String value) { FacesContext context = FacesContext.getCurrentInstance(); Application app = context.getApplication(); ValueBinding vb = app.createValueBinding(value); component.setValueBinding(name, vb); } /** * Set an ActionListener on a component - used by tags setProperties() * method. Handles method bindings. */ public static void setActionListener(UIComponent component, String value) { setMethodBinding(component, "actionListener", value, new Class[] { ActionEvent.class }); } /** * Set a ValueChangeListener on a component - used by tags setProperties() * method. Handles method bindings. */ public static void setValueChangeListener(UIComponent component, String value) { setMethodBinding(component, "valueChangeListener", value, new Class[] { ValueChangeEvent.class }); } /** * Set a Validator on a component - used by tags setProperties() method. * Handles method bindings. */ public static void setValidator(UIComponent component, String value) { setMethodBinding(component, "validator", value, new Class[] { FacesContext.class, UIComponent.class, Object.class }); } /** * Set an action on a component - used by tags setProperties() method. * Handles method bindings. */ public static void setAction(UIComponent component, String value) { if (value == null) { return; } if (UIComponentTag.isValueReference(value)) { setMethodBinding(component, "action", value, new Class[] {}); } else { FacesContext context = FacesContext.getCurrentInstance(); Application app = context.getApplication(); MethodBinding mb = new ActionMethodBinding(value); component.getAttributes().put("action", mb); } } /** * Set a MethodBinding on a component - used by tags setProperties() method. */ public static void setMethodBinding(UIComponent component, String name, String value, Class[] paramTypes) { if (value == null) { return; } if (UIComponentTag.isValueReference(value)) { FacesContext context = FacesContext.getCurrentInstance(); Application app = context.getApplication(); MethodBinding mb = app.createMethodBinding(value, paramTypes); component.getAttributes().put(name, mb); } } public static String eval(String expression) { if (expression == null) { return null; } if (UIComponentTag.isValueReference(expression)) { FacesContext context = FacesContext.getCurrentInstance(); Application app = context.getApplication(); return "" + app.createValueBinding(expression).getValue(context); } else { return expression; } } public static Integer evalInteger(String expression) { if (expression == null) { return null; } if (UIComponentTag.isValueReference(expression)) { FacesContext context = FacesContext.getCurrentInstance(); Application app = context.getApplication(); Object r = app.createValueBinding(expression).getValue(context); if (r == null) { return null; } else if (r instanceof Integer) { return (Integer) r; } else { return Integer.valueOf(r.toString()); } } else { return Integer.valueOf(expression); } } public static Double evalDouble(String expression) { if (expression == null) { return null; } if (UIComponentTag.isValueReference(expression)) { FacesContext context = FacesContext.getCurrentInstance(); Application app = context.getApplication(); Object r = app.createValueBinding(expression).getValue(context); if (r == null) { return null; } else if (r instanceof Double) { return (Double) r; } else { return Double.valueOf(r.toString()); } } else { return Double.valueOf(expression); } } public static Boolean evalBoolean(String expression) { if (expression == null) { return null; } if (UIComponentTag.isValueReference(expression)) { FacesContext context = FacesContext.getCurrentInstance(); Application app = context.getApplication(); Object r = app.createValueBinding(expression).getValue(context); if (r == null) { return null; } else if (r instanceof Boolean) { return (Boolean) r; } else { return Boolean.valueOf(r.toString()); } } else { return Boolean.valueOf(expression); } } /** * A shortcut MethodBinding which just returns a single string result - * useful when an action should just return a certain result, not call a * method. */ private static class ActionMethodBinding extends MethodBinding implements Serializable { private String result; public ActionMethodBinding(String result) { this.result = result; } public Object invoke(FacesContext context, Object params[]) { return result; } public String getExpressionString() { return result; } public Class getType(FacesContext context) { return String.class; } }
}
</source>
Converts UISelectMany submitted value to converted value
<source lang="java">
/**
* Licensed under the Common Development and Distribution License, * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.sun.ru/cddl/ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */
import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.faces.FacesException; import javax.faces.ruponent.UIComponent; import javax.faces.ruponent.UIInput; import javax.faces.ruponent.UIOutput; import javax.faces.ruponent.UISelectItem; import javax.faces.ruponent.UISelectItems; import javax.faces.ruponent.UISelectMany; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.el.ValueBinding; import javax.faces.model.SelectItem;
/**
* @author Maksim Kaszynski * */
public class SelectUtils {
/** * Gathers all select items from specified component"s children * @param context * @param component * @return list of {@link SelectItems} taken from f:selectItem and f:selectItems */ public static List getSelectItems(FacesContext context, UIComponent component) { ArrayList list = new ArrayList(); Iterator kids = component.getChildren().iterator(); while (kids.hasNext()) { UIComponent kid = (UIComponent) kids.next(); if (kid instanceof UISelectItem) { Object value = ((UISelectItem) kid).getValue(); if (value == null) { UISelectItem item = (UISelectItem) kid; list.add(new SelectItem(item.getItemValue(), item.getItemLabel(), item.getItemDescription(), item.isItemDisabled())); } else if (value instanceof SelectItem) { list.add(value); } else { String valueClass = (value != null ? """ + value.getClass().getName() + """ : ""); throw new IllegalArgumentException(Messages.getMessage(Messages.INVALID_ATTRIBUTE_VALUE, valueClass, "<selectItem>")); } } else if (kid instanceof UISelectItems && null != context) { Object value = ((UISelectItems) kid).getValue(); if (value instanceof SelectItem) { list.add(value); } else if (value instanceof SelectItem[]) { SelectItem items[] = (SelectItem[]) value; for (int i = 0; i < items.length; i++) { list.add(items[i]); } } else if (value instanceof Collection) { Iterator elements = ((Collection) value).iterator(); while (elements.hasNext()) { list.add(elements.next()); } } else if (value instanceof Map) { Iterator keys = ((Map) value).keySet().iterator(); while (keys.hasNext()) { Object key = keys.next(); if (key == null) { continue; } Object val = ((Map) value).get(key); if (val == null) { continue; } list.add(new SelectItem(val.toString(), key.toString(), null)); } } else { String valueClass = (value != null ? """ + value.getClass().getName() + """ : ""); throw new IllegalArgumentException("INVALID_ATTRIBUTE_VALUE, valueClass"); } } } return list; } /** * Converts UISelectMany submitted value to converted value * * @author Manfred Geiler * @param facesContext * @param component * @param submittedValue * @return * @throws ConverterException */ public static Object getConvertedUISelectManyValue( FacesContext facesContext, UISelectMany component, String[] submittedValue) throws ConverterException { // Attention! // This code is duplicated in jsfapi component package. // If you change something here please do the same in the other class! if (submittedValue == null) throw new NullPointerException("submittedValue"); ValueBinding vb = component.getValueBinding("value"); Class valueType = null; Class arrayComponentType = null; if (vb != null) { valueType = vb.getType(facesContext); if (valueType != null && valueType.isArray()) { arrayComponentType = valueType.getComponentType(); } } Converter converter = component.getConverter(); if (converter == null) { if (valueType == null) { // No converter, and no idea of expected type // --> return the submitted String array return submittedValue; } if (List.class.isAssignableFrom(valueType)) { // expected type is a List // --> according to javadoc of UISelectMany we assume that the // element type // is java.lang.String, and copy the String array to a new List int len = submittedValue.length; List lst = new ArrayList(len); for (int i = 0; i < len; i++) { lst.add(submittedValue[i]); } return lst; } if (arrayComponentType == null) { throw new IllegalArgumentException(Messages.getMessage(Messages.VALUE_BINDING_TYPE_ERROR)); } if (String.class.equals(arrayComponentType)) return submittedValue; // No conversion needed for String type if (Object.class.equals(arrayComponentType)) return submittedValue; // No conversion for Object class try { converter = facesContext.getApplication().createConverter( arrayComponentType); } catch (FacesException e) { System.out.println("NO_CONVERTER_FOUND_ERROR"); return submittedValue; } } // Now, we have a converter... if (valueType == null) { // ...but have no idea of expected type // --> so let"s convert it to an Object array int len = submittedValue.length; Object[] convertedValues = (Object[]) Array.newInstance( arrayComponentType == null ? Object.class : arrayComponentType, len); for (int i = 0; i < len; i++) { convertedValues[i] = converter.getAsObject(facesContext, component, submittedValue[i]); } return convertedValues; } if (List.class.isAssignableFrom(valueType)) { // Curious case: According to specs we should assume, that the // element type // of this List is java.lang.String. But there is a Converter set // for this // component. Because the user must know what he is doing, we will // convert the values. int len = submittedValue.length; List lst = new ArrayList(len); for (int i = 0; i < len; i++) { lst.add(converter.getAsObject(facesContext, component, submittedValue[i])); } return lst; } if (arrayComponentType == null) { throw new IllegalArgumentException("VALUE_BINDING_TYPE_ERROR"); } if (arrayComponentType.isPrimitive()) { // primitive array int len = submittedValue.length; Object convertedValues = Array.newInstance(arrayComponentType, len); for (int i = 0; i < len; i++) { Array.set(convertedValues, i, converter.getAsObject( facesContext, component, submittedValue[i])); } return convertedValues; } else { // Object array int len = submittedValue.length; ArrayList convertedValues = new ArrayList(len); for (int i = 0; i < len; i++) { convertedValues.add(i, converter.getAsObject(facesContext, component, submittedValue[i])); } return convertedValues.toArray((Object[]) Array.newInstance( arrayComponentType, len)); } } public static Object getConvertedUIInputValue( FacesContext facesContext, UIInput component, String submittedValue) throws ConverterException{ Object convertedValue = null; /* if (submittedValue == null) throw new NullPointerException("submittedValue"); */ if(InputUtils.EMPTY_STRING.equals(submittedValue)){ return null; } Converter converter = getConverterForProperty(facesContext, component, "value"); if(converter != null){ convertedValue = converter.getAsObject(facesContext, component, submittedValue); } else { convertedValue = submittedValue; } return convertedValue; } /** * * @param facesContext * @param component * @param property * @return converter for specified component attribute */ public static Converter getConverterForProperty(FacesContext facesContext, UIOutput component, String property){ Converter converter = component.getConverter(); if(converter == null){ ValueBinding valueBinding = component.getValueBinding(property); if(valueBinding != null){ Class valueType = valueBinding.getType(facesContext); if(valueType == null || String.class.equals(valueType) || Object.class.equals(valueType)){ //No converter needed } else { converter = facesContext.getApplication().createConverter(valueType); if(converter == null){ throw new ConverterException("NO_CONVERTER_FOUND_ERROR"); } } } } return converter; }
}
</source>
Gathers all select items from specified component"s children
<source lang="java">
/**
* Licensed under the Common Development and Distribution License, * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.sun.ru/cddl/ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */
import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.faces.FacesException; import javax.faces.ruponent.UIComponent; import javax.faces.ruponent.UIInput; import javax.faces.ruponent.UIOutput; import javax.faces.ruponent.UISelectItem; import javax.faces.ruponent.UISelectItems; import javax.faces.ruponent.UISelectMany; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.el.ValueBinding; import javax.faces.model.SelectItem;
/**
* @author Maksim Kaszynski * */
public class SelectUtils {
/** * Gathers all select items from specified component"s children * @param context * @param component * @return list of {@link SelectItems} taken from f:selectItem and f:selectItems */ public static List getSelectItems(FacesContext context, UIComponent component) { ArrayList list = new ArrayList(); Iterator kids = component.getChildren().iterator(); while (kids.hasNext()) { UIComponent kid = (UIComponent) kids.next(); if (kid instanceof UISelectItem) { Object value = ((UISelectItem) kid).getValue(); if (value == null) { UISelectItem item = (UISelectItem) kid; list.add(new SelectItem(item.getItemValue(), item.getItemLabel(), item.getItemDescription(), item.isItemDisabled())); } else if (value instanceof SelectItem) { list.add(value); } else { String valueClass = (value != null ? """ + value.getClass().getName() + """ : ""); throw new IllegalArgumentException(Messages.getMessage(Messages.INVALID_ATTRIBUTE_VALUE, valueClass, "<selectItem>")); } } else if (kid instanceof UISelectItems && null != context) { Object value = ((UISelectItems) kid).getValue(); if (value instanceof SelectItem) { list.add(value); } else if (value instanceof SelectItem[]) { SelectItem items[] = (SelectItem[]) value; for (int i = 0; i < items.length; i++) { list.add(items[i]); } } else if (value instanceof Collection) { Iterator elements = ((Collection) value).iterator(); while (elements.hasNext()) { list.add(elements.next()); } } else if (value instanceof Map) { Iterator keys = ((Map) value).keySet().iterator(); while (keys.hasNext()) { Object key = keys.next(); if (key == null) { continue; } Object val = ((Map) value).get(key); if (val == null) { continue; } list.add(new SelectItem(val.toString(), key.toString(), null)); } } else { String valueClass = (value != null ? """ + value.getClass().getName() + """ : ""); throw new IllegalArgumentException("INVALID_ATTRIBUTE_VALUE, valueClass"); } } } return list; } /** * Converts UISelectMany submitted value to converted value * * @author Manfred Geiler * @param facesContext * @param component * @param submittedValue * @return * @throws ConverterException */ public static Object getConvertedUISelectManyValue( FacesContext facesContext, UISelectMany component, String[] submittedValue) throws ConverterException { // Attention! // This code is duplicated in jsfapi component package. // If you change something here please do the same in the other class! if (submittedValue == null) throw new NullPointerException("submittedValue"); ValueBinding vb = component.getValueBinding("value"); Class valueType = null; Class arrayComponentType = null; if (vb != null) { valueType = vb.getType(facesContext); if (valueType != null && valueType.isArray()) { arrayComponentType = valueType.getComponentType(); } } Converter converter = component.getConverter(); if (converter == null) { if (valueType == null) { // No converter, and no idea of expected type // --> return the submitted String array return submittedValue; } if (List.class.isAssignableFrom(valueType)) { // expected type is a List // --> according to javadoc of UISelectMany we assume that the // element type // is java.lang.String, and copy the String array to a new List int len = submittedValue.length; List lst = new ArrayList(len); for (int i = 0; i < len; i++) { lst.add(submittedValue[i]); } return lst; } if (arrayComponentType == null) { throw new IllegalArgumentException(Messages.getMessage(Messages.VALUE_BINDING_TYPE_ERROR)); } if (String.class.equals(arrayComponentType)) return submittedValue; // No conversion needed for String type if (Object.class.equals(arrayComponentType)) return submittedValue; // No conversion for Object class try { converter = facesContext.getApplication().createConverter( arrayComponentType); } catch (FacesException e) { System.out.println("NO_CONVERTER_FOUND_ERROR"); return submittedValue; } } // Now, we have a converter... if (valueType == null) { // ...but have no idea of expected type // --> so let"s convert it to an Object array int len = submittedValue.length; Object[] convertedValues = (Object[]) Array.newInstance( arrayComponentType == null ? Object.class : arrayComponentType, len); for (int i = 0; i < len; i++) { convertedValues[i] = converter.getAsObject(facesContext, component, submittedValue[i]); } return convertedValues; } if (List.class.isAssignableFrom(valueType)) { // Curious case: According to specs we should assume, that the // element type // of this List is java.lang.String. But there is a Converter set // for this // component. Because the user must know what he is doing, we will // convert the values. int len = submittedValue.length; List lst = new ArrayList(len); for (int i = 0; i < len; i++) { lst.add(converter.getAsObject(facesContext, component, submittedValue[i])); } return lst; } if (arrayComponentType == null) { throw new IllegalArgumentException("VALUE_BINDING_TYPE_ERROR"); } if (arrayComponentType.isPrimitive()) { // primitive array int len = submittedValue.length; Object convertedValues = Array.newInstance(arrayComponentType, len); for (int i = 0; i < len; i++) { Array.set(convertedValues, i, converter.getAsObject( facesContext, component, submittedValue[i])); } return convertedValues; } else { // Object array int len = submittedValue.length; ArrayList convertedValues = new ArrayList(len); for (int i = 0; i < len; i++) { convertedValues.add(i, converter.getAsObject(facesContext, component, submittedValue[i])); } return convertedValues.toArray((Object[]) Array.newInstance( arrayComponentType, len)); } } public static Object getConvertedUIInputValue( FacesContext facesContext, UIInput component, String submittedValue) throws ConverterException{ Object convertedValue = null; /* if (submittedValue == null) throw new NullPointerException("submittedValue"); */ if(InputUtils.EMPTY_STRING.equals(submittedValue)){ return null; } Converter converter = getConverterForProperty(facesContext, component, "value"); if(converter != null){ convertedValue = converter.getAsObject(facesContext, component, submittedValue); } else { convertedValue = submittedValue; } return convertedValue; } /** * * @param facesContext * @param component * @param property * @return converter for specified component attribute */ public static Converter getConverterForProperty(FacesContext facesContext, UIOutput component, String property){ Converter converter = component.getConverter(); if(converter == null){ ValueBinding valueBinding = component.getValueBinding(property); if(valueBinding != null){ Class valueType = valueBinding.getType(facesContext); if(valueType == null || String.class.equals(valueType) || Object.class.equals(valueType)){ //No converter needed } else { converter = facesContext.getApplication().createConverter(valueType); if(converter == null){ throw new ConverterException("NO_CONVERTER_FOUND_ERROR"); } } } } return converter; }
}
</source>
Hello World JSF
<source lang="java">
//This example is from Jakub Czeczotka <jakub.czeczotka>
//web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.ru/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.ru/xml/ns/j2ee http://java.sun.ru/xml/ns/j2ee/web-app_2_4.xsd"> <display-name> HelloWorldJSF </display-name> <description> Hello in the JavaServer Faces World! </description> <listener> <listener-class> org.apache.myfaces.webapp.StartupServletContextListener </listener-class> </listener> <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>*.jsf</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list>
</web-app>
//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.ru/dtd/web-facesconfig_1_1.dtd">
<faces-config>
<managed-bean> <managed-bean-name>helloWorldBean</managed-bean-name> <managed-bean-class>eu.czeczotka.HelloWorldBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean>
</faces-config> //HelloWorldBean.java package eu.czeczotka; /**
* Sample bean for the HelloWorldJSF project * * @author Jakub Czeczotka */
public class HelloWorldBean {
private String hello = "Hello in the JavaServer Faces World!"; public String getHello () { return this.hello; }
} //helloworld.jsp <%@ taglib uri="http://java.sun.ru/jsf/core" prefix="f" %> <%@ taglib uri="http://java.sun.ru/jsf/html" prefix="h" %> <%-- HelloWorldJSF - author Jakub Czeczotka --%> <html> <head>
<title>HelloWorldJSF</title>
</head> <body>
<f:view> <h:form>
<h:outputText value="#{helloWorldBean.hello}" />
</h:form> </f:view>
</body> </html>
//index.jsp <% response.sendRedirect("helloworld.jsf"); %>
</source>
JavaServer Faces
<source lang="java">
/* Chapter 21: JavaServer Faces.
Beginning JavaServer Pages Vivek Chopra, Jon Eaves, Rupert Jones, Sing Li, John T. Bell ISBN: 0-7645-7485-X
- /
</source>
jsf jpa war
Jsf Utility
<source lang="java">
/*
* BEGIN_HEADER - DO NOT EDIT * * The contents of this file are subject to the terms * of the Common Development and Distribution License * (the "License"). You may not use this file except * in compliance with the License. * * You can obtain a copy of the license at * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. * See the License for the specific language governing * permissions and limitations under the License. * * When distributing Covered Code, include this CDDL * HEADER in each file and include the License file at * https://open-jbi-components.dev.java.net/public/CDDLv1.0.html. * If applicable add the following below this CDDL HEADER, * with the fields enclosed by brackets "[]" replaced with * your own identifying information: Portions Copyright * [year] [name of copyright owner] */
/*
* @(#)JsfUtility.java * * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved. * * END_HEADER - DO NOT EDIT */
import javax.el.MethodExpression; import javax.el.ValueExpression; import javax.faces.context.FacesContext; import javax.faces.ruponent.UIComponent;
public class JsfUtility {
protected JsfUtility() { super(); } /** * Helper method to set value expression property. * * @param component The UIComponent to set a value expression for. * @param name The name of the value expression property. * @param expression The expresion for the value expression. */ public static void setValueExpression(UIComponent component, String name, String expression) { if (expression == null) { return; } FacesContext context = FacesContext.getCurrentInstance(); component.setValueExpression(name, createValueExpression( context, expression, Object.class)); } /** * Helper method to set a method expression property. * Create a method expression that returns String and has no * input paramaters. * * @param component The UIComponent to set a value binding for. * @param name The name of the method expression property * @param expression The expression to create. */ public static void setMethodExpression(UIComponent component, String name, String expression) { setMethodExpression(component, name, expression, Object.class, new Class[0]); } /** * Helper method to set a method expression property. * * @param component The UIComponent to set a value binding for. * @param name The name of the method expression property * @param expression The expression to create. */ public static void setMethodExpression(UIComponent component, String name, String expression, Class out, Class[] in) { if (expression == null) { return; } FacesContext context = FacesContext.getCurrentInstance(); component.getAttributes().put(name, createMethodExpression(context, expression, out, in)); } public static MethodExpression createMethodExpression( FacesContext context, String expr, Class out, Class[] in) { return context.getApplication().getExpressionFactory(). createMethodExpression(context.getELContext(), expr, out, in); } public static ValueExpression createValueExpression( FacesContext context, String expr, Class value) { return context.getApplication().getExpressionFactory(). createValueExpression(context.getELContext(), expr, value); }
}
</source>
Simple utility class for CSS style formatting
<source lang="java">
/**
* Licensed under the Common Development and Distribution License, * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.sun.ru/cddl/ * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */
import java.util.HashMap; import java.util.Iterator; import java.util.Map; /**
* Simple utility class for CSS style formatting
* Current version isn"t thread-safe and doesn"t provide any validation
*
* Usage is simle
*
* CSSFormat format = new CSSFormat();
* format.add("background-position", "top left");
* format.addURL("background-image", "/images/corner.gif");
* responseWriter.writeAttribute("style", format, null);
*
*
* @author Maksim Kaszynski
*
*/
public class CSSFormat {
/** * Surrounds given URL withurl()
* @param url * @return */ public static String url(String url){ StringBuffer buf = new StringBuffer(url.length() + 7); buf.append("url(").append(url).append(")"); return buf.toString(); } /** * Formats property-value pair in CSS fashion * @param property * @param value * @return */ public static String propertyValue(String property, String value){ return formatPropertyValue(property, value); } private static String formatPropertyValue(Object property, Object value){ StringBuffer buf = new StringBuffer(); buf.append(property).append(": ").append(value).append(";"); return buf.toString(); } private Map properties; /** * Constructs an empty CSSFormat object */ public CSSFormat() { properties = new HashMap(); } /** * Constructs CSSFormat object * and fills it with given parameters * @param property * @param value */ public CSSFormat(String property, String value){ properties = new HashMap(3); add(property, value); } /** * Adds property. If such property already exists, * its value is replaced with new one * @param property * @param value * @return itself */ public CSSFormat add(String property, String value){ properties.put(property, value); return this; } /** * adds a property with URL value * given value is wrapped inurl()
clause * @param property * @param url * @return itself */ public CSSFormat addURL(String property, String url){ properties.put(property, url(url)); return this; } /** * Concatenates all properties with their values to produce single-line CSS output */ public String toString() { return concatenate(null); } /** * Concatenates all properties with their values to produce CSS output * @param separator - custom string to be inserted between properties * @return */ public String concatenate(String separator){ StringBuffer output = new StringBuffer(); for(Iterator iter = properties.entrySet().iterator(); iter.hasNext();){ Map.Entry entry = (Map.Entry) iter.next(); output.append(formatPropertyValue(entry.getKey(), entry.getValue())); if(separator != null && iter.hasNext()){ output.append(separator); } } return output.toString(); }
}
</source>