Wednesday, December 20, 2006

Calling Servlets from JSF

Another point I struggled with is calling servlets from JSF. Here is a simple example.

This is the bean which is called from .jsp page
import javax.faces.context.FacesContext;

public class ServletTest {

    public void doThis(){
    String url = "url of your servlet";
    FacesContext context = FacesContext.getCurrentInstance();
    try {
       context.getExternalContext().dispatch(url);
    }catch (Exception e) {
       e.printStackTrace();
    }
    finally{
       context.responseComplete();
    }
  }
}

This is the .jsp page

<f:view>
<h:form id="myForm">
<h:commandButton value="Do" action="#{ServletTest.doThis}" />
</h:form>
</f:view>

Saturday, December 02, 2006

Parameter passing in JSF

My part of the interns' project is to develop a web portal using JSF. However I'm new to JSF and have to search and learn. The hardest point I struggled with is passing parameters to the backing bean from the UI. I was stuck a whole day on this. Finally I got it and I'm wondering how hard this simple thing to be found and this is that.

<h:form>
    <h:commandButton value="Show" actionListener="#{MyBean.setStr}" action="#{MyBean.go}" >
        <f:attribute name="name" value="Hello"/>
    </h:commandButton>
</h:form>

public class MyBean {
    private String str;
    .....
    public void setStr(ActionEvent event){
        String name = (String) event.getComponent().getAttributes().get("name");
        this.str=name;
    }

    public String go(){
        return ("success");
    }
}

This may help those who are new to JSF like me:)



Related Posts with Thumbnails