Java.Servlet.What is the difference between and ?

Although both <c:set> and <jsp:useBean> create or work with variables/objects in JSP,
they have very different purposes and work at different levels.


🔵 1. <jsp:useBean>

FeatureExplanation
PurposeTo create or locate a JavaBean (Java class instance)
ScopePage, request, session, or application (specified explicitly)
TargetJavaBeans (classes with getters/setters)
BehaviorIf the bean doesn’t exist in scope, it creates a new one.
TagBuilt-in JSP Action tag (jsp:useBean)

✅ Used when you need an object instance (typically of a JavaBean) to hold structured data.

Example:

<jsp:useBean id="user" class="com.example.User" scope="session" />
<jsp:setProperty name="user" property="name" value="Stanley" />

Creates or reuses a User object and stores it in session scope.

User must have a public no-argument constructor.

🔵 2. <c:set>

FeatureExplanation
PurposeTo set a value (any object, simple value, or result of an expression) into a variable.
ScopePage, request, session, or application (default is page scope)
TargetAny variable (String, Integer, JavaBean, Map, etc.)
BehaviorAlways sets a value; does not create a new instance automatically.
TagPart of JSTL Core (c prefix)

✅ Used for assigning values or overwriting variables easily.

Example:

<c:set var="username" value="Stanley" scope="session" />

Simply sets "Stanley" into sessionScope.username.

✅ It can also modify JavaBean properties:

<c:set target="${user}" property="name" value="Stanley" />

Equivalent to user.setName("Stanley");

🛠️ Key Differences Table

Feature<jsp:useBean><c:set>
Creates new object?✅ Yes (if object not found in scope)❌ No, just sets a value
Main useCreate or find a JavaBeanSet a variable or update property
TargetJavaBean classAny object, String, Number, Collection, Map, Bean property
Part ofJSP Action Tags (jsp)JSTL Core (c)
Scope managementMust specify explicitly in tag (optional)Default is pageScope, but can specify others
DependencyNeeds a real Java class with getters/settersNo special class needed

🎯 In short:

If you need…Use…
To create or find a JavaBean instance<jsp:useBean>
To set or update a simple variable or a bean property<c:set>

📢 Real-World Example Together

Example JSP:

<jsp:useBean id="user" class="com.example.User" scope="session" />
<c:set target="${user}" property="name" value="Stanley" />
<p>Hello, ${user.name}!</p>

useBean ensures there is a User object.

c:set sets the name property.

EL ${user.name} reads it.

This entry was posted in Без рубрики. Bookmark the permalink.