Show TOC Start of Content Area

Procedure documentation Injecting Resources into Web Applications  Locate the document in its SAP Library structure

Use

In Java EE 5, applications can access a variety of resources using annotation-based resource injection. For example, such resources can be:

      Data sources

      JavaMail session objects

      Session contexts

      JMS resources

      URLs

      And so on.

In previous releases of the Java EE (J2EE) specification, the mechanism for accessing the latter resources required that you retrieve them using JNDI lookup, and add the corresponding fragment in the web.xml. In Java EE 5, using resource injection instead of JNDI lookup simplifies the development process.

Note

Optionally, you can still use JNDI lookup for resource retrieval in Java EE 5 applications.

Procedure

Add the @Resource annotation before the required field, method or class.

A @Resource annotation can have the following attributes:

      name

      type

      authenticationType

      shareable

      mappedName

      description

Depending on the type of resource you want to access, and the location of the @Resource annotation, different attributes are required.

Example

Getting a URL Resource

The following example retrieves a java.net.URL resource. The name attribute represents the JNDI name of the resource, and mappedName is the implementation-specific name to which the attribute is mapped (this attribute is optional).

public class Resource1_servlet extends HttpServlet {

  

   @Resource(name="myUrl", mappedName = "http://www.sap.com/index.epx")

   private java.net.URL myUrl

 

   public void doGet( HttpServletRequest req, HttpServletResponse resp){

   //....  

           

         out.println("myURL's path part ->" + myUrl.getPath());

 

   //....  

 

   }

Getting a Data Source

public class Resource2_servlet extends HttpServlet {

  

   @Resource

   (name = "jdbc/efsDataSource”, type = javax.sql.DataSource.class)

   private DataSource dataSource;  

 

   public void doGet( HttpServletRequest req , HttpServletResponse resp){

   //....  

           

         Connection connection = dataSource.getConnection();

 

 

   //....  

 

   }

Note that in the example above, jdbc/efsDataSource is a non-existent data source resource and in order to be resolved by the deployer it should be explicitly mapped to an existing one. This could be done in the data-source-aliases.xml or data-sources.xml descriptors. Each of them should be placed in the META-INF folder of the application.

<data-source-aliases>

 <aliases>

   <data-source-name>${com.sap.datasource.default}</data-source-name>

   <alias>jdbc/efsDataSource</alias>

  </aliases>

</data-source-aliases>

 

 

End of Content Area