Springowe beany w JSP
Na początek coś prostego, ale przydatnego. Tag JSP, który umożliwia dostanie się do springowego beana bezpośrednio w kodzie strony JSP.
Tag używamy w następujący sposób:
<js:useSpringBean id="nazwaZmiennej" name="nazwaBeana"/>
Ewentualnie dodatkowo można dodać parametr type, dzięki czemu tag sprawdzi dodatkowo czy typ pobranego beana zgadza się z oczekiwanym i w przeciwnym wypadku rzuci wyjątek BeanNotOfRequiredTypeException.
Kod taga:
public class UseSpringBeanTag extends TagSupport {
protected String name = null;
protected String type = null;
@Override
public int doStartTag() throws JspException {
ServletContext servletContext = pageContext.getServletContext();
ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
Object bean = null;
if (type == null) {
bean = applicationContext.getBean(name);
} else {
try {
bean = applicationContext.getBean(name, Class.forName(type));
} catch (ClassNotFoundException ex) {
throw new JspException(ex);
}
}
pageContext.setAttribute(id, bean);
return SKIP_BODY;
}
@Override
public void release() {
super.release();
name = null;
type = null;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Ponieważ tag ten udostępnia w stronie JSP zmienną, pod którą dostępny będzie pobrany ze springa bean, dodatkowo potrzebna jest klasa dziedzicząca z TagExtraInfo dostarczająca informacji o zmiennej:
public class UseSpringBeanTei extends TagExtraInfo {
@Override
public VariableInfo[] getVariableInfo(TagData data) {
String id = data.getAttributeString("id");
String type = data.getAttributeString("type");
if (id != null) {
if (type == null) {
type = "java.lang.Object";
}
return new VariableInfo[] { new VariableInfo(id, type, true,
VariableInfo.AT_END) };
}
return super.getVariableInfo(data);
}
}
Dodatkowo oczywiście potrzebujemy stworzyć plik TLD zawierający specyfikacje naszego taga:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>spring-jsp-tag</short-name> <tag> <name>useSpringBean</name> <tag-class>eu.bojar.web.taglib.UseSpringBeanTag</tag-class> <tei-class>eu.bojar.web.taglib.UseSpringBeanTei</tei-class> <body-content>empty</body-content> <attribute> <name>id</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>name</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>type</name> <required>false</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag> </taglib>