JSF 2.2 – Java Server Faces : JSF GuessNumber Example
JSF GuessNumber Example |
GuessNumber Project in JSF using Eclipse
UserNumberBean.java
package com.javaskool;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.LongRangeValidator;
import javax.faces.validator.ValidatorException;
import java.util.Random;
public class UserNumberBean {
Integer userNumber = null;
Integer randomInt = null;
String response = null;
public UserNumberBean() {
Random randomGR = new Random();
do {
randomInt = new Integer(randomGR.nextInt(10));
} while (randomInt.intValue() == 0);
System.out.println("Duke's number: " + randomInt);
}
public void setUserNumber(Integer user_number) {
userNumber = user_number;
System.out.println("Set userNumber " + userNumber);
}
public Integer getUserNumber() {
System.out.println("get userNumber " + userNumber);
return userNumber;
}
public String getResponse() {
if (userNumber != null && userNumber.compareTo(randomInt) == 0) {
return "Yay! You got it!";
} else if (userNumber == null) {
return "Sorry, " + userNumber +
" is incorrect. Try a larger number.";
} else {
int num = userNumber.intValue();
if (num > randomInt.intValue()) {
return "Sorry, " + userNumber +
" is incorrect. Try a smaller number.";
} else {
return "Sorry, " + userNumber +
" is incorrect. Try a larger number.";
}
}
}
protected String[] status = null;
public String[] getStatus() {
return status;
}
public void setStatus(String[] newStatus) {
status = newStatus;
}
private int maximum = 0;
private boolean maximumSet = false;
public int getMaximum() {
return (this.maximum);
}
public void setMaximum(int maximum) {
this.maximum = maximum;
this.maximumSet = true;
}
private int minimum = 0;
private boolean minimumSet = false;
public int getMinimum() {
return (this.minimum);
}
public void setMinimum(int minimum) {
this.minimum = minimum;
this.minimumSet = true;
}
public void validate(FacesContext context,
UIComponent component,
Object value) throws ValidatorException {
if ((context == null) || (component == null)) {
throw new NullPointerException();
}
if (value != null) {
try {
int converted = intValue(value);
if (maximumSet &&
(converted > maximum)) {
if (minimumSet) {
throw new ValidatorException(
MessageFactory.getMessage
(context,
LongRangeValidator.NOT_IN_RANGE_MESSAGE_ID,
new Object[]{
new Integer(minimum),
new Integer(maximum),
MessageFactory.getLabel(context,
component)
}));
} else {
throw new ValidatorException(
MessageFactory.getMessage
(context,
LongRangeValidator.MAXIMUM_MESSAGE_ID,
new Object[]{
new Integer(maximum),
MessageFactory.getLabel(context,
component)
}));
}
}
if (minimumSet &&
(converted < minimum)) {
if (maximumSet) {
throw new ValidatorException(MessageFactory.getMessage
(context,
LongRangeValidator.NOT_IN_RANGE_MESSAGE_ID,
new Object[]{
new Double(minimum),
new Double(maximum),
MessageFactory.getLabel(context, component)
}));
} else {
throw new ValidatorException(
MessageFactory.getMessage
(context,
LongRangeValidator.MINIMUM_MESSAGE_ID,
new Object[]{
new Integer(minimum),
MessageFactory.getLabel(context,
component)
}));
}
}
} catch (NumberFormatException e) {
throw new ValidatorException(
MessageFactory.getMessage
(context, LongRangeValidator.TYPE_MESSAGE_ID,
new Object[]{MessageFactory.getLabel(context,
component)}));
}
}
}
private int intValue(Object attributeValue)
throws NumberFormatException {
if (attributeValue instanceof Number) {
return (((Number) attributeValue).intValue());
} else {
return (Integer.parseInt(attributeValue.toString()));
}
}
}
MessageFactory.java
package com.javaskool;
import javax.el.ValueExpression;
import javax.faces.FactoryFinder;
import javax.faces.application.Application;
import javax.faces.application.ApplicationFactory;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public class MessageFactory extends Object {
private MessageFactory() {
}
public static FacesMessage getMessage(String messageId, Object params[]) {
Locale locale = null;
FacesContext context = FacesContext.getCurrentInstance();
// context.getViewRoot() may not have been initialized at this point.
if (context != null && context.getViewRoot() != null) {
locale = context.getViewRoot().getLocale();
if (locale == null) {
locale = Locale.getDefault();
}
} else {
locale = Locale.getDefault();
}
return getMessage(locale, messageId, params);
}
public static FacesMessage getMessage(Locale locale, String messageId,
Object params[]) {
FacesMessage result = null;
String
summary = null,
detail = null,
bundleName = null;
ResourceBundle bundle = null;
// see if we have a user-provided bundle
if (null != (bundleName = getApplication().getMessageBundle())) {
if (null !=
(bundle =
ResourceBundle.getBundle(bundleName, locale,
getCurrentLoader(bundleName)))) {
// see if we have a hit
try {
summary = bundle.getString(messageId);
detail = bundle.getString(messageId + "_detail");
}
catch (MissingResourceException e) {
}
}
}
// we couldn't find a summary in the user-provided bundle
if (null == summary) {
// see if we have a summary in the app provided bundle
bundle = ResourceBundle.getBundle(FacesMessage.FACES_MESSAGES,
locale, getCurrentLoader(bundleName));
if (null == bundle) {
throw new NullPointerException();
}
// see if we have a hit
try {
summary = bundle.getString(messageId);
detail = bundle.getString(messageId + "_detail");
}
catch (MissingResourceException e) {
}
}
// we couldn't find a summary anywhere! Return null
if (null == summary) {
return null;
}
if (null == summary || null == bundle) {
throw new NullPointerException(" summary " + summary + " bundle " + bundle);
}
// At this point, we have a summary and a bundle.
//
return (new BindingFacesMessage(locale, summary, detail, params));
}
// Methods from MessageFactory
public static FacesMessage getMessage(FacesContext context,
String messageId) {
return getMessage(context, messageId, null);
}
public static FacesMessage getMessage(FacesContext context,
String messageId,
Object params[]) {
if (context == null || messageId == null) {
throw new NullPointerException(" context " + context
+ " messageId "
+ messageId);
}
Locale locale = null;
// viewRoot may not have been initialized at this point.
if (context != null && context.getViewRoot() != null) {
locale = context.getViewRoot().getLocale();
} else {
locale = Locale.getDefault();
}
if (null == locale) {
throw new NullPointerException(" locale " + locale);
}
FacesMessage message = getMessage(locale, messageId, params);
if (message != null) {
return message;
}
locale = Locale.getDefault();
return (getMessage(locale, messageId, params));
}
public static FacesMessage getMessage(FacesContext context,
String messageId,
Object param0) {
return getMessage(context, messageId, new Object[]{param0});
}
public static FacesMessage getMessage(FacesContext context,
String messageId,
Object param0, Object param1) {
return getMessage(context, messageId, new Object[]{param0, param1});
}
public static FacesMessage getMessage(FacesContext context,
String messageId,
Object param0, Object param1,
Object param2) {
return getMessage(context, messageId, new Object[]{param0, param1, param2});
}
public static FacesMessage getMessage(FacesContext context,
String messageId,
Object param0, Object param1,
Object param2, Object param3) {
return getMessage(context, messageId,
new Object[]{param0, param1, param2, param3});
}
// Gets the "label" property from the component.
public static Object getLabel(FacesContext context,
UIComponent component) {
Object o = component.getAttributes().get("label");
if (o == null) {
o = component.getValueExpression("label");
}
// Use the "clientId" if there was no label specified.
if (o == null) {
o = component.getClientId(context);
}
return o;
}
protected static Application getApplication() {
FacesContext context = FacesContext.getCurrentInstance();
if (context != null) {
return (FacesContext.getCurrentInstance().getApplication());
}
ApplicationFactory afactory = (ApplicationFactory)
FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
return (afactory.getApplication());
}
protected static ClassLoader getCurrentLoader(Object fallbackClass) {
ClassLoader loader =
Thread.currentThread().getContextClassLoader();
if (loader == null) {
loader = fallbackClass.getClass().getClassLoader();
}
return loader;
}
static class BindingFacesMessage extends FacesMessage {
BindingFacesMessage(
Locale locale,
String messageFormat,
String detailMessageFormat,
// array of parameters, both Strings and ValueExpressions
Object[] parameters) {
super(messageFormat, detailMessageFormat);
this.locale = locale;
this.parameters = parameters;
if (parameters != null) {
resolvedParameters = new Object[parameters.length];
}
}
public String getSummary() {
String pattern = super.getSummary();
resolveBindings();
return getFormattedString(pattern, resolvedParameters);
}
public String getDetail() {
String pattern = super.getDetail();
resolveBindings();
return getFormattedString(pattern, resolvedParameters);
}
private void resolveBindings() {
FacesContext context = null;
if (parameters != null) {
for (int i = 0; i < parameters.length; i++) {
Object o = parameters[i];
if (o instanceof ValueExpression) {
if (context == null) {
context = FacesContext.getCurrentInstance();
}
o = ((ValueExpression) o)
.getValue(context.getELContext());
}
// to avoid 'null' appearing in message
if (o == null) {
o = "";
}
resolvedParameters[i] = o;
}
}
}
private String getFormattedString(String msgtext, Object[] params) {
String localizedStr = null;
if (params == null || msgtext == null) {
return msgtext;
}
StringBuffer b = new StringBuffer(100);
MessageFormat mf = new MessageFormat(msgtext);
if (locale != null) {
mf.setLocale(locale);
b.append(mf.format(params));
localizedStr = b.toString();
}
return localizedStr;
}
private Locale locale;
private Object[] parameters;
private Object[] resolvedParameters;
}
}
index.jsp
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsp="http://java.sun.com/JSP/Page"
xml:lang="en" lang="en">
<jsp:output doctype-root-element="html"
doctype-public="-//W3C//DTD XHTML 1.0 Trasitional//EN"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>
<jsp:directive.page contentType="application/xhtml+xml; charset=UTF-8"/>
<head>
</head>
<body>
<jsp:forward page="faces/greeting.jsp"/>
</body>
</html>
greetings.jsp
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xml:lang="en" lang="en">
<jsp:output doctype-root-element="html"
doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>
<jsp:directive.page contentType="application/xhtml+xml; charset=UTF-8"/>
<head>
<title>Hello</title>
</head>
<body bgcolor="white">
<f:view>
<h:form id="helloForm">
<h2>Hi. I am Duke. And i'm thinking of a number from
<h:outputText lang="en_US" value="#{UserNumberBean.minimum}"/>
to
<h:outputText value="#{UserNumberBean.maximum}"/> . Can you guess it?
</h2>
<h:graphicImage id="waveImg" url="/wave.med.gif"/>
<h:inputText id="userNo" label="User Number"
value="#{UserNumberBean.userNumber}"
validator="#{UserNumberBean.validate}"/>
<h:commandButton id="submit" action="success" value="Submit"/>
<p/>
<h:message showSummary="true" showDetail="false"
style="color: red; font-family: 'New Century Schoolbook', serif; font-style: oblique; text-decoration: overline"
id="errors1" for="userNo"/>
</h:form>
</f:view>
</body>
</html>
response.jsp
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xml:lang="en" lang="en">
<jsp:output doctype-root-element="html"
doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>
<jsp:directive.page contentType="application/xhtml+xml; charset=UTF-8"/>
<head>
<title>Guess The Number</title>
</head>
<body bgcolor="white">
<f:view>
<h:form id="responseForm">
<h:graphicImage id="waveImg" url="/wave.med.gif"/>
<h2>
<h:outputText id="result" lang="en"
value="#{UserNumberBean.response}"/>
</h2>
<h:commandButton id="back" value="Back" action="success"/>
<p/>
</h:form>
</f:view>
</body>
</html>
faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_1_2.xsd"
version="1.2">
<application>
<locale-config>
<default-locale>en</default-locale>
<supported-locale>de</supported-locale>
<supported-locale>fr</supported-locale>
<supported-locale>es</supported-locale>
</locale-config>
</application>
<navigation-rule>
<from-view-id>/greeting.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/response.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/response.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/greeting.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<managed-bean>
<description>
The "backing file" bean that backs up the guessNumber webapp
</description>
<managed-bean-name>UserNumberBean</managed-bean-name>
<managed-bean-class>com.javaskool.UserNumberBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>minimum</property-name>
<property-class>int</property-class>
<value>1</value>
</managed-property>
<managed-property>
<property-name>maximum</property-name>
<property-class>int</property-class>
<value>10</value>
</managed-property>
</managed-bean>
<managed-bean>
<description>
The "backing file" bean that backs up the guessNumber webapp
</description>
<managed-bean-name>requestBean</managed-bean-name>
<managed-bean-class>com.javaskool.UserNumberBean</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>minimum</property-name>
<property-class>int</property-class>
<value>12</value>
</managed-property>
<managed-property>
<property-name>maximum</property-name>
<property-class>int</property-class>
<value>22</value>
</managed-property>
</managed-bean>
</faces-config>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>JSFGuessNumberExample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<is-xml>true</is-xml>
</jsp-property-group>
</jsp-config>
<!-- Faces Servlet -->
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Faces Servlet Mapping -->
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<security-constraint>
<display-name>Restrict access to JSP pages</display-name>
<web-resource-collection>
<web-resource-name>
Restrict access to JSP pages
</web-resource-name>
<url-pattern>/greeting.jsp</url-pattern>
<url-pattern>/response.jsp</url-pattern>
</web-resource-collection>
<auth-constraint>
<description>
With no roles defined, no access granted
</description>
</auth-constraint>
</security-constraint>
</web-app>
Output
Downloads Example |
Recent Comments