Is it possible to use usebean on conditions in JSP?

1.9k views Asked by At

I have a application which allows user to make a search.

Based on the search criteria entered, a service call to DAO function is made (pattern jsp event -> interceptors -> processors -> services -> DAO -> database) and list of results is returned back which gets displayed in myView.jsp

Code as below is used to read the TO data in JSP:

<jsp:usebean id="myTO" type="com.myPackage.MyTO" scope="session"/>

and in the body something like

<%= myTo.getSomething() =%>

Each item on the list is clickable for details. So on clicking item 2 on the list, another call will be made with item 2's id to fetch more details on item 2.

Depending on type of item, the details are fetched in different TO's. e.g. Type1TO, Type2TO.

So detailed data on item is returned in one such TO.

Issue is: I am displaying the details in the same JSP. So the returnURL of the second request gets forwarded to myView.JSP

So I have put a line like

<jsp:usebean id="type1TO" type="com.myPackage.Type1TO" scope="session"/>

However this gives error during the first call of list search when above Type1TO does not yet exist. Error is something like "unable to find type1TO in scope session"

How could I solve this issue ???

Is there a way to put jsp:usebean tag in an if condition in the place where it is to be used in the body ?? Or any other solution to this ??

I am new to JSP and dealing with legacy JSP. So very advanced JSP (complex EL) might not be feasible.

2

There are 2 answers

0
Ramesh PVK On BEST ANSWER

The following are the usages of the <usebean>:

  1. <jsp:useBean id=”connection” class=”com.myco.myapp.Connection” /> . In this example the bean with the id is made available either by creating or finding the existing one in the session
  2. <jsp:useBean id=”connection” class=”com.myco.myapp.Connection”> <jsp:setProperty name=”connection” property=”timeout” value=”33”> </jsp:useBean>. In this example, the bean is created or found, and instatiated with the setProperty if it is being created.
  3. <jsp:useBean id=”wombat” type=”my.WombatType” scope=”session”/>. In this example the existing bean is found and made available with the given type.
0
Ken Russell On

If translated to Servlet, your first code snippet will look like:

getAttribute("myTO");

Whether to use a single attribute or 'multiple attributes with if-else logic' depends on your particular case. Without understanding your particular situation, I can see the following options:

Option 1 Wherever you are setting myTO attribute, ensure you set the value to the same variable, so that you don't have to use if-else logic in jsp.

Option 2 Use scripts

<%
  com.myPackage.MyTO toObject = session.getAttribute("myTo");
  if (toObject == NULL) {
      toObject = session.getAttrbute("type1TO");
  }
%>