1. 通过依赖注入访问无状态Session Bean
#1. EJB注入Servlet中
#2. EJB注入JSF中
2. 通过EJB引用访问有状态Session Bean
3. 在工具类中访问Session Bean
1. 通过依赖注入访问无状态Session Bean
#1. EJB注入Servlet中
NetBeans创建Java Enterprise Application, di(内嵌di-ejb, di-war)。
di-ejb:
Hello.java
package org.crazyit.service; import javax.ejb.*; @Local
public interface Hello
{
String hello(String name);
}
HelloBean.java
package org.crazyit.service; import javax.ejb.*; @Stateless(name = "hello")
public class HelloBean implements Hello { public String hello(String name) {
return name + ", How are you, the time now is " + new java.util.Date();
}
}
di-war:
HelloServlet.java
package lee; import javax.ejb.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*; import org.crazyit.service.*; public class HelloServlet extends HttpServlet { //指定将内部标识名为hello的EJB注入到该Field。
@EJB(beanName = "hello")
private Hello hello; public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
//获取请求参数
String name = request.getParameter("name");
if (name == null || name.equals("")) {
name = "non-login";
}
//调用Session Bean的业务方法
String resultStr = hello.hello(name);
//创建页面输出流
PrintStream ps = new PrintStream(response.getOutputStream());
//将调用EJB的结果输出到客户端
ps.println(resultStr);
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>lee.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping> <session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
#2. EJB注入JSF中
2. 通过EJB引用访问有状态Session Bean
3. 在工具类中访问Session Bean