Since servlets represent a front-end technology you may want to contact an EJB from a servlet. With the recent push to use web applications for enterprise solutions, servlets have started to perform important roles in business applications. While servlets control the flow and validation of page presentation, they also are the main access point to the back-end business logic contained in EJBs.
In our sample we are to create a login servlet with uses EJB behind to perform authentification. When contacting an EJB in the same container (the same virtual machine), you need only make use of a default instance of the InitialContext class. Our servlet contacts a Login EJB in order to process a user login.
...
public class LoginServlet extends HttpServlet {
// home interface for the EJB Login:
private LoginHome _loginHome = null;
public void init(ServletConfig conf) throws ServletException {
super.init(conf);
try {
// create initial context:
Context ctx = new InitialContext();
// find Login home interface:
_loginHome = (LoginHome) ctx.lookup("test.loginHome");
} catch (NamingException e) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
try {
// get login parameters:
String user = request.getParameter("user");
String password = request.getParameter("password");
// create EJB instance for the user requested:
Login login = _loginHome.create(name);
// perform login operation:
Boolean valid = login.login(password);
//perform further processing...
...
} catch (Exception e) {
//handle exception
}
}
}
In our sample we are to create a login servlet with uses EJB behind to perform authentification. When contacting an EJB in the same container (the same virtual machine), you need only make use of a default instance of the InitialContext class. Our servlet contacts a Login EJB in order to process a user login.
...
public class LoginServlet extends HttpServlet {
// home interface for the EJB Login:
private LoginHome _loginHome = null;
public void init(ServletConfig conf) throws ServletException {
super.init(conf);
try {
// create initial context:
Context ctx = new InitialContext();
// find Login home interface:
_loginHome = (LoginHome) ctx.lookup("test.loginHome");
} catch (NamingException e) {
e.printStackTrace();
}
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
try {
// get login parameters:
String user = request.getParameter("user");
String password = request.getParameter("password");
// create EJB instance for the user requested:
Login login = _loginHome.create(name);
// perform login operation:
Boolean valid = login.login(password);
//perform further processing...
...
} catch (Exception e) {
//handle exception
}
}
}
Comments
Post a Comment