Archive for the ‘JSEE’ Category

Cấu hình domain ảo ở localhost

Posted: April 25, 2014 in JSEE

Nếu bạn đang là php programmer thì hẳn trên máy ít ra phải cài localhost để test web. Đó có thể là AppServ, XAMPP, WAMP…các phần mềm này đều sử dụng Apache làm lớp Web Server, và đó là đối tượng của bài viết này.

Giả sử bạn phát triển 1 dự án và tạo trên localhost, cách thông thường là mỗi dự án thì bạn tạo một thư mục riêng trong thư mục www hoặc bên trong 1 thư mục nào đó. Vd mình có 1 dự án mới tên là shopabc, đặt trong thư mục “www\projects\freelanceproj\”, thì để truy cập tới ứng dụng này trên localhost, bạn cần phải gõ đường dẫn trên trình duyệt là: http://localhost/projects/freelanceproj/shopabc/ <– đường dẫn ở localhost đến ứng dụng shopabc mà bạn đang phát triển.

Đường dẫn dưới localhost này có một số khuyết điểm sau:
1.Mỗi lần type cũng dài và nhiều khi khó nhớ
2. Không hiển thị chân thật được kiến trúc URL đã định ban đầu cho website vì nó không phản ánh đúng domain name
3. Demo cho khách hàng với cái đường dẫn không ấn tượng lắm.

Với 3 khuyết điểm trên, mình viết bài này để chia sẽ tới các bạn một cách giúp giải quyết các khuyết điểm trên để làm cho việc phát triển web "vui" hơn một tí. Mục đích của mình cụ thể bây giờ là mình sẽ gõ http://myshop.com vào thanh địa chỉ của trình duyệt, và nó sẽ load nội dung y chang với đường dẫn http://localhost/projects/freelanceproj/shopabc/ của localhost. Để làm việc này mình sẽ sử dụng cơ chế Virtual Host của Apache.

Cấu hình chức năng như thế bạn cần tiến hành 3 bước như sau: cập nhật file host của windows, enable vhost module trong apache và add vhost để nhận domain mà bạn muốn.
Bước 1: Cập nhật file host của windows

Vì hệ thống của windows xp sử dụng file host (các windows khác mình chưa nghiên cứu, nếu ai có nghiên cứu rồi thì chia sẽ nhé!) để gắn 1 số domain để phân giải IP trực tiếp, nên bạn hãy vào file host của window (C:\WINDOWS\system32\drivers\etc\hosts) để thêm 1 dòng để nó phân giải tên miền bạn test, trong trường hợp này là myshop.com, sẽ được phân giải thành 127.0.0.1, tức là localhost của chúng ta.
Chỉ cần thêm 1 hàng mới là:
127.0.0.1 myshop.com
sau đó save lại là xong. Nếu bước 1 làm đúng, bạn vào trình duyệt gõ myshop.com thì nó sẽ load nội dung y chang đường dẫn http://localhost/.
Bước 2: Enable module vhost của apache

Bạn vào thư mục Apache trong localhost trên ổ cứng, nếu xài Appserv thì nó mặc định là : C:\AppServ\Apache2.2\conf\,
mở file “httpd.conf”
tìm dòng “#Include conf/extra/httpd-vhosts.conf“, bạn chỉ cần bỏ 1 ký tự dấu # ở đầu dòng này là đã enable module vhost của apache rồi.
Bước 3: Thêm cấu hình cho 1 virtual host

Tiếp tục, bạn vào thư mục “C:\AppServ\Apache2.2\conf\extra“, mở file “httpd-vhosts.conf“, thêm đoạn sau:

ServerName myshop.com
DocumentRoot “C:/AppServ/www/projects/freelanceproj/shopabc”

Khởi động lại server là xong <– Lưu ý chỗ này đó. Ngoài cấu hình domain chính, bạn cũng có thể làm tương tự 3 bước cho các subdomain để test. Các bạn chú ý là có thể đường dẫn của các bạn sẽ khác mình bởi vì có thể các bạn sử dụng bộ localhost khác nhau nên nó install ở các folder khác, nhưng cấu hình ở bước 2,3 đều là cấu hình trong thư mục Apache, bạn thử tìm thì sẽ thấy thôi. Hy vọng bài viết này sẽ giúp ích cho mọi người. Mong nhận sự chia sẽ từ các bạn.

Jquery Demo Effects

Posted: July 4, 2012 in JSEE

//

Show/Hide Panel
Demo
Demo
Demo
Demo
Demo
Show/Hide Panel
Demo
Demo
Demo
Demo

Communication in jsf

Posted: May 8, 2012 in JSEE

This can be done in several ways, with f:setPropertyActionListener, f:attribute and f:param.

f:setPropertyActionListener: with the h:commandLink and h:commandButton tags you can trigger a method of the backing bean using the action or the actionListener attribute. As you cannot directly pass some method parameters from the JSF to the backing bean, the f:setPropertyActionListener tag might be very useful to dynamically set the bean properties which can be used as parameters. This works in JSF 1.2 or newer only. Here is an example:

 

<h:form>
    <h:commandLink value="Click here" action="#{myBean.action}">
        <f:setPropertyActionListener target="#{myBean.propertyName1}" value="propertyValue1" />
        <f:setPropertyActionListener target="#{myBean.propertyName2}" value="propertyValue2" />
    </h:commandLink>

    <h:commandButton value="Press here" action="#{myBean.action}">
        <f:setPropertyActionListener target="#{myBean.propertyName1}" value="propertyValue1" />
        <f:setPropertyActionListener target="#{myBean.propertyName2}" value="propertyValue2" />
    </h:commandButton>
</h:form>

This require at least a setter for propertyName1 and propertyName2 in the backing bean:

package mypackage;

public class MyBean {

    // Init --------------------------------------------------------------------------------------

    private String propertyName1;
    private String propertyName2;

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        System.out.println("propertyName1: " + propertyName1);
        System.out.println("propertyName2: " + propertyName2);
    }

    // Setters -----------------------------------------------------------------------------------

    public void setPropertyName1(String propertyName1) {
        this.propertyName1 = propertyName1;
    }

    public void setPropertyName2(String propertyName2) {
        this.propertyName2 = propertyName2;
    }

}

Now the properties propertyName1 and propertyName2 should contain the values propertyValue1 and propertyValue2 respectively.

f:attribute: with the h:commandLink and h:commandButton tags you can also trigger a method of the backing bean using the actionListener attribute. With this you can also use the f:attribute tag to dynamically pass the parameters. Here is an example:

<h:form>
    <h:commandLink value="Click here" actionListener="#{myBean.action}">
        <f:attribute name="attributeName1" value="attributeValue1" />
        <f:attribute name="attributeName2" value="attributeValue2" />
    </h:commandLink>

    <h:commandButton value="Press here" actionListener="#{myBean.action}">
        <f:attribute name="attributeName1" value="attributeValue1" />
        <f:attribute name="attributeName2" value="attributeValue2" />
    </h:commandButton>
</h:form>

Those attributes can be retrieved using getAttributes() of the parent UI component, which on its turn can be retrieved by the ActionEvent passed by the actionListener.

package mypackage;

import javax.faces.event.ActionEvent;

import net.balusc.util.FacesUtil;

public class MyBean {

    // Actions -----------------------------------------------------------------------------------

    public void action(ActionEvent event) {
        String attributeName1 = FacesUtil.getActionAttribute(event, "attributeName1");
        String attributeName2 = FacesUtil.getActionAttribute(event, "attributeName2");

        System.out.println("attributeName1: " + attributeName1);
        System.out.println("attributeName1: " + attributeName1);
    }

}
package net.balusc.util;

import javax.faces.event.ActionEvent;

public class FacesUtil {

    // Getters -----------------------------------------------------------------------------------

    public static String getActionAttribute(ActionEvent event, String name) {
        return (String) event.getComponent().getAttributes().get(name);
    }

}

The variables attributeName1 and attributeName2 now should contain the values attributeValue1 and attributeValue2 respectively.

Take care that each attribute name should be unique and should not overwrite any default component attributes, like “id”, “name”, “value”, “binding”, “rendered”, etc.

f:param: another way to pass parameters to the backing bean is using the f:param tag. This works on h:commandLink and h:outputLink only. The h:outputLink example is described in the next chapter. Here is the h:commandLink:

 

<h:form>
    <h:commandLink value="Click here" action="#{myBean.action}">
        <f:param name="parameterName1" value="parameterValue1" />
        <f:param name="parameterName2" value="parameterValue2" />
    </h:commandLink>
</h:form>

Those parameters can be retrieved using getRequestParameterMap() of the FacesContext. With the following utility method you can use the f:param name to request the f:param value of any f:param parameter specified in the command block:

package mypackage;

import net.balusc.util.FacesUtil;

public class MyBean {

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        String parameterName1 = FacesUtil.getRequestParameter("parameterName1");
        String parameterName2 = FacesUtil.getRequestParameter("parameterName2");

        System.out.println("parameterName1: " + parameterName1);
        System.out.println("parameterName2: " + parameterName2);
    }

}
package net.balusc.util;

import javax.faces.context.FacesContext;

public class FacesUtil {

    // Getters -----------------------------------------------------------------------------------

    public static String getRequestParameter(String name) {
        return (String) FacesContext.getCurrentInstance().getExternalContext()
            .getRequestParameterMap().get(name);
    }

}

The variables parameterName1 and parameterName2 now should contain the values parameterValue1 and parameterValue2 respectively.

Back to top

Passing GET parameters from JSF to backing beans

This can be done easily using the h:outputLink tag with f:param:

 

<h:outputLink value="mypage.jsf">
    <f:param name="parameterName1" value="parameterValue1" />
    <f:param name="parameterName2" value="parameterValue2" />
    <h:outputText value="Click here" />
</h:outputLink>

Define those parameters in the faces-config.xml:

<managed-bean>
    <managed-bean-name>myBean</managed-bean-name>
    <managed-bean-class>mypackage.MyBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>parameterName1</property-name>
        <value>#{param.parameterName1}</value>
    </managed-property>
    <managed-property>
        <property-name>parameterName2</property-name>
        <value>#{param.parameterName2}</value>
    </managed-property>
</managed-bean>

And add those properties to the backing bean MyBean.java:

package mypackage;

public class MyBean {

    // Init --------------------------------------------------------------------------------------

    private String parameterName1;
    private String parameterName2;

    // Getters -----------------------------------------------------------------------------------

    public String getParameterName1() {
        return parameterName1;
    }

    public String getParameterName2() {
        return parameterName2;
    }

    // Setters -----------------------------------------------------------------------------------

    public void setParameterName1(String parameterName1) {
        this.parameterName1 = parameterName1;
    }

    public void setParameterName2(String parameterName2) {
        this.parameterName2 = parameterName2;
    }

}

The #{param} is a predefinied variable referring to the request parameter map which also can be retrieved by FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap(). Invoking a GET request using the following URL will set the parameter values automatically in the managed bean instance, thanks to the managed-property configuration in the faces-config.xml:
http://example.com/mypage.jsf?parameterName1=parameterValue1&parameterName2=parameterValue2

If you want to execute some action directly after setting of the managed properties, then add a method which you annotate using the @PostConstruct annotation.

    @PostConstruct
    public void doSomeAction() {
        // Do your thing here with parameterName1 and parameterName2!
    }

Which is only available as per JSF 1.2 however. If you’re still using JSF 1.1 or older, then consider adding ‘lazy executing’ to the setter (check if the current property is null and then execute some logic before assigning). This is the opposite of ‘lazy loading’ which can happen in the getter (check if the current property is null and then assign it before returning).

    public void setParameterName1(String parameterName1) {
        if (this.parameterName1 == null) {
            // This will only be executed if the property was null before.
            doSomeAction(parameterName1);
        }
        this.parameterName1 = parameterName1;
    }

    // Or, without passing the parameter (and let the action access the instance variable):

    public void setParameterName2(String parameterName2) {
        boolean wasNull = this.parameterName2 == null;
        this.parameterName2 = parameterName2;
        if (wasNull) {
            // This will only be executed if the property was null before.
            doSomeAction();
        }
    }
Back to top

Passing component attributes from JSF to backing beans

The f:attribute tag can also be used in conjunction with every UI component which is bound to the backing bean using the binding attribute of the UI component. All of those attributes can be retrieved using getAttributes() of the parent UI component. As you cannot directly pass some method parameters from the JSF to the getters and setters of the bound UI component in the backing bean, the f:attribute tag might be very useful to dynamically pass the parameters. Here is a basic JSF example with the h:outputText component bound to the backing bean:

<h:outputText binding="#{myBean.text}" value="#{myBean.textValue}">
    <f:attribute name="attributename" value="attributevalue" />
</h:outputText>

Take care that each attribute name should be unique and should not overwrite any default component attributes, like “id”, “name”, “value”, “binding”, “rendered”, etc.

Here is the dummy example of the backing bean code:

package mypackage;

import javax.faces.component.html.HtmlOutputText;

public class MyBean {

    // Init --------------------------------------------------------------------------------------

    private HtmlOutputText text;

    // Getters -----------------------------------------------------------------------------------

    public HtmlOutputText getText() {
        return text;
    }

    public String getTextValue() {
        return (String) text.getAttributes().get("attributename");
    }

    // Setters -----------------------------------------------------------------------------------

    public void setText(HtmlOutputText text) {
        this.text = text;
    }

}

The value of the h:outputText now should contain the value set in the f:attribute tag.

Back to top

Passing objects from request to request

If you have a request scoped managed bean and you want to reuse a property, parameter and/or object for the next request, without reinitializing it again and again, then just use the h:inputhidden tag to save the object in it. Here is a basic JSF example:

<h:form>
    ...
    <h:inputHidden value="#{myBean.value}" />
    ...
</h:form>

One requirement is that the value should be a String, or Number, or Boolean (where JSF has built-in converters for which automatically converts between them and String) or a primitive, otherwise you have to write a custom converter for it.

You can also use the SessionMap to store the values which should be saved during one user session:

package net.balusc.util;

import javax.faces.context.FacesContext;

public class FacesUtil {

    // Getters -----------------------------------------------------------------------------------

    public static Object getSessionMapValue(String key) {
        return FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(key);
    }

    // Setters -----------------------------------------------------------------------------------

    public static void setSessionMapValue(String key, Object value) {
        FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(key, value);
    }

}

This all is not needed for a session scoped managed bean as the managed bean instance won’t be garbaged and re-instantiated on every request. If you want to remove the value from the SessionMap, then set it to null or just invoke sessionMap.remove(key).

If you want to store static-like variables which are equal and accessible for all sessions, then you can use the ApplicationMap:

package net.balusc.util;

import javax.faces.context.FacesContext;

public class FacesUtil {

    // Getters -----------------------------------------------------------------------------------

    public static Object getApplicationMapValue(String key) {
        return FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().get(key);
    }

    // Setters -----------------------------------------------------------------------------------

    public static void setApplicationMapValue(String key, Object value) {
        FacesContext.getCurrentInstance().getExternalContext().getApplicationMap().put(key, value);
    }

}

Of course this one is also not needed for an application scoped managed bean.

An alternative to the above is the Tomahawk’s t:saveState tag. It is similar the h:inputHidden, with the biggest difference that you can pass non-standard object types (such as managed beans, collections, custom objects, etc) along it while the h:inputHidden only accepts standard object types (String, Number, Boolean) as long as you don’t supply a Converter.

Back to top

Passing new hidden values to backing beans

If you want to pass new hidden input values to the backing beans, then there are two general ways. One way where you use a plain vanilla HTML hidden input field with the hardcoded value and another way where you use the JSF h:inputHidden whose value is manipulated with Javascript.

Here is the hardcoded example, you can use a plain vanilla HTML hidden input field with a form-unique name. Its value will be available in the getRequestParameterMap(). You can obtain it directly in the action method or even define a managed property for it in the backing bean. The example below makes use of the managed-property entry.

<h:form>
    <h:commandButton value="submit" action="#{myBean.action}" />
    <input type="hidden" name="hiddenInput" value="foo" />
</h:form>

The relevant part of the faces-config.xml:

<managed-bean>
    <managed-bean-name>myBean</managed-bean-name>
    <managed-bean-class>mypackage.MyBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>hiddenInput</property-name>
        <value>#{param.hiddenInput}</value>
    </managed-property>
</managed-bean>

The backing bean (the getter is indeed not required):

package mypackage;

import javax.faces.context.FacesContext;

public class MyBean {

    // Init --------------------------------------------------------------------------------------

    private String hiddenInput;

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        System.out.println("hiddenInput: " + hiddenInput);

        // It is also available as follows:
        System.out.println(FacesContext.getCurrentInstance().getExternalContext()
            .getRequestParameterMap().get("hiddenInput"));
        // In this case the property as well as managed-property are redundant.
    }

    // Setters -----------------------------------------------------------------------------------

    public void setHiddenInput(String hiddenInput) {
        this.hiddenInput = hiddenInput;
    }

}

Here is the Javascript way, you can just use the h:inputHidden component and manipulate its value using Javascript. All what you need to know in the Javascript side is the client ID of the h:inputHidden component. Check the generated HTML source if you’re unsure.

<h:form id="form">
    <h:commandButton value="submit" action="#{myBean.action}"
        onclick="document.getElementById('form:hiddenInput').value = 'foo';" />
    <h:inputHidden id="hiddenInput" value="#{myBean.hiddenInput}" />
</h:form>

The relevant part of the faces-config.xml, there is no managed property needed:

<managed-bean>
    <managed-bean-name>myBean</managed-bean-name>
    <managed-bean-class>mypackage.MyBean</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

The backing bean:

package mypackage;

public class MyBean {

    // Init --------------------------------------------------------------------------------------

    private String hiddenInput;

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        System.out.println("hiddenInput: " + hiddenInput);
    }

    // Getters -----------------------------------------------------------------------------------

    public String getHiddenInput() {
        return hiddenInput;
    }

    // Setters -----------------------------------------------------------------------------------

    public void setHiddenInput(String hiddenInput) {
        this.hiddenInput = hiddenInput;
    }

}
Back to top

Communication between managed beans

You can have more than one managed bean in a scope. If required by design, then you can use getSessionMap() of the FacesContext to communicate between the managed beans during one browser session. This can be very useful for user-sessions by example.

An example of two managed beans in the faces-config.xml:

<managed-bean>
    <managed-bean-name>myBean1</managed-bean-name>
    <managed-bean-class>mypackage.MyBean1</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

<managed-bean>
    <managed-bean-name>myBean2</managed-bean-name>
    <managed-bean-class>mypackage.MyBean2</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

The managed beans myBean1 and myBean2 are instances of the backing beans MyBean1.java and MyBean2.java, which can be accessed by JSF pages. It don’t matter whether the managed-bean-scope is set to request or session. With the managed-bean-scope set to session, the same instance of the backing bean will be used during the whole session. When the scope is set to request, then each request (form action) will create a new instance of the backing bean everytime.

You can use the getSessionMapValue() and setSessionMapValue() of the FacesUtil which is mentioned in the former paragraph to get and set values in the SessionMap. Here is an use example:

package mypackage;

import net.balusc.util.FacesUtil;

public class MyBean1 {

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        String value = "value1";
        FacesUtil.setSessionMapValue("MyBean1.value", value);
    }

}
package mypackage;

import net.balusc.util.FacesUtil;

public class MyBean2 {

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        String value = (String) FacesUtil.getSessionMapValue("MyBean1.value");
    }

}

The variable value now should contain the value value1. Of course only if already set by another managed bean.

Back to top

Injecting managed beans in each other

You can also inject the one managed bean in the other managed bean as a property. This may be useful if you have an application scoped bean for e.g. configurations and you want to use it in a session or request scoped bean. This is also useful if you want to keep the large data of datatables in session scope and the form actions in request scope.

Here is an example of an application scoped and request scoped managed bean in the faces-config.xml where the application scoped bean is injected in the request scoped bean:

<managed-bean>
    <managed-bean-name>myBean1</managed-bean-name>
    <managed-bean-class>mypackage.MyBean1</managed-bean-class>
    <managed-bean-scope>application</managed-bean-scope>
</managed-bean>

<managed-bean>
    <managed-bean-name>myBean2</managed-bean-name>
    <managed-bean-class>mypackage.MyBean2</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
    <managed-property>
        <property-name>myBean1</property-name>
        <value>#{myBean1}</value>
    </managed-property>
</managed-bean>

Where the MyBean2 look like:

package mypackage;

public class MyBean2 {

    // Init --------------------------------------------------------------------------------------

    private MyBean1 myBean1;

    // Getters -----------------------------------------------------------------------------------

    public MyBean1 getMyBean1() {
        return myBean1;
    }

    // Setters -----------------------------------------------------------------------------------

    public void setMyBean1(MyBean1 myBean1) {
        this.myBean1 = myBean1;
    }

}
Back to top

Accessing another managed bean

If you have more than one managed bean in a scope and you want to get the current instance of the another managed bean and get access to its properties, then there are eight ways to get the instance using the FacesContext. You can use getRequestMap, getSessionMap, getApplicationMap, getVariableResolver, createValueBinding, getELResolver (since JSF 1.2), createValueExpression (since JSF 1.2) or evaluateExpressionGet (since JSF 1.2). The first three ways will not implicitly create the bean if it is not already created by JSF or yourself. The last five ways will do.

An example of two managed beans in the faces-config.xml:

<managed-bean>
    <managed-bean-name>myBean1</managed-bean-name>
    <managed-bean-class>mypackage.MyBean1</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

<managed-bean>
    <managed-bean-name>myBean2</managed-bean-name>
    <managed-bean-class>mypackage.MyBean2</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

The managed beans myBean1 and myBean2 are instances of the backing beans MyBean1.java and MyBean2.java, which can be accessed by JSF pages. It don’t matter whether the managed-bean-scope is set to request or session. Only take care that you can use the getRequestMap method only when the scope of the another managed bean is set to request, and you can use the getSessionMap only when the scope of the another managed bean is set to session.

The JSF use example:

<h:form>
    <h:commandButton action="#{myBean1.action1}" value="action1" />
    <h:commandButton action="#{myBean1.action2}" value="action2" />
    <h:commandButton action="#{myBean1.action3}" value="action3" />
    <h:commandButton action="#{myBean1.action4}" value="action4" />
    <h:commandButton action="#{myBean1.action5}" value="action5" />
    <h:commandButton action="#{myBean1.action6}" value="action6" />
    <h:commandButton action="#{myBean1.action7}" value="action7" />
    <h:commandButton action="#{myBean1.action8}" value="action8" />
    <h:outputText binding="#{myBean2.text}" />
</h:form>

Here is the first bean, MyBean1.java. Note that you should access the another managed bean by the managed-bean-name as definied in the faces-config.xml.

package mypackage;

import javax.faces.context.FacesContext;

public class MyBean1 {

    // Actions -----------------------------------------------------------------------------------

    // Using RequestMap. NOTE: myBean2 should be request scoped and already created!
    public void action1() {
        MyBean2 myBean2 = (MyBean2) FacesContext.getCurrentInstance().getExternalContext()
            .getRequestMap().get("myBean2");

        // This only works if myBean2 is request scoped and already created.
        if (myBean2 != null) {
            myBean2.getText().setValue("action1");
        }
    }

    // Using SessionMap. NOTE: myBean2 should be session scoped and already created!
    public void action2() {
        MyBean2 myBean2 = (MyBean2) FacesContext.getCurrentInstance().getExternalContext()
            .getSessionMap().get("myBean2");

        // This only works if myBean2 is session scoped and already created.
        if (myBean2 != null) {
            myBean2.getText().setValue("action2");
        }
    }

    // Using ApplicationMap. NOTE: myBean2 should be application scoped and already created!
    public void action3() {
        MyBean2 myBean2 = (MyBean2) FacesContext.getCurrentInstance().getExternalContext()
            .getApplicationMap().get("myBean2");

        // This only works if myBean2 is application scoped and already created.
        if (myBean2 != null) {
            myBean2.getText().setValue("action3");
        }
    }

    // Using VariableResolver. NOTE: this is deprecated since JSF 1.2!
    public void action4() {
        FacesContext context = FacesContext.getCurrentInstance();
        MyBean2 myBean2 = (MyBean2) context.getApplication()
            .getVariableResolver().resolveVariable(context, "myBean2");

        myBean2.getText().setValue("action4");
    }

    // Using ValueBinding. NOTE: this is deprecated since JSF 1.2!
    public void action5() {
        FacesContext context = FacesContext.getCurrentInstance();
        MyBean2 myBean2 = (MyBean2) context.getApplication()
            .createValueBinding("#{myBean2}").getValue(context);

        myBean2.getText().setValue("action5");
    }

    // Using ELResolver. NOTE: this is implemented since JSF 1.2!
    public void action6() {
        FacesContext context = FacesContext.getCurrentInstance();
        MyBean2 myBean2 = (MyBean2) context.getELContext()
            .getELResolver().getValue(context.getELContext(), null, "myBean2");

        myBean2.getText().setValue("action6");
    }

    // Using ValueExpression. NOTE: this is implemented since JSF 1.2!
    public void action7() {
        FacesContext context = FacesContext.getCurrentInstance();
        MyBean2 myBean2 = (MyBean2) context.getApplication().getExpressionFactory()
            .createValueExpression(context.getELContext(), "#{myBean2}", MyBean2.class)
                .getValue(context.getELContext());

        myBean2.getText().setValue("action7");
    }

    // Using evaluateExpressionGet. NOTE: this is implemented since JSF 1.2!
    public void action8() {
        FacesContext context = FacesContext.getCurrentInstance();
        MyBean2 myBean2 = (MyBean2) context.getApplication()
            .evaluateExpressionGet(context, "#{myBean2}", MyBean2.class);

        myBean2.getText().setValue("action8");
    }

}

The second bean, MyBean2.java:

package mypackage;

import javax.faces.component.html.HtmlOutputText;

public class MyBean2 {

    // Init --------------------------------------------------------------------------------------

    private HtmlOutputText text;

    // Getters -----------------------------------------------------------------------------------

    public HtmlOutputText getText() {
        return text;
    }

    // Setters -----------------------------------------------------------------------------------

    public void setText(HtmlOutputText text) {
        this.text = text;
    }

}

You’ll probably question: Which is the best way then?? Use the evaluateExpressionGet approach (which is by the way just a shorthand for the ValueExpression approach). For ones who are still sitting with the ancient JSF 1.1 or older, then go ahead with ValueBinding approach.

Back to top

Returning current managed bean instance of self

You can also let the backing bean return the current managed bean instance of self using a static method. Here is an example with a request scoped managed bean:

<managed-bean>
    <managed-bean-name>myBean1</managed-bean-name>
    <managed-bean-class>mypackage.MyBean1</managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

<managed-bean>
    <managed-bean-name>myBean2</managed-bean-name>
    <managed-bean-class>mypackage.MyBean2</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

Where the MyBean1 look like:

package mypackage;

import javax.faces.context.FacesContext;

public class MyBean1 {

    // Init --------------------------------------------------------------------------------------

    private static final String MANAGED_BEAN_NAME = "myBean1";

    // Actions -----------------------------------------------------------------------------------

    public static MyBean1 getCurrentInstance() {
        return (MyBean1) FacesContext.getCurrentInstance().getExternalContext()
            .getRequestMap().get(MANAGED_BEAN_NAME);
    }

}

So you can get the current instance of MyBean1 in the another bean as follows:

package mypackage;

public class MyBean2 {

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        MyBean1 myBean1 = MyBean1.getCurrentInstance();
    }

}

You can find an use example in the FriendlyUrlAction bean in the Friendly URL’s in JSF article.

Back to top

Lookup the managed bean name inside the backing bean

You can have more than one managed bean instance of the same backing bean. This might be useful if you want to implement different ways to use the backing bean. When you need to know the assigned managed bean name inside the current instance of the backing bean, then you need to lookup the values of the requestmap, sessionmap or applicationmap and compare them with the current instance of the backing bean. If it is equal, then the associated key is the same as the managed bean name.

package net.balusc.util;

import java.util.Map;

import javax.faces.context.ExternalContext;

public class FacesUtil {

    // Helpers -----------------------------------------------------------------------------------

    public static String lookupManagedBeanName(Object bean) {
        ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();

        // Get requestmap.
        Map<String, Object> requestMap = externalContext.getRequestMap();

        // Lookup the current bean instance in the request scope.
        for (String key : requestMap.keySet()) {
            if (bean.equals(requestMap.get(key))) {
                // The key is the managed bean name.
                return key;
            }
        }

        // Bean is not in the request scope. Get the sessionmap then.
        Map<String, Object> sessionMap = externalContext.getSessionMap();

        // Lookup the current bean instance in the session scope.
        for (String key : sessionMap.keySet()) {
            if (bean.equals(sessionMap.get(key))) {
                // The key is the managed bean name.
                return key;
            }
        }

        // Bean is also not in the session scope. Get the applicationmap then.
        Map<String, Object> applicationMap = externalContext.getApplicationMap();

        // Lookup the current bean instance in the application scope.
        for (String key : applicationMap.keySet()) {
            if (bean.equals(applicationMap.get(key))) {
                // The key is the managed bean name.
                return key;
            }
        }

        // Bean is also not in the application scope.
        // Is the bean's instance actually a managed bean instance then? =)
        return null;
    }

}

You can call it as follows:

package mypackage;

import net.balusc.util.FacesUtil;

public class MyBean {

    // Actions -----------------------------------------------------------------------------------

    public void action() {
        String managedBeanName = FacesUtil.lookupManagedBeanName(this);
    }

}

Although remember that this is not always a good practice. If you can, rather subclass (extend) the backing bean into another backing bean and if necessary override or add some more code. Then assign another managed bean name to the subclassed backing bean.

Back to top

Accessing the FacesContext inside HttpServlet or Filter

Other Servlets than the FacesServlet and all Filters cannot directly access the FacesContext in the same web container, because they are sitting in the ServletContext outside the FacesContext. When you want to request the FacesContext instance outside the FacesContext, you’ll get FacesContext.getCurrentInstance() == null. In this case you need to precreate the FacesContext yourself.

package mypackage;

import java.io.IOException;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.balusc.util.FacesUtil;

public class MyServlet extends HttpServlet {

    // Actions -----------------------------------------------------------------------------------

    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        doSomething(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        doSomething(request, response);
    }

    private void doSomething(HttpServletRequest request, HttpServletResponse response) {

        // Get the FacesContext inside HttpServlet.
        FacesContext facesContext = FacesUtil.getFacesContext(request, response);

        // Now you can do your thing with the facesContext.
    }

}

And here is how you can precreate the FacesContext:

package net.balusc.util;

import javax.faces.FactoryFinder;

import javax.faces.component.UIViewRoot;
import javax.faces.context.FacesContext;
import javax.faces.context.FacesContextFactory;
import javax.faces.lifecycle.Lifecycle;
import javax.faces.lifecycle.LifecycleFactory;
import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class FacesUtil {

    // Getters -----------------------------------------------------------------------------------

    public static FacesContext getFacesContext(
        HttpServletRequest request, HttpServletResponse response)
    {
        // Get current FacesContext.
        FacesContext facesContext = FacesContext.getCurrentInstance();

        // Check current FacesContext.
        if (facesContext == null) {

            // Create new Lifecycle.
            LifecycleFactory lifecycleFactory = (LifecycleFactory)
                FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY); 
            Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);

            // Create new FacesContext.
            FacesContextFactory contextFactory  = (FacesContextFactory)
                FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
            facesContext = contextFactory.getFacesContext(
                request.getSession().getServletContext(), request, response, lifecycle);

            // Create new View.
            UIViewRoot view = facesContext.getApplication().getViewHandler().createView(
                facesContext, "");
            facesContext.setViewRoot(view);                

            // Set current FacesContext.
            FacesContextWrapper.setCurrentInstance(facesContext);
        }

        return facesContext;
    }

    // Helpers -----------------------------------------------------------------------------------

    // Wrap the protected FacesContext.setCurrentInstance() in a inner class.
    private static abstract class FacesContextWrapper extends FacesContext {
        protected static void setCurrentInstance(FacesContext facesContext) {
            FacesContext.setCurrentInstance(facesContext);
        }
    }     

}

Think twice about this practice and don’t misuse it. If you’re using a Filter and you want to access the FacesContext, then rather use a PhaseListener instead and listen on the first phase (the PhaseId.RESTORE_VIEW). If you just want to pass objects (attributes) from the ServletContext to the FacesContext using a HttpServlet, then rather use the getAttribute() and setAttribute() methods of the HttpServletRequest (which reflects to the RequestMap), or the HttpSession (which reflects to the SessionMap), or the ServletContext (which reflects to the ApplicationMap).

The HttpSession is accessible in the HttpServlet using HttpServletRequest#getSession() and the ServletContext is accessible in the HttpServlet using the inherited method getServletContext().

Reset password in SVN

Posted: May 3, 2012 in JSEE

The Problem

When you open a project from Subversion repository AnkhSVN will prompt you to authenticate (If you have turned on security in your subversion repository). Once you enter your username and password and check the save password it will not prompt again.

Now what if you change your password? I googled about this for two days but didn’t find any solution. Luckily today my boss found this.
The Solution

The authentication data is saved to the following directories

%APPDATA%\Subversion\auth\svn.ssl.server
%APPDATA%\Subversion\auth\svn.simple

Deleting all the files inside these folders will solve the problem. After deleting these files AnkhSVN will prompt you for username and password once again.

I am currently writing a small Visual Studio Add-in that will help you clear these information from within Visual Studio.

http://www.roseindia.net/jsf/richfaces/

 

Uploading Files in NetBeans Visual Web JSF Applications

Contents:

  1. Machine specifications used in this tutorial

  2. About the File Upload Component

  3. Creating a Page That Includes a File Upload Component

  4. Adding Code to Handle Image Uploads

  5. Testing the Application

  6. Doing More #1: Uploading a Text File

  7. Doing More #2: Modifying the Maximum File Upload Size

  8. Doing More #3: Saving the Uploaded Files to Other Locations

  9. A Different Folder in the Web Application

  10. A Known Directory on the Server

About the File Upload Component

The File Upload component enables users of your web application to locate a file on their system and upload that file to the server. This component is useful for collecting text files, image files, and other data. The contents of the uploaded file are stored together with some information about the file, including the file name, size, and MIME type (such as text/plain or image/jpeg).

The server holds the uploaded file in memory unless it exceeds 4096 bytes (4Kb), in which case the server holds the file contents in a temporary file. You can change this threshold by modifying the sizeThreshold parameter for the UploadFilter filter entry in the web application’s web.xml file. For more information on modifying the web.xml file, see the last section in this tutorial, Doing More: Modifying the Maximum File Upload Size. In cases where you want to retain the uploaded file, you have three choices:

  • Write the file to a location of your choice, as shown in this tutorial.
  • Create an UploadedFile property in a managed bean and set it to the component’s value before you exit the page (as in the button’s action method).
  • Save the file to a database that means in the table’s cell as other data or as normally done, save the file links in the database and the files to a location of your choice (under a folder).

By default, the File Upload component can handle files up to one megabyte in size. You can change the maximum file size by modifying the maxSize parameter for the UploadFilter filter entry in the application’s web.xml file, as described in the last section in this tutorial, Doing More: Modifying the Maximum File Upload Size.

Creating a Page That Includes a File Upload Component

First, you build a form that enables users to select a file to upload.

1.      Create a new Web Application project, name it FileUploadExample, and enable the Visual Web JavaServer Faces framework. The figure below shows the page that you will create in the steps that follow:

Let begin from scratch.

2.      From the Basic section of the Palette, drop a Label component on the page, type Choose a File to Upload: and press Enter.

3.      Drag a File Upload component onto the page and drop it underneath the Label component.

4.      Drag a Button component onto the page, type Upload File, and press Enter. In the Properties window, set the Button’s id property to uploadFileButton.

5.      Drag a Label component onto the page and set the text to File Name:

6.      Place a Static Text component to the right of the Label. In the Properties window, set the Static Text’s id property to fileNameStaticText.

7.      Drag another Label onto the page. Set the text of the Label to File Type:

8.      Place a Static Text component to the right of the new Label. Set the id of the Static Text to fileTypeStaticText.

9.      Drag another Label and Static Text pair onto the page. Set the text of the Label to File Size: and the id of the Static Text to fileSizeStaticText.

10. Place an Image component below the Static Text components.

 

11. Place a Message Group component below the Image component.

Adding Code to Handle Image Uploads

Now that you have the basic file upload form, you must add code to handle the file upload.

1.      Double-click the Upload File button to open the Java Editor and add the button’s event handler, uploadFileButton_action, to the page bean. Before adding code to this method, you define variables for storing the image file and add code to the init() and prerender() methods.

2.      Scroll up to the init() method and add the following two variables before the method.

Code Sample 1: Variables

private String realImageFilePath;

private static final String IMAGE_URL = “/resources/image-file”;

The variable realImageFilePath is the actual path and filename of the image file on the server. The IMAGE_URL variable is the logical path of the image file in the running web application. So these are a logical and physical path for the image file.

3.      Add the following lines of bold (shown in bold) at the end of the init method, but note that the code contains a Class Not Found error. You add import statements to fix these errors in next step. After inserting the code, you can press Ctrl-Shift-F to reformat the code.

Code Sample 2: init Method

public void init() {

   super.init();

     // Perform application initialization that must complete

     // *before* managed components are initialized

     // TODO – add your own initialization code here

                

     // Managed Component Initialization

     // Perform application initialization that must complete

     // *after* managed components are initialized

     // TODO – add your own initialization code here

     ServletContext theApplicationsServletContext =

         (ServletContext) this.getExternalContext().getContext();

     this.realImageFilePath = theApplicationsServletContext.getRealPath(IMAGE_URL);

}

This code converts IMAGE_URL into the real image file path so that the file can be written to the correct directory on the server.

4.      Scroll to the prerender method and add the following code:

Code Sample 3: prerender Method

public void prerender() {

   String uploadedFileName = (String) this.fileNameStaticText.getValue();

        if (uploadedFileName != null) {

            image1.setUrl(this.realImageFilePath);

            }

}


If there is an image file to display, this code binds the file to the Image component. The image1 is the image component id.

5.      Add the following code to the uploadFileButton_action() method.

Code Sample 4: Code to Upload an Image File

public String uploadFileButton_action() {

        UploadedFile uploadedFile = fileUpload1.getUploadedFile();

        if( uploadedFile == null )

            return null;

        String uploadedFileName = uploadedFile.getOriginalName();

        // Some browsers return complete path name, some don’t

        // Make sure we only have the file name

        // First, try forward slash

        int index = uploadedFileName.lastIndexOf(‘/’);

        String justFileName;

        if (index >= 0)

  {

            justFileName = uploadedFileName.substring( index + 1 );

        } else {

            // Try backslash

            index = uploadedFileName.lastIndexOf(‘\\’);

            if (index >= 0) {

                justFileName = uploadedFileName.substring( index + 1 );

            } else {

                // No forward or back slashes

                justFileName = uploadedFileName;

            }

        }

        this.fileNameStaticText.setValue(justFileName);

        Long uploadedFileSize = new Long(uploadedFile.getSize());

        this.fileSizeStaticText.setValue(uploadedFileSize);

        String uploadedFileType = uploadedFile.getContentType();

        this.fileTypeStaticText.setValue(uploadedFileType);

        if ( uploadedFileType.equals(“image/jpeg”)

        || uploadedFileType.equals(“image/pjpeg”)

        || uploadedFileType.equals(“image/gif”)

        || uploadedFileType.equals(“image/png”)

        || uploadedFileType.equals(“image/x-png”)) {

            try {

                File file = new File(this.realImageFilePath);

                uploadedFile.write(file);

            } catch (Exception ex) {

                error(“Cannot upload file: ” + justFileName);

            }

        } else {

            error(“You must upload a JPEG, PJPEG, GIF, PNG, or X-PNG file. “);

            new File(this.realImageFilePath).delete();

        }

   return null;

}

Correct all the formatted characters such as double and single quotes if needed. For each file, the program extracts the file name, size, and type from the UploadedFile object and binds them to the Static Text components. The program makes a key decision with all uploads: If the file is a JPEG, PJPEG, GIF, PNG, or X-PNG file, the program saves the uploaded file to the realImageFilePath variable. If the file is not a valid image file or if there are other problems uploading the file, the program deletes the image from the server and displays an error message.

6.      Right-click in the Java Editor and choose Fix Imports. In the Fix Import dialog box, ensure that java.io.File appears in the File dropdown list, and click OK. This action fixes the errors in the code.

Testing the Application

1.      Run the application by clicking the icon.

2.      Click Browse to navigate through your local drives and select an image file to upload. Then click the Upload File button.

3.       The following figure shows the application with an uploaded JPEG file. The image is stored in project-directory\FileUploadExample\build\web\resources.

In the browser address bar you can see something like the following address.

http://localhost:8080/FileUploadExample/faces/Page1.jsp;jsessionid=269b734bcc82f032446401390f6d

4.      Enter a text file in the File Upload component and click the Upload File button. Verify that the error message displays. Note: The rendering of the File Upload component can differ depending on the web browser. Be sure to test this component in the web browsers that you expect your users to use.

Doing More #1: Uploading a Text File

This section is a mini-tutorial on how to upload a text file. This example displays the file contents in a text area component, and the file name and size in a message group component. This example does not save the contents of the file. To do so, you must add code to save the file to disk, as shown in the previous example.

1.      Create a new Web Application project named UploadTextFile and enables the Visual Web JavaServer Faces framework.

2.      Drag a File Upload component onto the page.

3.      Add a Button component, a Text Area component, and a Message Group component.

———————————————————————————————————————————

 

———————————————————————————————————————————

Resize the Text Area component as needed.

4.      Double-click the Button component and add the following action code to the button1_action() method:

Code Sample 5: Code to Upload a Text File

public String button1_action() {

   UploadedFile uploadedFile = (UploadedFile) fileUpload1.getUploadedFile();

   if( uploadedFile == null )

       return null;

   info(“Uploaded file originally named ‘” + uploadedFile.getOriginalName() + “‘ of size ‘” +  uploadedFile.getSize() +  “‘”);

   textArea1.setText(uploadedFile.getAsString());

   return null;

  }

5.      Press Ctrl-Shift-I or right-click and select Fix Imports to fix imports and automatically add the UploadedFile import statement.

6.      Run the application. The following figure shows a sample page with an uploaded text file.

7.      Click the Browse button to select a text file for uploading.

8.      Click the Button button.

Doing More #2: Modifying the Maximum File Upload Size

To enable the upload of a file greater than one megabyte (such as a large image file, ZIP, JAR, or executable file), you must modify the maxSize parameter for the UploadFilter filter in your application’s web.xml file.

1.      Open the Files window and expand project-name > web > WEB-INF.

2.      Right-click the web.xml node and choose Edit.

3.      In the XML editor, click the Filters button.

4.      Select the maxSize parameter for the UploadFilter, and click the Edit button.

5.      In the dialog box, set Param Value to the desired value, in this case we change 1MB to 10 MB and click OK.

6.      Note: For security reasons, do not set the maxSize parameter to a negative value, which indicates that there is no file size limit.

7.      Choose File > Save or click the Save All button to save your changes.

Note: If a user of your application tries to upload a file larger than the value of the maxSize parameter, the following exception is thrown and caught as a validation error:

org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException

The summary message displayed to users reads:

No file was uploaded

The detail message reads:

No file was uploaded. The specified file exceeds the maximum allowable size of 10000000 Mb

where 10000000 Mb is the value of maxSize.

Doing More #3: Saving the Uploaded Files to Other Locations

The previously completed tutorial shows how to upload a file to the web application’s /resources folder. What if you want to save the uploaded files elsewhere? Here are some alternatives.

A Different Folder in the Web Application

You can put the images in any directory in the web application (that is, any directory under the web application’s web directory). For example, you can create an upload/images subfolder under web and use the following code to store the images there:

Code Sample 6: Code to Upload a File to a Different Folder

String realPath = theApplicationsServletContext.getRealPath(“/upload/images”);

File file = new File(realPath + File.separatorChar + justFileName);

Be careful when putting the uploaded files in the web application because anyone can access the files by URL, such as:

http://localhost:29080/MyWebApplication/faces/upload/images/myPicture.gif.

You may want to put an index.html/index.htm/index.asp/index.php file (the first default web page) in the folder so that when user tries to go directly to the sub folder, the index.html file will be loaded. Then in the index.* file, create a link to the main application page. User will see something like the following where user can browse your web directory if there is no index file. Keep in mind that this folder has write permission for certain image file types.

Let modify the previous FileUploadExample. Create a /upload/images folder under the project’s web folder as shown below.

Re-open the project. Change the variables declaration to the following.

private String realPath;

private static final String IMAGE_URL = “/upload/images”;

 

Change the init() to the following. The realPath only hold the path and not the image file.

ServletContext theApplicationsServletContext=(ServletContext) this.getExternalContext().getContext();

       realPath = theApplicationsServletContext.getRealPath(IMAGE_URL);

Change the prerender to the following code. We display the image when user selects a file from the File Upload component. We read the file from the selected image file.

String uploadedFileName = (String) this.fileNameStaticText.getValue();

        if (uploadedFileName != null) {

              /* path + \ or \\ + filename */

            image1.setUrl(IMAGE_URL + File.separatorChar + uploadedFileName);

        }

Finally change the following code in the uploadFileButton_action()

File file = new File(this.realImageFilePath);

To

File file = new File(realPath + File.separatorChar + justFileName);

Run your project.

Browse an image and click the Upload File button.

Try several more images and then verify the uploaded images in the upload/images folder.

A Known Directory on the Server

To store the images somewhere else on the server, you can use code such as the following:

Code Sample 7: Code to Upload a File to a Known Directory on a Server

File file = new File(“C:/upload/images” + File.separatorChar + justFileName);

uploadedFile.write(file);

Create upload/images folder on your C drive.

Change the following code in the uploadFileButton_action()

File file = new File(realPath + File.separatorChar + justFileName);

to

File file = new File(“C:/upload/images” + File.separatorChar + justFileName);

Run your project.

Select an image and click the Upload File button. Upload several more images.

Verify the uploaded files.

If you plan to deploy the application to different servers, you might use code like the following to ensure that the upload directory exists:

Code Sample 8: Code to Upload a File to Different Servers

File dir = new File(“C:/upload/images”);

if (! dir.exists())

dir.mkdirs();

File file = new File(dir.getCanonicalPath() + File.separatorChar + justFileName);

uploadedFile.write(file);

For more information about the File class, see Java File class.

An As-Yet Unknown Directory

Another alternative is to put the directory path in the deployment descriptor so that you can change the location dynamically.

1.      In the Files window, expand the web node and then expand WEB-INF. Double-click web.xml to open it.

2.      Click the General button and expand Context Parameters, and click the Add button.

3.      Set the following values, and then click OK.

Param Name: uploadDirectory (or whatever you want to name it)

Param Value: C:/upload/images (or whatever your path is)

4.      Close and save the web.xml file.

5.      Use the following code:

Code Sample 9: Code to Upload a File to an As-Yet Unknown Directory

String uploadDirectory = getExternalContext().getInitParameter(“uploadDirectory”);

File file = new File(uploadDirectory + File.separatorChar + justFileName);

uploadedFile.write(file);

http://www.javaguicodexample.com/javawebappjsfnetbeansuploadfiles8.html

Upload File in Richfaces

Posted: April 26, 2012 in JSEE

<ui:composition xmlns=”http://www.w3.org/1999/xhtml&#8221;
xmlns:ui=”http://java.sun.com/jsf/facelets&#8221;
xmlns:h=”http://java.sun.com/jsf/html&#8221;
xmlns:f=”http://java.sun.com/jsf/core&#8221;
xmlns:a4j=”http://richfaces.org/a4j&#8221;
xmlns:rich=”http://richfaces.org/rich”&gt;

<style>
.top {
vertical-align: top;

}
.info {
height: 202px;
overflow: auto;
}
</style>

<h:form>
<h:panelGrid columns=”2″ columnClasses=”top,top”>
<rich:fileUpload fileUploadListener=”#{fileUploadBean.listener}”
maxFilesQuantity=”#{fileUploadBean.uploadsAvailable}”
id=”upload”
immediateUpload=”#{fileUploadBean.autoUpload}”
acceptedTypes=”jpg, gif, png, bmp” allowFlash=”#{fileUploadBean.useFlash}”>
<a4j:support event=”onuploadcomplete” reRender=”info” />
</rich:fileUpload>
<h:panelGroup id=”info”>
<rich:panel bodyClass=”info”>
<f:facet name=”header”>
<h:outputText value=”Uploaded Files Info” />
</f:facet>
<h:outputText value=”No files currently uploaded”
rendered=”#{fileUploadBean.size==0}” />
<rich:dataGrid columns=”1″ value=”#{fileUploadBean.files}”
var=”file” rowKeyVar=”row”>
<rich:panel bodyClass=”rich-laguna-panel-no-header”>
<h:panelGrid columns=”2″>
<a4j:mediaOutput element=”img” mimeType=”#{file.mime}”
createContent=”#{fileUploadBean.paint}” value=”#{row}”
style=”width:100px; height:100px;” cacheable=”false”>
<f:param value=”#{fileUploadBean.timeStamp}” name=”time”/>
</a4j:mediaOutput>
<h:panelGrid columns=”2″>
<h:outputText value=”File Name:” />
<h:outputText value=”#{file.name}” />
<h:outputText value=”File Length(bytes):” />
<h:outputText value=”#{file.length}” />
</h:panelGrid>
</h:panelGrid>
</rich:panel>
</rich:dataGrid>
</rich:panel>
<rich:spacer height=”3″/>
<br />
<a4j:commandButton action=”#{fileUploadBean.clearUploadData}”
reRender=”info, upload” value=”Clear Uploaded Data”
rendered=”#{fileUploadBean.size>0}” />
</h:panelGroup>
</h:panelGrid>
</h:form>
</ui:composition>

http://livedemo.exadel.com/richfaces-demo/richfaces/fileUpload.jsf