J2EE

    Editions:

  • JSE [J2SE] – Java Standard Edition [Java Core Concepts & StandAlone]
  • JEE [J2EE] – Java Enterprise Edition [Java Advanced Concepts & Network with server ,Client]
  • JME [J2ME] – Java Micro Edition [For Mobile,PDA,Tablet]

It has KVM [Kilobyte Virtual Machine] instead of JVM [Java Virtual Machine].

  • WebPage -> Static Content [HTML]
  • WebApps -> Dynamic Content [PHP,Perl,JSP]

Web Server Purpose:

    • Instance Persistance
    • Session Management
    • Security

Components:

      1. Servlet [Control]
      2. Java bean[Business Logic]
      3. JSP [Presentation Logic]
      4. Deployment Descriptor. [web.xml]

Servlet:

Servlets are server side components that provide a powerful mechanism for developing server side programs.

LifeCycle:

WEB APP:

  • J2EE has WCD [Web Container Development].
  • Devlopement & Deploy in Server.
  • Apache Tomcat is the first invented server [httpd]
  • All App Server can be web server.
  • All App server contain Web container.

Web App Folder Structure:

STEPS:

    1. Create Application structure.
    2. Create Servlet
    3. set class path [setclasspath=”c:/…….”]
    4. Compile the servlet
    5. Update Web.xml filw with servlet name.
    6. Start the server
    7. Send Request [“http://localhost:8080/Appname/servletname”]

GenericServlet => HttpServlet

[Accept all]    [Accept only HTTP request]

 BASE CLASS           DERIVED CLASS

   Request – Define Client Details

   Response – Define Server Details

Web.xml Structure: [Deployment Descripter]

<web-app>

<servlet>

<servlet-name> serv </servlet-name>  [Step3]

<servlet-class> serv </servlet-class>     [Step4]

</servlet>

<servlet-mapping>

<servlet-name> [Must Match]   [Step2]

        <url-pattern>[Request Url ]       [Step1]

<servlet-mapping>

</web-app>

  • Restart & Recompile  server is required to update the change in servlet file.
  • Only one Web.xml is allowed for the application.

Web Container Operation: [After Found the class using web.xml]

      1. Class file will be loaded into JVM
      2. Object will be created to create servlet config
      3. Create Servlet Config
      4. call init(ServletConfig)
      5. Create Request,Response object
      6. Call service(Request,Response)[Service Method from generic/HTTPServlet Class]
      7. Call Destroy.

Where;

Single Time Process

Upon Request Only [Multiple Types]

ServerShutdown [One time]

  • Object Creation is the single time process. Only for the first Request
  • Object  removed by either server shutdown /Garbage Collection.
  • Service method called according to the Request

GET:        URL: http://localhost:8080/test/Getserv?t1=abc&t2=123

  • Bookmark is possible
  • Max 255 Characters could be transformed
  • Data will be passed through URL
  • Faster than POST
  • Only Character can be transformed
  • Easier to switch between pages by change the values in URL.
  • GET method can be restricted in servlet and HTML by using doGet instead of service in servlet and Get in HTML.

POST:        URL: http://localhost:8080/Getserv

  • Data transferred through Socket.
  • Unlimited Character can be transferred. Because we using Socket instead of URL.
  • Able to send both character and binary type[file] data.
  • POST method can be restricted in servlet and HTML by using doPost instead of service in servlet and Post in HTML.

Where;

    • service only perform either GET/POST.
    • DoGet and DoPost will be called during Step 5 & Step 6
    • Default Method of form is GET
    • doGet and doPost will not called if we have the service in the program.
    • We can override doPost/doGet but we cant override service.

Redirecting Methods:

  1. SendRedirect :
        • Just Redirect to another page/Servlet
        • Wont allow reusing data from main servlet [Security for data]
        • It allow reuse the servlet/html to redirect to same/different application

res.SendRedirect(“/test/succ”)

  1. Forward
        • Forward to another page/Servlet with Request and Response object.
        • Allow reusing of Response&Resquest object from main servlet to child
        • ServletContext in forwarding used to redirect to other App’s in same Server.[Alternative to redirect to other Application]
        • It wont used outside the application only within same application

RequestDispatcher rd1=req.getRequestDispatcher(“/succ.html”);

Servlet Config:[Private Data]

  • Servlet Config value only applicable in the single servlet initialized in web.xml.
  • <param-name>x</param-name> <param-value>12<param-value> as it hold values.
  • Servlert Config value can be included in the servlet during servlet creation [or] after the creation in the web.xml. ServletConfig con1 = getServletConfig();

Servlet Context: [Global/Public Data]:

    • Servlet context data can be used by all the servlet in the package.
    • <context-param>…</context-param> hold the values in web.xml.
    • ServletContext con = getServletContext(); will get the value.

HTTP/TCP:

  • Http preferable for internet because ther is less waiting time for user and 1conn => 1req
  • Http is stateless protocol. It wont store any state of the client request.

SESSION:

  • A Session object is a single-threaded context for producing and consuming messages. Although it may allocate provider resources outside the Java virtual machine (JVM), it is considered a lightweight Java Message Service [JMS]object.
  • Sessions are commonly used to store temporary data to allow multiple pages to offer a complete functional transaction for the same visitor.

A session serves several purposes:

  • It is a factory for its message producers and consumers.
  • It supplies provider-optimized message factories.
  • It is a factory for TemporaryTopics and TemporaryQueues [Twitter Updates].
  • It supports a single series of transactions that combine work spanning its producers and consumers into atomic units.
  • It defines a serial order for the messages it consumes and the messages it produces.
  • It retains messages it consumes until they have been acknowledged[Security].
    • Every registered user has personalized username and password that will retrieve the personalized content and it used in all the pages to retrieve the content everywhere like inbox,sent Item,Draft.
    • These details is alive upto the session alive r user logout the service.
    • Session data available in anywhere in a application.

Ways to Create Session:

    1. Http Session
        • HttpSession interface is defined in “javax.servlet.http” package and is used for the purpose of session tracking while working with servlets.
        • Session Tracking:

Session tracking is a mechanism that is used to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time.

        • HttpSession session = request.getSession();

The session object can be found using getSession() method of the servlet request object. With the help of this interface the servlet can view and manipulate information about a session,

        • Inside the service method we ask for the session and every thing gets automatically, like the creation of the HttpSession object.
      • There is no need to generate the unique session id. There is  no need to make a new Cookie object. Everything happens automatically behind the scenes.
Method Description
getAttribute/Names()

getValue/Names()

Return object value or null if the object is not available
isNew() Returns true if the new session is created
getId() Returns a unique identifier assigned to this session.[Automated Value]
set/getMaxInactiveInterval() set/Returns the maximum time interval, in seconds, that the servlet container will keep this session alive.
invalidate()     Invalidates the session then unbinds any objects bound to the session.

b.Cookies

  • cookie are the object of the class javax.servlet.http.Cookie.
  • This class is used to creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server.
  • Cookies store the user details in client system and it will carried to server whenever the server need it.
  • Needs to carry more information to the server so efficiency will not be optimal.
  • A cookie’s value can uniquely identify a client, so cookies are commonly used for session management. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
  • Cookie cookie = new Cookie (“username”,username);

                    [Value]           [Cookie]

  • Method
  • Description
  • getComment()
  • Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.
  • getMaxAge()
  • Returns the maximum specified age of the cookie.
  • getName()
  • Returns the name of the cookie.
  • getPath()
  • Returns the prefix of all URLs for which this cookie is targeted.
  • getValue()
  • Returns the value of the cookie.
  • setComment(String)
  • If a web browser presents this cookie to a user, the cookie’s purpose will be described using this comment.
  • setMaxAge(int)
  • Sets the maximum age of the cookie. The cookie will expire after that many seconds have passed. Negative values indicate the default behavior: the cookie is not stored persistently, and will be deleted when the user web browser exits. A zero value causes the cookie to be deleted
  • setPath(String)
  • This cookie should be presented only with requests beginning with this URL.
  • setValue(String)
  • Sets the value of the cookie. Values with various special characters (white space, brackets and parentheses, the equals sign, comma, double quote, slashes, question marks, the “at” sign, colon, and semicolon) should be avoided. Empty values may not behave the same way on all browsers.

       

    c.URL Rewriting:

        • Appending the data’s in the URL and retrieve it from the response

    d.Hidden Form Field:

        • Send values from client to the server without the knowledge of the user.
        • It can be retrieved from the server using                      String x = response.getParameter(“hd1”);

Filter:

It’s used for pre-process the request and post-process the response.

Steps:

  • init(FilterConfig)
  • service(request,response,FilterChain);
  • destroy()
    1. Business Logic : Java Bean,EJB
    2. Presentation Logic : JSP,HTML
    3. Controller : Servlet

Java Server Page [JSP]:

  • It’s a presentation Logic
  • Automation tool for servlet
  • Don’t need to configure web.xml.
  • No restart / Re-compile during change in file
  • like JSP  buss.Logic and Presc.Logic it helps the developer to reuse the logics.
  • Modification can done with less alternation in code.
  • fast developement made possible by seperating buss.Logic/Presc.Logic.
  • It’s simillar to html the java codes will be included by using SCRIPTLETS <%…%>

Elements Of JSP:

  • Scriptlets <%…%>
  • Used to tell the browser the code in the body section is java.
  • Expression <%=….%>
  • Declaration <%!…%>
  • Comments
  • HTML  <!– …–>
  • Java <%….%>
  • JSP <%– … –%>

Directives:

  • Page Directive
  • Include Directive
  • Tag Directive

Interview Questions:

 What is J2EE?

J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications.

What can be considered as a web component? – J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content.

What is the container? – Containers are the interface between a component and the low-level platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container.

What are container services? – A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle management, security, deployment, and threading.

What is the web container? – Servlet and JSP containers are collectively referred to as Web containers. It manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server.

What is Enterprise JavaBeans (EJB) container? – It manages the execution of enterprise beans for J2EE applications. Enterprise beans and their container run on the J2EE server.

What is Applet container? – IManages the execution of applets. Consists of a Web browser and Java Plugin running on the client together.

What is JAXP? – JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations.

What is J2EE Connector? – The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter. Note: A resource adapter is a software component that allows J2EE application components to access and interact with the underlying resource manager. Because a resource adapter is specific to its resource manager, there is typically a different resource adapter for each type of database or enterprise information system.

What is JAAP? – The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization.

What is Java Naming and Directory Service? – The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and directory services such as LDAP, NDS, DNS, and NIS.

What is Struts? – A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between.

How is the MVC design pattern used in Struts framework? – In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application’s business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans.

What is deployment descriptor? – A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a component’s deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations

for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly.

How to communicate between twoservlets?

Two ways:

  1. Forward or redirect from one Servlet to another.
  2. Load the Servlet from ServletContext and access methods.

Servlet Collaboration or Communication can be achieved either by using Request Dispatcher’s Forward or Include methods (available with request object) or Send Redirect method(available with response object). Servlet Context is also one of the ways to acheive servlet collaboration coz it is the one which provides the information of all the servlets.

What is the servlet life cycle?

Each servlet has the same life cycle:

A server loads and initializes the servlet (init())

The servlet handles zero or more client requests (service())

The server removes the servlet (destroy()) (some servers do this step only when they shut down).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s