How do i embed java code inside jsf page?

回眸只為那壹抹淺笑 提交于 2020-01-01 16:53:33

问题


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.



来源:https://stackoverflow.com/questions/12330934/how-do-i-embed-java-code-inside-jsf-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!