Role
In our development, the interface and program code is done separately to do the art of the interface but the artist does not understand the Java language if we write Java code in the JSP file, will affect the art work if we use custom tags, Then in the JSP we just need to add a reference tag code just fine will not affect the artwork work also JSP file simple, convenient for us to modify later
1 Creating a Class
Package Com.eyugame.common.tag;import Java.io.ioexception;import Javax.servlet.jsp.jspexception;import Javax.servlet.jsp.jspwriter;import Javax.servlet.jsp.tagext.tagsupport;import Org.springframework.web.context.contextloader;import Org.springframework.web.context.WebApplicationContext; Import Com.eyugame.common.service.hibernate.hibernatebaseservice;import Com.eyugame.security.entity.SysUser; public class MyTag extends TagSupport {private static hibernatebaseservice hibernatebaseservice;private String username ;/** * */private static final long serialversionuid = 1L; @Overridepublic int doStartTag () throws Jspexception {JspWriter writer = This.pageContext.getOut ();/* Get bean*/if (hibernatebaseservice==null) {Webapplicationcontext Webapplicationcontext = Contextloader.getcurrentwebapplicationcontext (); Hibernatebaseservice = ( Hibernatebaseservice) Webapplicationcontext.getbean ("Hibernatebaseservice");} /* Query database */sysuser user = HIBERNATEBASESERVICE.FINDUNIQUEBYHQL (Sysuser.class, "from Sysuser as u where u.username= ' "+ username +" ' "); try {writer.print (User.getnickname ());} catch (IOException e) {e.printstacktrace ();} return skip_body;} @Overridepublic int Doendtag () throws Jspexception {return Super.doendtag ();} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;}}
Create a TLD file
My.tld
<?xml version= "1.0" encoding= "UTF-8"? ><taglib version= "2.0" xmlns= "Http://java.sun.com/xml/ns/j2ee" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "http://java.sun.com/xml/ns/j2ee Web-jsptaglibrary_2_0.xsd "><tlib-version>1.0</tlib-version><jsp-version>2.0</ Jsp-version><short-name>cc</short-name><uri>/mytaglib</uri><tag><name> mytag</name><tag-class>com.eyugame.common.tag.mytag</tag-class><body-content>empty< /body-content><attribute><name>username</name><required>true</required>< Rtexprvalue>true</rtexprvalue></attribute></tag></taglib>
3.web.xml Add the following configuration
<jsp-config> <taglib> <taglib-uri>/tagtest </taglib-uri> < taglib-location>/tld/my.tld</taglib-location> </taglib> </jsp-config>
4.jsp page Add the following content
<!--JSP top join, URI is the context path of the Web project--><% @taglib prefix= "cc" uri= "/tld/my.tld"%> <!--added in body <cc:mytag username= "admin"/>
Look at my database, there's a record .
After the JSP display
The results are correct
JSP custom label (and inject beans in the spring container)