0

I am trying to study 'jsp:useBean' and found that 'jsp:setProperty' and 'jsp:getProperty' is used in association with useBean. My doubt is, why do we need these action tags when we can directly call the setter and getter methods using bean id.?

I did a sample to test it.

Bean:

package test.usebean.bean;

public class UseBeanTarget {

    @Override
    public String toString() {
        return "UseBeanTarget [userName=" + userName + ", password=" + password
                + "]";
    }


    private String userName;
    private String password;
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }


    public String displayName(){
        return userName;
    }

}

JSP:

<jsp:useBean id="targetBean" class="test.usebean.bean.UseBeanTarget"></jsp:useBean>
<jsp:setProperty property="userName" name="targetBean" value="Renjith"/>
<jsp:setProperty property="password" name="targetBean" value="ren@1234"/>

<h2>
Set using setProperty
<br />
<%= targetBean %>
</h2>
<hr />
<% 
targetBean.setUserName("Renjith_Direct");
targetBean.setPassword("ren$1234");
%>
<h2>
After setting the properties directly
<br />
<%= targetBean.getUserName() %>
<br />
<%= targetBean.getPassword() %>
</h2>

What i observed is that both serves the same purpose.

Result:

Set using setProperty 

UseBeanTarget [userName=Renjith, password=ren@1234]

After setting the properties directly 

Renjith_Direct 
ren$1234
Renjith
  • 1,122
  • 1
  • 19
  • 45

1 Answers1

2

Yes, both the methods work fine but generally using java code inside a JSP file is frowned upon. Using JSP tags as opposed to using java code with <% %> tag preserves the XML format of the JSP file and makes the code more readable.

sope
  • 86
  • 2
  • 9
  • oh.. is it? so it doesn't serve any other purpose? I felt java code is comparatively simpler. – Renjith Aug 19 '16 at 04:27
  • Well, basically that's why. Scriptlets may feel simpler when it comes to small codes like this but it would be tiresome to manage a large project with a lot of scriptlets. JSP files should only be used for "presentation" and the logic should be in the servlet class file. Using one liner scriptlets could be seen as okay but try to use JSP tags whenever possible. More descriptive answer: http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files. Make sure to tick my answer if it was helpful :) – sope Aug 19 '16 at 04:48