Thursday, February 18, 2010

How to use struts tags in java script files?

Struts tags sometimes need to be used in java scripts. For example if we have certain validation in javascripts and we need to display a custom error message which is defined in application resources.properties file then we use the tag < bean:message key='error' >. But if this java script is in a .js file instead of the jsp page itself then this tag cannot be interpreted correctly and there is an error during runtime.
The solution to this problem is you first need to import the struts tag library using:
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%> in the .js file.
This line will be shown in error, ignore the same that is the feature of the IDE like netbeans or eclipse.
The path where the java script files are stored is given to the servlet engine so that at runtime the jsp tags will be interpreted properly. This can be done by adding the following servlet mapping and servlet elements in the web.xml file. Here the javascript files are stored at  /scripts/dynamic/ location in the root folder
< servlet >
    < servlet-name >JspServlet< /servlet-name >
    < servlet-class >org.apache.jasper.servlet.JspServlet<  /servlet-class >

   

< servlet-mapping>
     < servlet-name>JspServlet< /servlet-name>
     < url-pattern>/scripts/dynamic/*< /url-pattern>
< /servlet-mapping> 


Hence all the javascript part will be rendered to the client using the servlet engine which is able to interpret the struts jsp tags.