25 November 2016

EJB NetBeans Hello World Java

Tạo project có tên  Hello_World
Tạo Session Bean có tên HelloSessionBean
Chọn Alt + Insert > Add business method
HelloSessionBean.java
Java EJB 2016
package session;

import javax.ejb.Stateless;

/**
 *
 * @author Lonely
 */
@Stateless
public class HelloSessionBean implements HelloSessionBeanLocal {

    @Override
    public String sayHello() {
        return "Hello Lonely Cat!";
    }
    
}

HelloSessionBeanLocal.java
Java EJB 2016
package session;

import javax.ejb.Local;

/**
 *
 * @author Lonely
 */
@Local
public interface HelloSessionBeanLocal {

    String sayHello();
    
}
Tiếp theo ở file Hello_World-war chúng ta xóa index.html tạo mới index.jsp
index.jsp
Java EJB 2016
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>${requestScope.say}</h1>
    </body>
</html>
Tạo servlet tên HelloServlet
Alt + Insert  > Call Enterprise Bean..

HelloServlet.java
Java EJB 2016
package servlet;

import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import session.HelloSessionBeanLocal;

/**
 *
 * @author Lonely
 */
public class HelloServlet extends HttpServlet {
    @EJB
    private HelloSessionBeanLocal helloSessionBean;
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String say = helloSessionBean.sayHello();
        request.setAttribute("say", say);
        request.getRequestDispatcher("index.jsp").forward(request, response);
    }

}
Click vào tam giác Clear and build > Deploy > Run chạy 

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang