Using JavaBeans in JSP

The JSP that we created previously does not follow JSP best practices. In general, it is a bad idea to have scriptlets (Java code) in JSP. In most large organizations, UI designer and programmer are different roles performed by different people. Therefore, it is recommended that JSP contains mostly markup tags so that it is easy for designers to work on the page design. Java code should be in separate classes. It also makes sense from a reusability point of view to move Java code out of JSP.

You can delegate the processing of the business logic to JavaBeans from JSP. JavaBeans are simple Java objects with attributes and getters and setters methods. The naming convention for getter/setter methods in JavaBeans is the prefix get/set followed by the name of the attribute, with the first letter of each word in uppercase, also known as CamelCase. For example, if you have a class attribute named firstName, then the getter method will be getFirstName and the setter will be setFirstName.

JSP has a special tag for using JavaBeans—jsp:useBean:

<jsp:useBean id="name_of_variable" class="name_of_bean_class" 
scope="scope_of_bean"/>

Scope indicates the lifetime of the bean. Valid values are application, page, request, and session.

Scope name

Description

page

Bean can be used only in the current page.

request

Bean can be used in any page in the processing of the same request. One web request can be handled by multiple JSPs if one page forwards the request to another page.

session

Bean can be used in the same HTTP session. The session is useful if your application wants to save the user data per interaction with the application, for example, to save items in the shopping cart in an online store application.

application

Bean can be used in any page in the same web application. Typically, web applications are deployed in a web application container as web application archive (WAR) files. In the application scope, all JSPs in the WAR file can use JavaBeans.

 

We will move the code to validate users in our login example to the JavaBean class. First, we need to create a JavaBean class:

  1. In Project Explorer, right-click on the src folder New | Package menu option.
  2. Create a package named packt.book.jee_eclipse.ch2.bean.
  3. Right-click on the package and select the New | Class menu option.
  4. Create a class named LoginBean.
  1. Create two private String members as follows:
public class LoginBean { 
  private String userName; 
  private String password; 
} 
  1. Right-click anywhere inside the class (in the editor) and select the Source | Generate Getters and Setters menu option:
Figure 2.20: Generate getters and setters
  1. We want to generate getters and setters for all members of the class. Therefore, click the Select All button and select Last member from the drop-down list for Insertion point, because we want to insert the getters and setters after declaring all member variables.

The LoginBean class should now be as follows:

public class LoginBean { 
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; 
  } 
} 
  1. We will add one more method to it, to validate username and password:
public boolean isValidUser() 
  { 
    //Validation can happen here from a number of sources 
    //for example, database and LDAP 
    //We are just going to hardcode a valid username and 
    //password here. 
    return "admin".equals(this.userName) && 
"admin".equals(this.password); }

This completes our JavaBean for storing user information and validation.
We will now use this bean in our JSP and delegate the task of validating users to this bean. Open index.jsp. Replace the Java scriptlet just above the <body> tag in the preceding code with the following:

<%String errMsg = null; %> 
<%if ("POST".equalsIgnoreCase(request.getMethod()) && request.getParameter("submit") != null) {%> 
  <jsp:useBean id="loginBean" 
class="packt.book.jee_eclipse.ch2.bean.LoginBean"> <jsp:setProperty name="loginBean" property="*"/> </jsp:useBean> <% if (loginBean.isValidUser()) { //valid user out.println("<h2>Welcome admin !</h2>"); out.println("You are successfully logged in"); } else { errMsg = "Invalid user id or password. Please try again"; } %> <%} %>

Before we discuss what has changed in the preceding code, note that you can invoke and get code assist for the attributes and values of <jsp:*> tags too. If you are not sure whether code assist is available, just press Ctrl/Cmd + C.

Figure 2.21: Code assist in JSP tags

Notice that Eclipse displays code assist for the JavaBean that we just added.

Let's now understand what we changed in the JSP:

  • We created multiple scriptlets, one for declaration of the errMsg variable and two more for separate if blocks. 
  • We added a <jsp:useBean tag in the first if condition. The bean is created when a condition in the if statement is true, that is, when the form is posted by clicking the Submit button.
  • We used the <jsp:setProperty> tag to set attributes of the bean:
<jsp:setProperty name="loginBean" property="*"/> 

We are setting values of member variables of loginBean. Furthermore, we are setting values of all the member variables by specifying property="*". However, where do we specify values? The values are specified implicitly because we have named members of LoginBean to be the same as the fields in the form. So, the JSP runtime gets parameters from the request object and assigns values to the JavaBean members with the same name.
If names of the members of JavaBean do not match the request parameters, then you need to set the values explicitly:

<jsp:setProperty name="loginBean" property="userName" 
  value="<%=request.getParameter("userName")%>"/> 
<jsp:setProperty name="loginBean" property="password" 
  value="<%=request.getParameter("password")%>"/> 
  • We then checked whether the user is valid by calling loginBean.isValidUser(). The code to handle error messages hasn't changed.

To test the page, perform the following steps:

  1. Right-click on index.jsp in Project Explorer.
  2. Select the Run As | Run on Server menu option. Eclipse will prompt you to restart the Tomcat server.
  3. Click the OK button to restart the server.

The page will be displayed in the internal Eclipse browser. It should behave in the same way as in the previous example.

Although we have moved validation of users to LoginBean, we still have a lot of code in Java scriptlets. Ideally, we should have as few Java scriptlets as possible in JSP. We still have scriptlets for checking conditions and for variable assignments. We can write the same code by using tags so that it is consistent with the remaining tag-based code in JSP and will be easier for web designers to work with it. This can be achieved using JSP Standard Tag Library (JSTL).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.158.134