显示应用程序如何报告状态:
图 10. 显示状态消息的结果
CalculatorController(见清单 24)避免了 JSF 相关代码混入 POJO 中。它能够感知 JSF,与组件 绑定,并将错误和状态消息放到 facesContext 中。
清单 24. 感知 JSF 的 CalculatorController
package com.arcmind.jsfquickstart.controller;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIInput;
import javax.faces.component.UIPanel;
import javax.faces.context.FacesContext;
import com.arcmind.jsfquickstart.model.Calculator;
public class CalculatorController {
private Calculator calculator;
private UIPanel resultsPanel;
private UIInput firstNumberInput;
private UIInput secondNumberInput;
public String add() {
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
calculator.add();
resultsPanel.setRendered(true);
facesContext.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_INFO, "Added successfully", null));
} catch (Exception ex) {
resultsPanel.setRendered(false);
facesContext.addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), null));
}
return null;
}
public String multiply() {
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
calculator.multiply();
resultsPanel.setRendered(true);
facesContext.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_INFO, "Multiplied successfully", null));
} catch (Exception ex) {
resultsPanel.setRendered(false);
facesContext.addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), null));
}
return null;
}
public String divide() {
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
calculator.divide();
resultsPanel.setRendered(true);
facesContext.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_INFO, "Divided successfully", null));
} catch (Exception ex) {
resultsPanel.setRendered(false);
if (ex instanceof ArithmeticException) {
secondNumberInput.setValue(Integer.valueOf(1));
}
facesContext.addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), null));
}
return null;
}
public String clear() {
FacesContext facesContext = FacesContext.getCurrentInstance();
try {
calculator.clear();
resultsPanel.setRendered(false);
facesContext.addMessage(null, new FacesMessage(
FacesMessage.SEVERITY_INFO, "Results cleared", null));
} catch (Exception ex) {
resultsPanel.setRendered(false);
facesContext.addMessage(null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.getMessage(), null));
}
return null;
}
public String getFirstNumberStyleClass() {
if (firstNumberInput.isValid()) {
return "la
|