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>
| Feature | Explanation |
|---|---|
| Purpose | To create or locate a JavaBean (Java class instance) |
| Scope | Page, request, session, or application (specified explicitly) |
| Target | JavaBeans (classes with getters/setters) |
| Behavior | If the bean doesn’t exist in scope, it creates a new one. |
| Tag | Built-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>
| Feature | Explanation |
|---|---|
| Purpose | To set a value (any object, simple value, or result of an expression) into a variable. |
| Scope | Page, request, session, or application (default is page scope) |
| Target | Any variable (String, Integer, JavaBean, Map, etc.) |
| Behavior | Always sets a value; does not create a new instance automatically. |
| Tag | Part 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 use | Create or find a JavaBean | Set a variable or update property |
| Target | JavaBean class | Any object, String, Number, Collection, Map, Bean property |
| Part of | JSP Action Tags (jsp) | JSTL Core (c) |
| Scope management | Must specify explicitly in tag (optional) | Default is pageScope, but can specify others |
| Dependency | Needs a real Java class with getters/setters | No 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.