Google

Mar 7, 2012

Enterprise Java Interview Questions and Answers: What is new in JEE 6?

It is imperative to keep track of the  key enhancements and improvements to JEE. If you are interested in JEE basics the try Enterprise Java frequently asked questions and answers.


Q. What is new in the Java EE 6  (JEE 6) compared to Java EE 5 (JEE 5)?
A.

  • JEE 6 provides more extensibility points and service provider interfaces to plug into for the service providers. For example, "Java Authentication Service Provider interface Containers" provides a mechanism for the authentication providers to integrate with the containers.
  • JEE 5 favored convention over configuration by replacing XML with annotations and POJOs. The JEE 6 extended POJOs with dependency injection (i.e JSR 299 -- Context and Dependency Injection - CDI). This enables a JSF managed bean component to interact with an enterprise Java bean (i.e. EJB) component model to simplify development. It is about time all various types of managed beans are unified. In Java EE 6, the CDI builds on a new concept called "managed beans", which is managed by the enterprise edition container. In CDI, a managed bean is a Java EE component that can be injected into other components. The specification also provides a set of services like resource injection, lifecycle callbacks, and interceptors.   
  • Any CDI managed component may produce and consume events. This allows beans to interact in a completely decoupled fashion. Beans consume events by registering for a particular event type and qualifier.
  • The JAX-WS stack was overhauled to be an integrated stack with JAX-WS 2.x, JAXB 2.x, SAAJ 1.x, JAX-RS 1.x (new RESTful) and JAXR 1.x. (new pull-parsing API). 
  • Servlet 3.0 spec introduced the Async Servlet, file uploading functionality, and annotations based configuration.The web.xml file is optional.
  • Singleton EJBs  (i.e. one EJB per container) and asynchronous session beans  were introduced. The EJB was streamlined  with fewer classes, interfaces, and simpler object to relational mapping by taking advantage of the JPA.
  • Bean based validation framework was introduced to avoid duplication.
  • Enterprise Java Beans (i.e EJBs) can be packaged directly into a WAR file. No longer required to be packaged as JAR and then included into an EAR.
  • The JSF 2.0 simplifies the development of UI components.The JSF 2.0 has integrated Ajax and CDI support.  
Note: "Convention over configuration" is a design paradigm, which seeks to standardize, simplify, and decrease the number of decisions that developers need to make without compromising on flexibility. For example, ANT build tool allowed you to come up with any project structure, whereas Maven is strict on convention as to how the project is structured.

Q. How does the new bean validation framework avoid duplication?
A. Developers often code the same validation logic in multiple layers of an application, which is time consuming and error-prone. At times they put the validation logic in their data model, cluttering it with what is essentially metadata. JEE 6 Improves validation and duplication with a much improved annotation based bean validation. Bean Validation offers a framework for validating Java classes written according to JavaBeans conventions. You use annotations to specify constraints on a JavaBean. For example,

The JavaBean is defined below

public class Contact {

    @NotEmpty @Size(max=100)
    private String firstName;

    @NotEmpty @Size(max=100)
    private String surname;
    
    @NotEmpty @Pattern("[a-zA-Z]+")
    private String category;
    
    @ShortName
    private String shortName; //custom validation 

    ...

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    ...
}

Custom validators can be defined by defining an annotation and relevant implementation

@ConstraintValidator(ShortNameValidator.class)
@Documented
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RUNTIME)
public @interface ShortName {
       String message() default "Wrong name";
       String[] groups() default {};
}



Next the validation implementation class

public class ShortNameValidator implements ConstraintValidator <Contact, String> {

    private final static Pattern SHORTNAME_PATTERN = Pattern.compile("[a-zA-Z]{5,30}");

    public void initialize(Contact constraintAnnotation) {
        // nothing to initialize
    }
 
 
 public boolean isValid(String value, ConstraintValidatorContext context) {
        return SHORTNAME_PATTERN.matcher(value).matches();
    }

} 


You could use the validator as shown below

Contact contact = new Contact();
conatct.setFirstName("Peter");
//.... set other values

ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
 
Set<ConstraintViolation<Contact>> violations = validator.validate(Contact);



Q. What are the benefits of the asynchronous processing support that was introduced in Servlet 3.0 in JEE 6?
A.

1. If you are building an online chess game or a chat application, the client browser needs to be periodically refreshed to reflect the changes. This used to be achieved via a technique known as the server-polling (aka client pull or client refresh). You can use the HTML tag <META> for polling the server. This tag tells the client it must refresh the page after a number of seconds.

<META http-equiv="Refresh" content="10"; url="newPage.html" />

The URL newPage.html will be refreshed every 10 seconds. This approach has the downside of wasting network bandwidth and server resources. With the introduction of this asynchronous support, the data can be sent via the mechanism known as the server push as opposed to server polling. So, the client waits for the server to push the updates as opposed to frequently polling the server.



2. The Ajax calls are integral part of any web development as it provides richer user experience. This also means that with Ajax, the clients (i.e. browsers) interact more frequently with the server compared to the page-by-page request model. If an Ajax request needs to tap into server side calls that are very time consuming (e.g. report generation), the synchronous processing of these Ajax requests can degrade the overall performance of the application because these threads will be blocked as the servers generally use a thread pool with finite number of threads to service concurrent requests. The asynchronous processing will allow these time consuming requests to be throttled via a queue, and the same thread(s) to be recycled to process queued requests without having to chew up the other threads from the server thread-pool. This approach can be used for non Ajax requests as well.


Note: In JEE 6, The EJB 3.1 can also specify a Session Bean to be asynchronous.



Q. What are benefits of web fragements introduced in Servelt 3.0 spec?
A. Web applications use frameworks like JSF, Struts, Spring MVC, Tapestry, etc. These frameworks normally bootsrap (i.e register) via the web.xml file using the <servlet> and <listener> tags. For example


The web.xml file

<?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>My JSFServlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>My JSFServlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>

</web-app>

If a particular application uses more than one framework, the above approach is not modular as you will have to bootstrap all the frameworks within the same web.xml file, making it large and difficult to isolate framework specific descriptors. The Servlet 3.0 specification addresses this issue by introducing web fragments. A web fragment can be considered as one of the segment of the whole web.xml and it can be thought of as one or more web fragments constituting a single web.xml file. The fragment files are stored under /META-INF/web-fragment.xml, and it is the responsibility of the container to scan the fragement files during the server start-up.

The web-fragment.xml file

<web-fragment>
    <servlet>
        <servlet-name>myFrameworkSpecificServlet</servlet-name>
        <servlet-class>myFramework.myFrameworkServlet </servlet-class>
    </servlet>

    <listener>
        <listener-class>myFramework.myFrameworkListener</listener-class>
    </listener>
</web-fragment>


Note: The Servlet 3.0 specification also provides enhanced pluggability by providing an option to add servlets, filters, servlet mappings and filter mappings during the run time.


Q. What do you understand by the term "Web profile" in Java EE 6?
A. Java EE 6 introduces the concept of profiles as a way to slimming the footprint of the Java EE platform and better target it for specific audiences. Profiles are configurations of the Java EE platform that are designed for specific classes of applications. For example, the required elements for a Web profile are

  • Java EE 6 (JSR-316)
  • Common Annotations for Java Platform 1.1 (JSR-250)
  • Dependency Injection for Java 1.0 (JSR-330)
  • Contexts and Dependency Injection for Java EE platform 1.0 (JSR-299)
  • Servlet 3.0 (JSR-315)
  • JavaServer Pages (JSP) 2.2 (JSR-245)
  • Expression Language (EL) 2.2 (JSR-245)
  • Debugging Support for Other Languages 1.0 (JSR-45)
  • Standard Tag Library for JavaServer Pages (JSTL) 1.2 (JSR-52)
  • JavaServer Faces (JSF) 2.0 (JSR-314)
  • Enterprise JavaBeans (EJB) 3.1 Lite (JSR-318)
  • Java Transaction API (JTA) 1.1 (JSR-907)
  • Java Persistence API (JPA) 2.0 (JSR-317)
  • Bean Validation 1.0 (JSR-303)
  • Managed Beans 1.0 (JSR-316)
  • Interceptors 1.1 (JSR-318)


The JEE 6 has also introduced the concept known as "pruning" to manage complexities. This is similar to the concept introduced in Java SE 6. Pruning is performed as a multistep process where a candidate is declared in one release but may be relegated to an optional component in the next release, depending on community reaction. For example, JAX-RPC will be pruned and replaced by JAX-WS. However, if Java EE application server vendors do include a pruned technology, they must do so in a compatible way, such that existing applications will keep running. The profiles and pruning are debatable topics and only time will tell if they work or not.

More relevant JEE questions and  answers:

Labels:

1 Comments:

Blogger john son said...

Wonderful blog & good post.Its really helpful for me, awaiting for more new post. Keep Blogging!

JAVA Training in Chennai

8:35 PM, August 20, 2014  

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home