How do i embed java code inside jsf page?

2020-07-22 09:39发布

问题:

I have: A managed bean called "LoginBean". A JSF page called "login.xhtml"

In this jsf page, i have a login form.

Inside the managebean i have a loginCheck function.

public void loginCheck(){
 if(logincorrect){
  //set user session 
 }else{
  //set lockout count session ++
 }
}

What i want to do in my jsf page is that when the lock out count session == 2 (means users failed to login correctly 2 times, i need a recaptcha tag to be displayed.

<td>
    <%
         if(FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("numberOfLogins") == 2){
         <p:captcha label="Captcha" requiredMessage="Oops, are you human?"/>
       }
     %>

Apparently, the <% tag does not work. Appreciate any help from java/jsf experts.

回答1:

Scriptlets (those PHP-like <% %> things) are part of JSP which is deprecated since JSF 2.0 in favor of its successor Facelets (XHTML). Facelets doesn't support any alternative to scriptlets anymore. Using scriptlets in JSP has in almost all cases lead to badly designed and poorly maintainable codebase. Forget about them. Java code belongs in fullworthy Java classes. Just prepare the model (some Javabean class) in the controller (a JSF backing bean class) and use taglibs and EL (Expression Language, those #{} things) to access the model in the view.

Your concrete use case,

<%
     if(FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("numberOfLogins") == 2){
     <p:captcha label="Captcha" requiredMessage="Oops, are you human?"/>
   }
 %>

can be solved in fullworthy JSF/EL as follows:

<p:captcha label="Captcha" requiredMessage="Oops, are you human?" rendered="#{numberOfLogins == 2}" />

That numberOfLogins can by the way much better be made a property of a JSF @SessionScoped @ManagedBean than some attribute being manually placed in the session map.

See also:

  • Our JSF wiki page - contains some links to decent JSF tutorials as well


回答2:

This is not how JSF works, at least not with XHTML as the presentation layer instead of JSP. (<% is part of JSP, which you're no longer using here.) The proper way to do this is with managed beans. Alternatively, you could use Expression Language (EL) here.

I'd review the "JavaServer Faces Technology" chapter of Oracle's Java EE tutorial for some additional assistance.