2

我在类 String 消息中有一个 String var;

private int checkConstraints() 
    int a = 0;
    if (docProcessId==0) {
        a++;
   message = "<script language=\"javascript\"> alert('Please Select Doc Process Name'); </script>";
    }else if (refTypeName.equals("")) {
        a++;
        message = "<script> alert('Enter Reference Type Name!');</script>";
    }

    return a;

}

实际上我正在这样做,但是当调用此方法时不等于 0,则消息等于整个字符串打印在页面上,请不要发出警报任何解决方案

4

1 回答 1

2

JSF by default HTML-escapes all model values as part of XSS attack prevention. Your concrete problem suggests that you had no idea of that. You can "solve" it by using <h:outputText> with escape attribute set to false.

<h:outputText value="#{bean.message}" escape="false" />

However, your concrete problem is bigger. You're in JSF/MVC perspective basically making two major design mistakes here:

  1. Writing HTML code in model instead of in the view.
  2. Performing validation in an action method instead of in a validator.

You should be writing HTML code in the view, not in the model. You should be performing validation using a normal JSF validator. JSF has a lot of builtin validators.

Besides, not really a design mistake, but more an user experience mistake, there's a third mistake: using JavaScript alerts to show validation messages. This is simply too 1990 and Web 1.0. We're currently in 2013 and have learnt a lot, a lot of the user experience failures made back then. Using JavaScript alerts to show validation messages is one of them.

Here's the right approach using JSF-provided validation facilities:

<h:form>
    <h:selectOneMenu value="#{bean.docProcessId}" required="true" 
        requiredMessage="Please Select Doc Process Name">
        <f:selectItems ... />
    </h:selectOneMenu>
    <h:inputText value="#{bean.refTypeName}" required="true"
        requiredMessage="Enter Reference Type Name" />
    <h:commandButton value="submit" />
    <h:messages />
</h:form>

That's it. The required="true" tells JSF that those inputs are required. The requiredMessage attribute allows you to specify custom messages for required validation. The messages will be displayed in place as declared by <h:messages>. You can customize the layout by layout attribute and by CSS means like infoClass, errorClass, etc. You can even manually loop over it and manually create annoying alerts for each message instead of using <h:messages>:

<ui:repeat value="#{facesContext.messageList}" var="message">
    <script>alert("#{message.summary}");</script>
</ui:repeat>
于 2013-11-12T11:49:31.020 回答