Wednesday, December 10, 2014

an example of using a Java Bean

This .jsp page is gonna say: "My dog has fleas."

<%--
   Document : whatmydoghas
   Created on : Dec 10, 2014, 8:03:01 AM
   Author : tjaeschke
--%>
 
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>What My Dog Has</title>
   </head>
   <body>
      <h1>What My Dog Has</h1>
      <jsp:useBean id="lentil" scope="page" class="whatever.Lentil" />
      <jsp:setProperty name="lentil" property="owner" value="dog" />
      <jsp:setProperty name="lentil" property="possessions" value="fleas" />
      <jsp:getProperty name="lentil" property="sentance" />
   </body>
</html>

 
 

It's gonna use this Java Bean to craft the sentance.

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package whatever;
 
/**
 *
 * @author tjaeschke
 */
public class Lentil {
   private String owner;
   private String possessions;
 
   public void setOwner(String owner) {
      this.owner = owner;
   }
 
   public void setPossessions(String possessions) {
      this.possessions = possessions;
   }
 
   public String getSentance(){
      return "My " + owner + " has " + possessions + ".";
   }
}

 
 

If the values are left off of the set tags in the .jsp page, Java will attempt to find request variables of the same names as the variables to set and hand in their values to the Bean. The presence of both a request variable and an inline value seemed to cause Java to blow up when I experimented with it.

No comments:

Post a Comment