# J2EE\_Basics

### Version Java EE 8 (J2EE 1.8) maintained under Oracle/Jakarta EE 8 (maintained by eclipse foundation)

_(Tomcat 9 supports J2EE 1.8 version)_

#### What is J2EE ?

* Consists of specifications only _(i.e interfaces and abstract classes)_.
* Which specifications _(i.e Rules or contracts)_
* Specifications of services required for any enterprise application.

#### Who uses this specifications?

* Used by J2EE vendors to implement J2EE compliant web servers.

#### What is enterprise application ?

* An enterprise application (EA) is a large software system platform designed to operate in a corporate environment .
* It includes online shopping and payment processing, interactive product catalogs, computerized billing systems, security, content management, IT service management, business intelligence, human resource management, manufacturing, process automation, enterprise resource planning ....

#### What does this specifications include?

* These specifications include

1. Servlet API
2. JSP(Java server page) API
3. Security
4. Connection pooling
5. EJB (Enterprise Java Bean) --> New Competitor Spring
6. JNDI(Naming service -- Java naming & directory i/f
7. JPA(java persistence API)
8. JMS(java messaging service)
9. Java Mail
10. Java Server Faces --> (Fading Technology)
11. Java Transaction API
12. Webservices support(SOAP/REST) etc...

#### Who is the Vendor of J2EE specs

* Earlier it used to be under Sun microsystem, Oracle purchased Sun microsystem and now distributes these specification under Eclipse License as Oracle submitted Java EE to the Eclipse Foundation.

#### J2EE compliant web server

* Apache Tomcat _(web server : servlet/web container)_

**Difference between web server and Application server**

* A web server,
  * normally contains only one Web container\[i.e (server side JVM)/(Web Engine)]
  * Can only manage dynamic web component for eg. Servlet, JSP, Servlet Filter.
  * Some of the services implemented by web server may include servlet API,JSP API,Security,Connection pooling,JNDI(naming service) does not implement all of them.
* Whereas, an application server _(here J2EE complaint application server)_ can be formulated as,
  * **web container + EJB (enterprise java bean)container + ALL J2EE services implementation**.

**J2EE server Vendors & Products**

| Vendor     | Product                               |
| ---------- | ------------------------------------- |
| Apache     | tomcat(web server)/Tomee (app server) |
| Oracle/Sun | Glassfish                             |
| Red Hat    | JBoss (wild fly)                      |
| Oracle     | weblogic(by BEA Systems)              |
| IBM        | Websphere                             |

**WHY J2EE**

1. Can support different types of clients
   * thin client(web client + Internet connection)
   * thick client --- application client(eg : TCP client/RESTful client)
   * smart clients -- mobile client
2. J2EE server independence
   * Create & deploy server side application i.e., any J2EE compliant server it is guaranteed to produce SAME results without making any changes or re-deploying on any other J2EE server\[i.e by making WAR file(bundled output)]
3. Ready made implementation of primary services(eg., security, conn, pooling, email etc) which gives independence from the worry of managing the life cycle of the servlet etc, so that J2EE developer doesn't have to worry about primary services. Rather they can concentrate on actual business logic.
4. Layers involved in HTTP request-response flow ![request-response-diagram](https://574639531-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJDnjsv52I3fJ56WbLgHu%2Fuploads%2Fgit-blob-9261f947994040ef19e938030f2aff866b666080%2Frequest-response-flow.png?alt=media)
   * Web browser sends the request (URL) eg : http://www.abc.com:8080/day1.1 /day1.1 --> root/context path/web app name

* Host -->Web server -->Web Container(server side JVM) -->Web application -->HTML/JSP/Servlet....

**Note: One web container can deploy multiple web applications**

**What is dynamic web application server side application?**

* Its an program deployed(installed) on web-server/app-server, meant for servicing typically web clients(thin clients) using application layer protocol HTTP/HTTPS.

**Note: IDE automatically creates J2EE compliant web application folder structure i.e J2EE server independent.** ![folder-structure-diagram](https://574639531-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJDnjsv52I3fJ56WbLgHu%2Fuploads%2Fgit-blob-4010f027d694981fc2cbaa87c32cc8c008ebcdbe%2Fj2ee-compliant-webappln-folderstructure.png?alt=media)

#### What is Web container?

1. Server side JVM residing within web server. It is a run-time environment for dynamic web components(such as Servlet & JSP,Filter).

#### Responsibilities of Web container

1. Creating Http Request & Http response objects
2. Controlling life-cycle of dynamic web components (i.e manages life cycle of servlet,JSP,Filters)
3. Giving ready-made support for services such as Naming,security,Connection pooling.
4. Handling concurrent request from multiple clients.
5. Managing session tracking.

**What is web.xml**

* Deployment descriptor one per web application created by developer(in current case : by IDE)
* This descriptor is read by Web Container, in the begginning of web application deployment.

**What are the contents of web.xml?**

* Deployment instructions for welcome page, servlet deployment tags, session configuration, sec config......

### Servlets

**Why servlets?**

* To add dynamic nature to the web application

**What is a servlet ?**

* Java class (with NO main method)
* Represents dynamic web component whose life cycle will be managed by WC(web container : server side JVM)
* life cycle methods such as init, service, destroy are called by WC using call back mechanism. These method implementation are provided by developer but when to invoke this method is decided by web container.

> A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.

**Life-cycle methods used by Web container to manage Servlet**

* Web container calls the init() method only once after servlet object has been created by the web container.
* Similarly, the destroy() method is also called only once after the end of the servlet life cycle.
* Similarly, web container calls the service() method once per request.

**Responsibilities of Servlet**

1. Request processing(involving conversion(string to Java data types)/validation).
2. Business Logic.
3. Dynamic response generation.
4. Managing Data Access Logic.
5. Page navigation.

**Servlet API details**

![Servlet-API-details](https://574639531-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FJDnjsv52I3fJ56WbLgHu%2Fuploads%2Fgit-blob-28d7bdbdecd2184d802777c38a2b473b990b8b7f%2Fservlet_api.png?alt=media)

**Servlet API Info**

```java
/*
   Defines methods that all servlets must implement.
*/
   public interface Servlet
/* 
   Generic servelet with init and destroy implemented 
   But service method is an abstract method
*/
   public abstract class GenericServlet
   extends Object
   implements Servlet, ServletConfig, Serializable
/*
   Http Servlet with init, destroy and service methods implemented, 
   we override do[Get|Post|Put|Delete...]() methods
*/
   public abstract class HttpServlet
   extends GenericServlet
```

* Deployment of the servlet
  * Via annotation _(before J2EE 1.5 only xml based configuration was possible)_
  * All annotations for Servlet is present in `javax.servlet.annotation`

```java
/*
   Url pattern has to start with '/' act as url separator
*/
@WebServlet(value="/validate", loadOnStartup=1)
public class LoginServlet extends H.S {....}
```

* When `@WebServlet` annotation is used web container internally creates a hash map like structure with,

| key           | value                              |
| ------------- | ---------------------------------- |
| **/validate** | pages.LoginServlet                 |
| (url pattern) | Fully Qualified Servlet Class Name |

**Note: Does not need a constructor. Why?**

**A bit about init() and destroy()**

* Both methods are called only once by the webcontainer
  * `init()/init(ServletConfig config)`
    * Called only once on **first** request to the web server.
    * This behavior can be changed through load-on-startup tag in `web.xml` by default lazy initialization **(loadOnStartup=-1)**
  * `destroy()`
    * Called only once when
      * application is undeployed
      * server is reloaded(One case when this happens is when source code is changed. Not html changes but java code changes.)
      * server is shutdown

```java
   
   javax.servlet.GenericServlet
   /*init style method*/
   public void init() throws ServletException
   public void init(ServletConfig config) throws ServletException

   /*destroy style method*/
   public void destroy()

   /* service method */
   public abstract void service(ServletRequest req,
   ServletResponse res) throws ServletException, IOException
   /*--------------------------------------------*/
   
   javax.servlet.HttpServlet
   public void service(ServletRequest req,
   ServletResponse res) throws ServletException, IOException

   protected void service(HttpServletRequest req,
   HttpServletResponse resp) throws ServletException,
   IOException

   protected void do****(HttpServletRequest req, HttpServletResponse resp)  throws ServletException, IOException

```

**load on startup**

* With load-on-startup optional element we can change the default behaviour of sevlet instance initialization to eager(i.e a positive value, 0 is normally **not** used).
* Higher the value, lower the priority of Servlet initialization.
* Web Container(WC) loads servlet class at server side Web Container's Method area. Single instance of servlet class is created using default constructor and init() is invoked. Now servlet is completely initialized for servicing client requests.

**Hmm, then what?**

* Now once servlet has been initialised by the WC, service() method of `HttpServlet` class is invoked by WC.
* service() method then checks for method in request header, based on which it decides which do\*\*\*\* method of the programmer provided servlet class needs to be called.
* One the request has been served by the servlet, it sends the processed response to the Web Container, which in turn sends it to the Web server.
* Web server basically wraps the response received from the WC in to a reponse packet with response status code, header and body. _(Default response code is 200 (OK))_
* This response packet is send back to client. This reponse is rendered on to the client browser based on content type i.e html.

**Legacy Approach: Using XML tags to configure a Web Servlet**

```xml
   <!-- Mapping servlet name and class-->
   <servlet>
      <servlet-name>abc</servlet-name>
       <!-- value (FQCN)-->
      <servlet-class>pages.SecondServlet</servlet-class>
   </servlet>
   <!-- Mapping servlet to url pattern using servlet name configured above-->
   <servlet-mapping>
      <servlet-name>abc</servlet-name>
      <!-- key (url pattern)-->
      <url-pattern>/hi</url-pattern>
      <load-on-startup>1</load-on-startup>
   </servlet-mapping>
```

_Explanation remains same only how we confugure the servlet changes._ _This one set of xml tags will be repeated for as many servlet classes that needs to deployed. Leads to bloating._

#### Hence, Annotation rocks...!

**Note: One servlet can be mapped to multiple url pattern. But multiple servlet cannot be mapped to same url pattern.**

* At the time of web app deployment, WC tries to populate map of url patterns , from XML tags (from web.xml). Later, it will check for @WebServlet annotation

#### How to read request parameters sent from the client, in a servlet?

```java
javax.servlet.ServletRequest   

<!-- All parameters are treated as string -->
<!-- Used for single valued parmeters -->
public String getParameter(String paramName)

<!-- Used for multi-valued parmeters -->
public String[] getParameterValues(String paramName)

```
