TechWriterDev
  • Cloud
    • AWS
      • 00_Doubts
      • CloudPractitioner
        • Cloud Computing
        • AWS Global Infrastructure
        • Introduction to AWS EC2
        • Elastic load balancer(ELB)
        • 04_Messaging_Queuing
        • Aditional Computing Service
        • Accessing AWS resources
        • AWS Networking
        • Storage
        • Amazon Database Solutions
        • Monitoring Tools
        • AWS Security
        • Distributed Denial Of Service Attacks
      • DeveloperAssociate
        • References
        • AWS DVA-C02 Services Index
        • Services
          • 00_IAM
            • Identity and Access Management (IAM)
            • Account Protection Mechanisms
            • Access Mechanism of AWS Resources
            • Security Tools
            • Responsibility Model
            • Advanced Concepts
          • 01_EC2
            • Elastic Compute Cloud (EC2)
            • EC2 Volume Types
            • Amazon Machine Image (AMI)
            • AWS charges for IPv4 address
          • 02_SecurityGroups
            • Security Groups
          • 03_Elastic_LoadBalancing
            • Terminology
            • Elastic load balancer
            • Features
            • Basics
          • 04_AutoScaling
            • Auto Scaling
          • 05_RDS
            • Relational Database Service (RDS)
            • Aurora
            • Security
            • RDS Proxy
          • 06_ElastiCache
            • Cache
            • Cache Offerings
          • 07_Route53
            • Basics of DNS
            • Route 53
          • 08_VPC
            • Virtual Private Cloud (VPC)
          • 09_S3
            • Simple Storage Service (S3)
            • S3 Features
            • S3 Encryption
            • S3 Features
            • S3 Bucket Policy and IAM Policy
          • 10_ECS
            • Elastic Container Service (ECS)
            • Elastic Container Registry (ECR)
            • AWS Copilot
          • 11_EKS
            • Elastic Kubernetes Service (EKS)
          • 12_SDK_CLI_Tips
            • Access AWS Resources
          • 13_CloudFront
            • Cloud Front
          • 14_Messaging
            • Simple Queue Service (SQS)
            • Simple Notification Service (SNS)
            • Fan Out Pattern
            • Kinesis
            • Compare and Contrast
          • 15_ElasticBeanStalk
            • Elastic Beanstalk
          • 16_CloudFormation
            • CloudFormation
            • Dynamic References
          • 17_Monitoring
            • AWS Monitoring
            • AWS CloudWatch
            • CloudWatch Alarms
            • Synthetics Canary
            • Amazon EventBridge (formerly CloudWatch Events)
            • X-Ray
            • OpenTelemetry
            • CloudTrail
          • 18_Lambda
            • Lambda
            • Lambda Integrations
            • Configuring Lambda
            • Lambda Layers
          • 19_API_Gateway
            • API Gateway
            • API Gateway Integrations
          • 20_DynamoDB
            • DynamoDB
            • Operations
            • Indexes
            • DynamoDB Accelerator (DAX)
            • DynamoDB Streams
            • Transactions
            • Integrations
          • 21_CICD
            • CICD
            • CodeCommit
            • CodePipeline
            • CodeBuild
            • CodeDeploy
            • CodeArtifact
            • CloudGuru
          • 22_SAM
            • Serverless Application Model (SAM)
          • 23_CDK
            • Cloud Development Kit (CDK)
          • 24_StepFunctions
            • Step Functions
            • Types of step function
          • 25_AppSync
            • AppSync
          • 26_Amplify
            • Amplify
          • 27_STS
            • Security Token Service (STS)
          • 28_DirectoryService
            • Active Directory
          • 29_KMS
            • Encryption
            • KMS API
            • Features
            • Cloud Hardware Security Module (HSM)
          • 30_SSM_Store
            • SSM Parameter Store
          • 31_SecretsManager
            • Secrets Manager
          • 32_Cognito
            • Cognito
      • Questions
        • AWS_Region
        • EC2
        • IAM
  • Database
    • MongoDb
      • Mongo db Basics
      • Mongo DB Atlas
      • Document
      • Import-Export based on Data Format
      • Mongo Shell Commands
      • Query Operators
      • Indexes
      • Upsert
      • MongoDB Aggregation Framework
      • Aggregation Framework Operators
    • PostgreSQL
      • POSTGRE SQL DataTypes
      • About table
      • Constraints
  • Technologies
    • RabbitMQ
      • RabbitMQ Concepts
      • Introduction to Exchanges
      • Introduction to Queues
    • Terraform
      • 00_Introduction
      • Configuration blocks
      • Commands
      • Variables
      • Terraform Cloud
      • Modules
  • Languages
    • Java
      • Logging
        • Getting Started
      • 00_Core
        • 00_Basics
          • Java Vs C++
          • Object oriented principles
          • Steps to compile a java program
          • JVM Internals
          • Understanding Java Development Kit
          • What is JIT Compiler?
          • Java data types
          • 07_identifiers_type_conversion
          • 08_references_and_packages
          • Steps for attaching scanner
        • Concurrency
          • 00_Threads
            • Threads
          • 01_ExecutorFramework
            • Executor Framework
            • Asynchronous Computation
      • 01_Backend
        • 01_HttpAndWebServerBasics
          • HTTP
          • Content Type
          • Web Server
        • 02_J2EE_Basics
          • J2EE_Basics
          • Why HttpServlet classs is declared as abstract class BUT with 100 % concrete functionality ?
        • 03_TomCatAndSession
          • What is a Session?
          • WebContainer
        • 04_PageNavigation
          • Cookies Additional Information
          • Page Navigation Techniques
        • 05_AboutServlet
          • CGI v/s Servlet
          • Executor Framework
          • Servlet Life cycle
          • SERVLET CONFIG
          • Servlet Context
          • Servlet Listener (web application listener)
        • 08_SpringBoot
          • Spring Boot
          • Some common annotations used in spring eco system
        • 09_SpringDataJPA
          • Spring Data JPA
        • Java_Language_Changes
          • JDK enhancement tracking reference
        • 06_ORM_Hibernate
          • readmes
            • Hibernate
            • Advantages of Hibernate
            • Hibernate Caching
            • Hibernate API
            • Hibernate Query API
            • Hibernate Annotations and JPQL
            • Entity and Value Type
        • 07_SpringFramework
          • bean_validation
            • Bean Validation
          • core
            • readme
              • Spring
              • Spring Framework Modules
              • Spring MVC Request flow
              • Dependency Injection
              • Spring Beans
              • 06_Spring_Framework_Annotations
      • 03_Tools
        • Maven
          • Maven
  • SoftwareEngineering
    • DesignPatterns
      • Notes
        • Basics
        • OOP
        • SOLID Principles
        • 03_Creational
          • Abstract Factory (aka Kit)
          • Builder
          • Factory Method (aka Virtual constructor)
          • Prototype
          • Singleton
        • 04_Structural
          • Adapter (aka Wrapper)
          • Bridge (aka Handle | Body)
          • Composite
          • Decorator (aka Wrapper)
          • Facade
          • Flyweight
          • Proxy (aka Surrogate)
        • 05_Behavioral
          • Chain of Responsibility
          • Command (aka Action | Transaction)
          • Iterator (aka Cursor)
          • Observer (aka Publish-Subscribe | Dependents)
          • Strategy (aka Policy)
    • Principles
      • REST
        • REST
  • Tools
    • Containers
      • Docker
        • Docker
        • Docker Image
        • Commands
        • Compose
        • Best Practices
      • Kubernetes
        • Kubernetes
    • VCS
      • Git
        • Quick reference of useful Git commands
Powered by GitBook
On this page
  • Version Java EE 8 (J2EE 1.8) maintained under Oracle/Jakarta EE 8 (maintained by eclipse foundation)
  • Servlets
  1. Languages
  2. Java
  3. 01_Backend
  4. 02_J2EE_Basics

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.

    • 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.

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 Info

/*
   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

/*
   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

   
   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

   <!-- 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?

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)
Previous02_J2EE_BasicsNextWhy HttpServlet classs is declared as abstract class BUT with 100 % concrete functionality ?

Last updated 4 months ago

Layers involved in HTTP request-response flow

Note: IDE automatically creates J2EE compliant web application folder structure i.e J2EE server independent.

Servlet-API-details