Beans Java Interview Questions | Eklavya Online

Beans Java Interview Questions

Wiring UI components to back-end data sources such as backing bean properties.

The principal that identifies the invoker of the enterprise bean method.

A JavaBeans component that corresponds to a JSP page that includes JavaServer Faces components. The backing bean defines properties for the components on the page and methods that perform processing for the component. This processing includes event handling, validation, and processing associated with navigation.

A deletion that triggers another deletion. A cascade delete can be specified for an entity bean that has container-managed persistence

The code that implements the functionality of an application. In the Enterprise JavaBeans architecture, this logic is implemented by the methods of an enterprise bean.

A method of an enterprise bean that implements the business logic or rules of an application.

The mechanism whereby data transfer between an entity bean’s variables and a resource manager is managed by the entity bean.

The Session bean and Entity bean are two main parts of EJB container.

Session Bean

  • represents a workflow on behalf of a client
  • one-to-one logical mapping to a client
  • created and destroyed by a client
  • not permanent objects
  • lives its EJB container(generally) does noot survive system shut down
  • There are two two types of Session Bean:
    • stateless session bean
    • stateful session bean

Entity Bean

  • represents persistent data and behavior off this data
  • can be shared among multiple clients
  • persists across multiple invocations
  • findable permanent objects
  • outlives its EJB container, survives systeem shutdown
  • There are two two types of Entity Bean:
    • container managed persistence(CCMP)
    • bean managed persistence(BMP)

A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:

  • Application clients and applets are client components.
  • Java Servlet and JavaServer PagesTM (JSPTM) technology components are web components.
  • Enterprise JavaBeansTM (EJBTM) components (enterprise beans) are business components.
  • Resource adapter components provided by EIS and tool vendors.

A transaction whose boundaries are defined by an enterprise bean.

  • Application client module
  • Web module
  • Enterprise JavaBeans module
  • Resource adapter module

response. setHeader(”Set-Cookie”, “cookie string”); To give the response-object to a bean, write a method setResponse (HttpServletResponse response) – to the bean, and in jsp-file:<% bean. setResponse (response); %>

JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. Available actions include: jsp:include – Include a file at the time the page is requested. jsp:useBean – Find or instantiate a JavaBean. jsp:setProperty – Set the property of a JavaBean. jsp:getProperty – Insert the property of a JavaBean into the output. jsp:forward – Forward the requester to a newpage. Jsp: plugin – Generate browser-specific code that makes an OBJECT or EMBED

?– (1) Request Lifetime: Using this technique to pass beans, a request dispatcher (using either “include” or forward”) can be called. This bean will disappear after processing this request has been completed. Servlet: request. setAttribute(”theBean”, myBean); RequestDispatcher rd = getServletContext(). getRequestDispatcher(”thepage. jsp”); rd. forward(request, response); JSP PAGE:<jsp: useBean id=”theBean” scope=”request” class=”. . . . . ” />(2) Session Lifetime: Using this technique to pass beans that are relevant to a particular session (such as in individual user login) over a number of requests. This bean will disappear when the session is invalidated or it times out, or when you remove it. Servlet: HttpSession session = request. getSession(true); session. putValue(”theBean”, myBean); /* You can do a request dispatcher here, or just let the bean be visible on the next request */ JSP Page:<jsp:useBean id=”theBean” scope=”session” class=”. . . ” /> 3) Application Lifetime: Using this technique to pass beans that are relevant to all servlets and JSP pages in a particular app, for all users. For example, I use this to make a JDBC connection pool object available to the various servlets and JSP pages in my apps. This bean will disappear when the servlet engine is shut down, or when you remove it. Servlet: GetServletContext(). setAttribute(”theBean”, myBean); JSP PAGE:<jsp:useBean id=”theBean” scope=”application” class=”. . . ” />

A language used to write expressions that access the properties of JavaBeans components. EL expressions can be used in static text and in any standard or custom tag attribute that can accept an expression

A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.

The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the

<jsp:setProperty actionvalue=””/ >

Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components:

  • the tag handler class that defines the tag\’s behavior
  • the tag library descriptor file that maps the XML element names to the tag implementations
  • the JSP file that uses the tag library

When the first two components are done, you can use the tag by using taglib directive:

<%@ taglib uri=”xxx.tld” prefix=”…” %>

Then you are ready to use the tags you defined. Let’s say the tag prefix is test:

MyJSPTag or

JavaBeans are Java utility classes you defined. Beans have a standard format for Java classes. You use tags to declare a bean and use to set value of the bean class and use to get value of the bean class.

<%=identifier.getclassField() %>

Custom tags and beans accomplish the same goals — encapsulating complex behavior into simple and accessible forms. There are several differences:

Custom tags can manipulate JSP content; beans cannot.Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans.Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

< jsp : useBean > tag is used to use any java object in the jsp page. Here are the scope values for < jsp : useBean > tag:

  • page
  • request
  • session and
  • application

JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of “jsp” followed by a colon, followed by the action name followed by one or more attribute parameters.

There are six JSP Actions:

  • < jsp : include / >
  • < jsp : forward / >
  • < jsp : plugin / >
  • < jsp : usebean / >
  • < jsp : setProperty / >
  • < jsp : getProperty / >

The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.

public void doPost (HttpServletRequest request, HttpServletResponse response)

{
try {

govi.FormBean f = new govi.FormBean();

String id = request.getParameter(“id”);

f.setName(request.getParameter(“name”));

f.setAddr(request.getParameter(“addr”));

f.setAge(request.getParameter(“age”));

//use the id to compute

//additional bean properties like info

//maybe perform a db query, etc.

// . . .

 

f.setPersonalizationInfo(info);
request.setAttribute(“fBean”,f);
getServletConfig().getServletContext()

.getRequestDispatcher(“/jsp/Bean1.jsp”).forward(request, response);

}

catch (Exception ex) {}

}

The JSP page Bean1.jsp can then process fBean, after first extracting it from the default requestscope via the useBean action.

  • <jsp:useBean id=”fBean”class=”govi.FormBean” scope=”request”/>
  • <jsp:getPropertyname=”fBean” property=”name”/>
  • <jsp:getProperty name=”fBean” property=”addr”/>
  • <jsp:getProperty name=”fBean” property=”age”/>
  • <jsp:getProperty name=”fBean” property=”personalizationInfo”/>

There are three types of dependency injection:

  • Constructor Injection(e.g. Spring): Dependencies are provided as constructor parameters.
  • Setter Injection(e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods).
  • Interface Injection(e.g. Avalon): Injection is done through an interface.

Spring has a layered architecture with over 20 modules to choose from. This means, use what you need and leave what you don’t need now. Spring simplifies JEE through POJO programming. There is no behind the scene magic in Spring as in JEE programming. POJO programming enables continuous integration and testability.

 

Spring framework’s core functionality is dependency injection (DI). Dependency injection promotes easy unit testing and more maintainable and flexible code. DI code is much easier to test. The functionality expressed by the object can be tested in a black box by building ‘mock’ objects implementing the interfaces expected by yourapplication logic. DI code is much easier to reuse as the ‘depended’ functionality is extrapolated into well defined interfaces, allowing separate objects whose configuration is handled by a suitable application platform to be plugged into other objects at will. DI code is more flexible. It is innately loosely coupled code to an extreme. This allows the programmer to pick and choose how objects are connected based exclusively on their required interfaces on one end and their expressed interfaces on the other.

Spring supports Aspect Oriented Programming (AOP), which enables cohesive development by separatingapplication business logic from system services. Supporting functionalities like auditing, gathering performance and memory metrics, etc can be enabled through AOP.

Spring also provides a lot of templates which act as base classes to make using the JEE standard technologies a breeze to work with. For example, the JdbcTemplate works well with JDBC, the JpaTemplate does good things with JPA, JmsTemplate makes JMS pretty straightforward. The RestTemplate is simply awesome in it’s simplicity. Simplicity means more readable and maintainable code.When writing software these days, it is important to try and decouple as much middleware code from your business logic as possible. The best approach when using remoting is to use Spring Remoting which can then use any messaging or remoting technology under the covers. Apache Camel is a powerful open source integration framework based on known Enterprise Integration Patterns with powerful Bean Integration. Apache Camel is designed to work nicely with the Spring Framework in a number of ways.

It also provides declarative transactions, job scheduling, authentication, a fully-fledged MVC webframework, and integration to other frameworks likeHibernate,iBatis,JasperReports,JSF,Struts,Tapestry,Seam, Quartz job scheduler, etc.

Spring beans can be shared between different JVMs using Terracotta. This allows you to take existing beans and spread them across a cluster, turn Spring application context events into distributed events, export clustered beans via Spring JMX, and make your Spring applications highly available and clustered. Spring also integrate well with other clustering solutions like Oracle’s Coherance.Spring favors unchecked exceptions and eliminates unsightly try, catch, and finally (and some times try/catch within finally itself) blocks. The Spring templates like JpaTemplate takes care of closing or releasing a database connection. This prevents any potential resource leaks and promotes more readable code.It prevents the proliferation of factory and singleton pattern classes that need to be created to promote loose coupling if not for using a DI framework like Spring or Guice.