简体   繁体   中英

different way for <jsp:useBean>

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 ?

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 .

<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM