Dieses Beispiel zeigt, wie einfach es ist eine JavaBean zu erstellen und in einer JSP-Datei zu benutzen.
JavaBean-Beispiel mit JSP
de.bennyn.test.SimpleBean.java
package de.bennyn.test; public class SimpleBean { public String getSomething() { return "Hello World!!"; } } |
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <jsp:useBean id="myBean" class="de.bennyn.test.SimpleBean"/> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <%=myBean.getSomething()%> </body> </html> |
Referenz für jsp:useBean
:
<jsp:useBean id="object-name" class="fully-qualified-classname" beanName="fully-qualified-beanName" scope="page | request | session | application" type="type-of-object" /> |
JavaBean-Properties in JSP benutzen
de.bennyn.test.SimpleBean.java
package de.bennyn.test; public class SimpleBean { private String myProperty = null; public String getMyProperty() { return myProperty; } public void setMyProperty(String myProperty) { this.myProperty = myProperty; } public String getSomething() { return "Hello World!!"; } } |
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <jsp:useBean id="myBean" class="de.bennyn.test.SimpleBean"/> <jsp:setProperty name="myBean" property="myProperty" value="Let the Sunshine In!"/> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <%=myBean.getSomething()%><br/> <jsp:getProperty name="myBean" property="myProperty" /> </body> </html> |
Ausgabe mit Expression Language (EL):
Ohne EL:
<jsp:setProperty name="myBean" property="myProperty" value="Let the Sunshine In!"/> <jsp:getProperty name="myBean" property="myProperty" /> |
Mit EL:
<jsp:setProperty name="myBean" property="myProperty" value="Let the Sunshine In!"/> ${myBean.myProperty} |
Interessante Links:
How to Reference and Use JSTL in your Web Application