Servlet资源注射

 

Servlet程序:

import java.io.IOException;

import javax.annotation.Resource;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")

public class ResourceInto extends HttpServlet{

private @Resource(name="uname") String uname; //资源注射

public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{

request.setCharacterEncoding("utf-8");

response.setCharacterEncoding("utf-8");

response.setContentType("text/html");

response.getWriter().print(uname);

}

public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{

this.doPost(request, response);

}

}

 在web.xml中配置该注射参数



ResourceInto

cn.edu.bzu.ResourceInto





ResourceInto

/ResourceInto







uname

java.lang.String

TOM

资源注射的工作原理是JNDI(Java命名与目录接口,Java Naming and Directory Interface)。Servlet实例中使用〈env-entry>配置了名为uname的JNDI资源,然后使用@Resource将指定名称的JNDI资源注射到Servlet实例里。

如果不使用@Resource,通过查找JNDI同样可以获取到这三个资源,代码如下:

Context ctx=new InitialContext();    //实例化一个Context对象
String message=(String)ctx.lookup("uname"); //查找资源uname

 Servlet中不公可以注射String、Integer等类型的变量,还可以注入自定义的Java Bean以及数据源等复杂类型的变量。

 

 

 
 

你可能感兴趣的:(温故而知新)