0

I'm using JSF,... I thought this is a stupid question but really i don't understand. My question: I have a jsf page: /product.xhtml

<f:metadata>
    <f:viewParam name="p" value="#{singleProduct.p}" />
</f:metadata>
...
<h:form>
        <h:inputTextarea value="#{singleProduct.content}" />
        <h:commandLink value="Comment" action="#{singleProduct.postComment}" />
</h:form>

And my bean: SingleProduct

@Named
@SessionScoped
@Inject
private ProductService productService; //EJB
private int p;
private String content;
//Getters and setters;

public void postComment(){
  productService.addComment(p,content); //addComment(int productId, String commentContent)
}

Now, i open a tab of browser with URL: /product.xhtml?p=1. Then open another tab with URL:/product.xhtml?p=2. Then return to tab with URL: /product.xhtml?p=1 to type and submit form. I want to ask: The comment that is saved to database with how many productId values: 1 or 2 ? I thought my question is related to state of JSF, but i don't understand about it clearly. Thanks

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Lost Heaven 0809
  • 396
  • 2
  • 7
  • 23
  • Related: http://stackoverflow.com/questions/7031885/how-to-choose-the-right-bean-scope/7031941#7031941 – BalusC Nov 12 '13 at 11:30

1 Answers1

1

You need to understand the lifetime of differently scoped beans to answer your question on your own. Session scoped data lives until the session has ben invalidated or it has timed out due to a period of inactivity. It can be created implicitly by JSF when it's first needed, i.e. when you access session bean in your view via EL. You can of course create session beforehand on your own, or remove session attributes, which beans (or proxies) are, but I think that it's not your scenario.

HTTP session is unique for some period of time per one browser that may have different tabs opened. So, as there is one bean whose values keep on being overwritten there are clear scoping problems. you ultimately don't want your message to be written to a different id, do you? Essentially you want unique data (bean) to be on a per-view basis, thus you need @ViewScoped bean.

skuntsel
  • 11,624
  • 11
  • 44
  • 67
  • I know about lifetime of differently scoped beans and i know about '@ViewScoped'. But before JSF 2.2, CDI bean don't have '@ViewScoped'. Really, i don't like Managed bean because of its limitation. Based on your answer, p = 2 ? what happen if i use '@RequestScoped' ? – Lost Heaven 0809 Nov 12 '13 at 08:13
  • Request scoped bean will be created upon every page submit and view parameter will also be set on postback, so in your case it will work as expected. As you don't seem to keep view state this is a good solution for your use case. – skuntsel Nov 12 '13 at 08:27