3

There is -

<html>
<body>
         <jsp:useBean id="user" class="user.UserData" scope="session"/>
</body>
</html>

And -

<html>
<body>
         <%
             Object user = session.getAttribute("user.UserData") ; 
         %>
</body>
</html>

Assume user.UserData exists on the session . is there any differnce between the two ways ?

URL87
  • 10,667
  • 35
  • 107
  • 174

2 Answers2

3

A well known issue in JSPs is: avoid everything you can on using Java code with your page (.jsp). So the first approach fits better, do you agree? Taglibs <jsp:useBean /> among others are a nice way of accessing code without mixing the layers. This concepts I barely introduced are part of MVC "specification".

-- EDIT --

The second way of acessing a bean is known as scriptlets and should be avoided as always as possible. A brief comparison can be found here JSTL vs jsp scriptlets.

Community
  • 1
  • 1
axcdnt
  • 14,004
  • 7
  • 26
  • 31
3
<jsp:useBean id="user" class="user.UserData" scope="session"/>

is equivalent to

<%
    Object userDataObject = session.getAttribute("user") ; // id="user" of <jsp:useBean> maps to session attribute name "user"
%>

Besides, the scriptlet only reads existing data from session or returns null if no attribute is found.
If <jsp:useBean> finds attribute "user" in session to be null, It will create an instance of 'user.UserData' and add to attribute "user" in session scope.

AshwinN
  • 301
  • 2
  • 4
  • so what the "user.UserData" in jsp:useBean mean ? – URL87 Aug 02 '12 at 18:29
  • the Object in session will be an instance of class "user.UserData". i.e. will automatically type cast from class "Object" to "user.UserData. In terms of scriptlet - user.UserData userDataObject = (user.UserData) session.getAttribute("user") ; – AshwinN Aug 04 '12 at 04:28