资源注射是从JavaEE 5.0开始出现,实现了Tomcat在启动时自动将web.xml中的配置信息“注射”到Servlet中。资源注射是通过Annotation完成,Annotation是一种特殊的接口,以"@"为标志,用法如下:
@Resource (name="messageNameInWebXml") private String message;
有时为了简洁,上面的两行代码可以缩写为一行:
private @Resource(name="messageNameInWebXml") String message;加入@Resource注释后,Tomcat会在Servlet运行时将变量message的值注入,这个值设置在web.xml中名为messageNameInWebXml的参数中。
下面用实例来说明:
package com.hello.servlet; import java.io.*; import javax.annotation.Resource; import javax.servlet.*; import javax.servlet.http.*; public class InjectionServlet extends HttpServlet{ private @Resource(name="hello") String hello; private @Resource(name="i") int i; @Resource(name="persons") private String persons; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional //EN\">"); out.println("<HTML>"); out.println("<HEAD><TITLE>资源注入</TITLE></HEAD>"); out.println("<style>body{font-size:12px;}</style>"); out.println("<b>注入的字符串</b>: <br/> - " + hello +"<br />"); out.println("<b>注入的整数</b>: <br/> - " + i +"<br />"); out.println("<b>注入的字符串数组</b>: <br/>"); for(String person : persons.split(",")){ out.println(" - " + person +"<br />"); } out.println("<BODY>"); out.println("</BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
<servlet> <servlet-name>InjectionServlet</servlet-name> <servlet-class>com.hello.servlet.InjectionServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>InjectionServlet</servlet-name> <url-pattern>/servlet/InjectionServlet</url-pattern> </servlet-mapping> <!-- 下面是资源配置 --> <env-entry> <env-entry-name>hello</env-entry-name> <env-entry-type>java.lang.String</env-entry-type> <env-entry-value>Hello, Welcome to the JavaEE Resource Injection</env-entry-value> </env-entry> <env-entry> <env-entry-name>i</env-entry-name> <env-entry-type>java.lang.Integer</env-entry-type> <env-entry-value>14</env-entry-value> </env-entry> <env-entry> <env-entry-name>persons</env-entry-name> <env-entry-type>java.lang.String</env-entry-type> <env-entry-value>Helloween, Cobain, Roses, WLJ, </env-entry-value> </env-entry>
InjectionServlet实例中使用<env-entry>配置了名为hello, i, persons的JNDI资源,然后使用@Resource将指定名称的JNDI资源注射到InjectionServlet里。如果不使用@Resource,直接通过JNDI也可以获取这三个参数,代码如下:
Context ctx = new InitialContext(); String message = (String)ctx.lookup("message"); Integer i = (Integer)ctx.lookup("i"); String persons = (String)ctx.lookup("persons");