This page mainly contains my notes from:
a) Java: The Complete Reference
b) HeadFirst: Servlets and JSP
Index:
Chapter 1: Why use Servlets and JSPs
Chapter 2: Web App Architecture
Chapter 3: Mini MVC Tutorial
Chapter 4: Request and Response - Being a Servlet
Chapter 5: Attributes and Listeners - Being a Servlet
Chapter 6: Session Management - Conversational State
Chapter 7: Using JSP - Being a JSP
Chapter 8: Scriptless JSP - Script-free pages

c) Servlet and JSP : A Tutorial Kurniawan, Budi

Chapter 34: Java Beans

What is a Java Bean
- A Java Bean is a software content that has been designed to be reusable in a variety of different environments. There is no restriction in the capability (in terms of complexity) of a Java Bean. A bean may perform a simple function or a complicated function.
- At a basic level, JavaBeans are simply Java classes which adhere to certain coding conventions. Specifically, classes that have:
  • public default (no argument) constructors
  • allow access to their properties using accessor (getter and setter) methods
  • implement java.io.Serializable
  • all JavaBean instance variables should be private
What is the difference between a Java Bean and a POJO
- A JavaBean follows certain conventions. Getter/setter naming, having a public default constructor, being serializable etc. See JavaBeans Conventions for more details.
- A POJO (plain-old-Java-object) isn't rigorously defined. It's a Java object that doesn't have a requirement to implement a particular interface or derive from a particular base class, or make use of particular annotations in order to be compatible with a given framework, and can be any arbitrary (often relatively simple) Java object.
- All JavaBeans are POJOs but not all POJOs are JavaBeans.
What is the difference between a Java Bean and a Spring Bean
- A Spring bean is basically an object managed by Spring. More specifically, it is an object that is instantiated, configured and otherwise managed by a Spring Framework container. Spring beans are defined in Spring configuration files (or, more recently, with annotations), instantiated by Spring containers, and then injected into applications.
- Note that Spring beans need not always be JavaBeans. Spring beans might not implement the java.io.Serializable interface, can have arguments in their constructors, etc. This is the very basic difference between JavaBeans and Spring beans.
- The reason Spring managed objects are referred to as beans is because in the very early versions, Spring was intended only for use with JavaBeans. That is no longer the case of course: Spring can manage just about any object, even if it doesn’t have JavaBean type characteristics such as default constructors or mutator methods (getters and setters). None the less, the term ‘Spring beans’ has stuck. Can Spring beans be POJOs? Yes, and they usually are (although they don’t have to be – e.g. Spring can be used with ‘heavyweight’ Java objects, such as EJBs). Can Spring beans be JavaBeans? As I have said, yes and again they often are but don’t have to be.
A JavaBean on its own is not terribly interesting, it's just a Java class that conforms to some standards. However, conformance with this standard is one of the pillars on which the Java EE framework is built and it comes up in quite a few places. FYI, there are a few different types of EJB listed below:
  • Entity Beans:
  • You might want to read/write objects to/from an underlying database. You could use JDBC/SQL to do this but you could also use a persistance framework. The Java EE spec includes a spec for persistance whereby you declare your class to be an "entity bean" and have Java automatically generate database tables and logic to map between entries in your database and objects in your program. The actual implementation is provided by a lower level library such as Eclipselink, Toplink, Hibernate etc. but the Java API abstracts away any differences between them.
    Session beans represent logic while entity beans represented persistent objects. These days entity beans aren't used anymore in favour to JPA entities.
  • Stateful Session Beans
  • Imagine that you want to create an instance of a Java class which exists on separate JVM. The JVMs might be running on the same physical machine but equally, may be on separate machines communicating over a network. Using a Java EE application server, you can create a class which can be instantiated by clients of the app server. These clients can instantiate a class which will act just like a normal object but any methods that are invoked on the object get executed on the server with the results being passed back to the caller. It's basically an object oriented form of remote procedure calls.
  • Stateless Session Beans
  • This is a minor variation on stateful session beans. With stateful beans, if the server has 1000 clients then it will potentially have to create 1000 instances of the bean and remember which instance belongs to which client. With stateless beans, the server creates a pool of beans and doesn't bother to remember which client owns which bean. When a client invokes a method, the server picks a bean from the pool and uses it, returning it to the pool on completion. You use stateful session beans when you want the server to remember details about each client, you will use stateless beans when you don't need to remember client specific details. Note that the stateless beans may well have state, it's just that this state won't be of interest to the client.
  • Singleton Beans
  • //TODO..?
Introspection
Introspection is the automatic process of analyzing a bean's design patterns to reveal the bean's properties, events, and methods. This process controls the publishing and discovery of bean operations and properties.
There are two ways in which the developer of a Bean can indicate which of its properties, events, and methods should be exposed. With the first method, simple naming conventions are used. These allow the introspection mechanisms to infer information about a Bean. In the second way, an additional class that extends the BeanInfo interface is provided that explicitly supplies this information.
The introspection mechanism finds all of the public methods of a Bean. Protected and private methods are not presented.
Design Pattern for Properties
A property is a subset of a Bean’s state. The values assigned to the properties determine the behavior and appearance of that component. A property is set through a setter method. A property is obtained by a getter method. There are two types of properties:
  • Simple: A simple property has a single value. It can be identified by the following design patterns, where N is the name of the property and T is its type:
    public T getN()
    public void setN(T arg)
    A read/write property has both of these methods to access its values. A read-only property has only a get method. A write-only property has only a set method.
  • Indexed: An indexed property consists of multiple values. It can be identified by the following design patterns, where N is the name of the property and T is its type:
    public T getN(int index);
    public void setN(int index, T value);
    public T[] getN();
    public void setN(T values[]);
Design Pattern for Events
Beans use the delegation event model that was discussed earlier in this book. Beans can generate events and send them to other objects. These can be identified by the following design patterns, where T is the type of the event:
public void addTListener(TListener eventListener)
public void addTListener(TListener eventListener) throws java.util.TooManyListenersException
public void removeTListener(TListener eventListener)
These methods are used to add or remove a listener for the specified event. The version of addTListener() that does not throw an exception can be used to multicast an event, which means that more than one listener can register for the event notification. The version that throws TooManyListenersException unicasts the event, which means that the number of listeners can be restricted to one. In either case, removeTListener() is used to remove the listener.
//TODO: Example code of how to actually use a listener to listen for an event and take action based on it.

Chapter 35: Introducing Servlets

The javax.servlet Package
The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate.
Interface Description
Servlet Declares the life cycle methods for a Servlet
ServletConfig Allows Servlets to get intiialization parameters
ServletContext Enables servlets to log events and access information about their environment
ServletRequest Used to read data froma Client Request
Servlet Response Used to write data to a Client Response
Class Description
GenericServlet Implements the Servlet and the ServletConfig interfaces
ServletInputStream Encapsulates an input stream for reading requests from a client
ServletOutputStream Encapsulates an output stream for writing response to a Client
ServletException Indicates a Servlet error occurred
UnavailableException Indicates a Servlet is Unavailable
The Servlet Interface
- Defines methods that all servlets must implement.
- 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.
- To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet.
- This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence:
1) The servlet is constructed, then initialized with the init method.
2) Any calls from clients to the service method are handled.
3) The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.
- In addition to the life-cycle methods, this interface provides the getServletConfig method, which the servlet can use to get any startup information, and the getServletInfo method, which allows the servlet to return basic information about itself, such as author, version, and copyright.

Method Description
void init(ServletConfig sc) throws ServletException Called when the Servlet is initialized. Initialization parameters for the Servlet can be obtained from the sc. A ServletExce[tion should be thrown if the Servlet cannot be intiialized
void service(ServletRequest req, ServletResponse res) throws ServletException, IOException Called to process a request from the Client. The request from the clint can be read from req, the response to the client can be written to res. An exception is generated if if a servlet or IO problem occurs.
void destroy() Called when the Servlet is unloaded from the memory
String getServletInfo() Returns a String describing the Servlet
ServletConfig getServletConfig() Returns a ServletConfig object that contains any initialization parameters
The ServletConfig Interface
- A servlet configuration object used by a servlet container to pass information to a servlet during initialization.
The ServletContext Interface
- The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.
- This interface defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.
- There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.
The ServletRequest Interface
- Defines an object to provide client request information to a servlet.
- The servlet container creates a ServletRequest object and passes it as an argument to the servlet's service method.
- A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest.
The ServletResponse Interface
- Defines an object to assist a servlet in sending a response to the client.
- The servlet container creates a ServletResponse object and passes it as an argument to the servlet's service method.
- To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream(). To send character data, use the PrintWriter object returned by getWriter(). To mix binary and text data, for example, to create a multipart response, use a ServletOutputStream and manage the character sections manually.
The GenericServlet Class
- Defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend HttpServlet instead.
- GenericServlet implements the Servlet and ServletConfig interfaces. .
The javax.servlet.http Package
- The preceding examples have used the classes and interfaces defined in javax.servlet. However, when working with HTTP, you will normally use the interfaces and classes in javax.servlet.http.
Interface Description
HttpServletRequest Extends the ServletRequest interface to enable servlets to read data from the HTTP Request
HttpServletResponse Extends the ServletResponse interface to enable servlets to write data to an HTTP response
HttpSession Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.
Class Description
Cookie Allows state information to be stored ona Client machine
HttpServlet Provides methods to handle HTTP requests and responses.
The HttpServletRequest Interface
- Extends the ServletRequest interface to provide request information for HTTP servlets.
- The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).
- Java EE Link to the methods
The HttpServletResponse Interface
- Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies.
- The servlet container creates an HttpServletResponse object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).
- Several constants are defined that correspond to the different status codes that can be assigned to a HTTP Response.
- Java EE Link to the methods
The HttpSession Interface
- Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.
- The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs.
- This interface allows servlets to:
  • View and manipulate information about a session, such as the session identifier, creation time, and last accessed time
  • Bind objects to sessions, allowing user information to persist across multiple user connections
- //TODO:
- When an application stores an object in or removes an object from a session, the session checks whether the object implements HttpSessionBindingListener. If it does, the servlet notifies the object that it has been bound to or unbound from the session. Notifications are sent after the binding methods complete. For session that are invalidated or expire, notifications are sent after the session has been invalidated or expired.
- When container migrates a session between VMs in a distributed container setting, all session attributes implementing the HttpSessionActivationListener interface are notified.
- A servlet should be able to handle cases in which the client does not choose to join a session, such as when cookies are intentionally turned off. Until the client joins the session, isNew returns true. If the client chooses not to join the session, getSession will return a different session on each request, and isNew will always return true.
- Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another.
- Java EE Link to the methods
The Cookie Class
- The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state information.
- Cookies are valuable for tracking user activities. For example, assume that a user visits an online store. A cookie can save the user's name, address, and other information. The user does not need to enter this data each time he or she visits the store.
- A servlet can write a cookie to a user's machine via the addCookie() method of the HttpServletResponse interface. The data for that cookie is then included in the header of the HTTP response that is sent to the browser. The names and values of cookies are stored on the user's machine.
- Some of the information that can be saved for each cookie includes the following:
  • The name of the cookie
  • The value of the cookie
  • The expiration date of the cookie
  • The domain and path of the cookie
- The expiration date determines when this cookie is deleted from the user's machine. If an expiration date is not explicitly assigned to a cookie, it is deleted when the current browser session ends.
- The domain and path of the cookie determine when it is included in the header of an HTTP request. If the user enters a URL whose domain and path match these values, the cookie is then supplied to the web server. Otherwise, it is not.
- Java EE Link to the methods
The HttpServlet Class
- The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that receive and process HTTP requests.
- Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:
  • doGet, if the servlet supports HTTP GET requests
  • doPost, for HTTP POST requests
  • doPut, for HTTP PUT requests
  • doDelete, for HTTP DELETE requests
  • init and destroy, to manage resources that are held for the life of the servlet
  • getServletInfo, which the servlet uses to provide information about itself
- There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above). Likewise, there's almost no reason to override the doOptions and doTrace methods.
- Servlets typically run on multi-threaded servers, so be aware that a servlet must handle concurrent requests and be careful to synchronize access to shared resources. Shared resources include in-memory data such as instance or class variables and external objects such as files, database connections, and network connections.
- Java EE Link to the methods
Using Cookies
//TODO: There is an example in the book that you have to code
Session Tracking
- HTTP is a stateless protocol. Each request is independent of the previous one. However, in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism.
- A session can be created via the getSession() method of HttpServletRequest. An HttpSession object is returned. This object can store a set of bindings that associate names with objects. The setAttribute(), getAttribute(), getAttributeNames(), and removeAttribute() methods of HttpSession manage these bindings. Session state is shared by all servlets that are associated with a client.
Step1

These are my notes from the book - Head First: Servlets and JSP

Chapter 1: Why use Servlets and JSPs

- To prevent deployment problems that come with building stand alone apps, we instead deploy our apps to the browser.
Servers_And_Clients

Terminology

Web Server

: A web browser lets a user request a resource. The web server receives the request, finds the resource, and then sends it back to the user. A resource can be anything - HTML page, image, PDF File. If the requested resource is not found, the server replies with a 404-Not Found error code. A web server can refer to either the physical machine (hardware) or the web server application (software).

Web Client

: Both the human and the browser application (Mozilla, Chrome) being used are referred to as the Web Client. A web browser can communicate with the web server. It can interpret the HTML code that is sent as a part of the server's response and render that web page. Hence a Web Client (browser) lets the user request something from the server and shows the user the result of that request.

HTML

: When a server answers a request, the server usually sends some type of content for the browser to display. This content is written in HTML. Two important tags in HTML are: form and input
Expand Gist Expand Code Snippet

HTTP

: Most of the conversations held on the web between clients and servers are held using HTTP Protocol, which allows for simple request-response type conversations. The client sends an HTTP Request and the Server responds with a HTTP Response. HTTP runs on top of TCP/IP. The structure of and HTTP conversation is a simple Request/Response.
Key elements of the request stream
  • HTTP Method Name(the action to be performed): The method name tells the server the kind of request that is being made, and how the rest of the message will be formatted. The HTTP protocol has several methods, but we mostly use GET and POST methods.
    • GET: Gets a resource (HTML page, image, file,..) from the server and sends it back to the Client. You can also send some data (from the Client to the Server) with a GET request, but this is not recommended. Firstly, because the number of characters that are sent via a GET request are limited and secondly all the data sent in a GET request is visible in the URL. The "?" separates the path and the parameters. Together, the entire String is the request that is the URL that is sent with the request.
      GET_REQUEST
    • POST: With POST, you can request something and at the same time send form data to the server. For eg., if the user has completed a long form, you want this data to be stored into a database. In this case you would use a POST method. The data to be sent back to the server is known as the "payload" or the "message body".
      POST_REQUEST
  • The page to access (a URL)
  • Form parameters (like arguments to a method). These are sometimes also called "query strings"
  • Key elements of the response
  • A status code (for whether the request was successful)
  • Content-type (text, picture, HTML). Also known as MIME type
  • The actual content
  • HTTP_RESPONSE
    - An HTTP response can contain HTML. HTTP adds a Header to the response generated by the server. This Header information helps the client process the response. Inside this response can be a <html></html> that the client then renders as the HTML page that we finally see.
    All the pieces in one page
    All-The-Pieces
    What is a URL
    - Note the part labeled as Resource. Resource is the name of the content being requested. This could be an HTML page, a servlet, an image, pdf, or anything else. If this optional part of the URL is left out, most web servers will look for index.html by default. What_Is_URL
    What is a TCP Port
    - A TCP port is a 16-bit number that uniquely identifies the software that is running on the server hardware. They are NOT physical ports on a system. They are just numbers representing an applications. As per the standard, the HTTP Server Software runs on Port 80. Without port numbers, the Server would have no way of telling which application/software a Client wants to connect to.
    - Think of a port as a logical connection to a particular piece of software that is running on the server hardware.
    - There are a bunch of other ports that are pre-defined to connect to specific services. The TCP ports from 0 to 1023 are reserved for well-known services. Don't use these ports for your own custom programs.
    Two things the Server won't do on its own
  • Dynamic Content: The Web Server Application serves only static pages, but a separate "helper" application that the web server can communicate with can build non-static, just-in-time web pages. Just-in-time web pages do not exist before the request comes in. Once the request comes in, the helper app "writes" the HTML and the web server sends the page back to the Client as if it were a static web page.
  • Saving data on the Server: A Web Server cannot process form data. To process that form data, either to save it to a file or database or even just to use it to generate the response page, you need another app. When the web server sees a request for a helper app, it assumes that all of the parameters are meant for the Helper app. Hence the web server hands over the parameters and gives the app a way to generate a response to the client.
  • What is a Servlet? And what is JSP?
    - The Helper App in Java is known as a Servlet. So a Servlet is just some Java code. But when the web server calls the helper Servlet, it expects HTML code in return. This is done by using using the PrintWriter.println() method. The HTML code that is to be returned to the web server is included as a String type argument in the println() method. As you can hope, stuffing properly formatted HTML tags into the println()is not a viable solution. For eg. you will have to manually escape every quote character (") because Java treats them as end of string character. And HTML happens to use a ton of quotes to specify the attribute values and what not.
    - To solve this problem, JSPs were introduced. This allows us to add Java code to HTML instead of writing HTML code in a Java class. The JSP page contains java variables that calls the main Java code and creates the completed HTML page as a JIT web page.
    - Read more about what a servlet is on SO here. A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request. Basically servlets are usually used to implement web applications - but there are also various frameworks which operate on top of servlets (e.g. Struts) to give a higher-level abstraction than the "here's an HTTP request, write to this HTTP response" level which servlets provide. Servlets run in a servlet container which handles the networking side (e.g. parsing an HTTP request, connection handling etc). One of the best-known open source servlet containers is Tomcat.

    Chapter 2: Web App Architecture

    What is a Container
    - Servlets don't have a main() method. They are under the control of another Java application known as the Container.
    - Apache is you web server application. Tomcat is your Container.
    - When your web server application gets a request for a Servlet (as opposed to, say, a plain static HTML page) the server hands the request not to the servlet itself, but to the Container in which the servlet is deployed.
    - It's the Container that gives the Servlet the HTTP Request and Response, and it's the Container that calls the servlet's methods like doGet() and doPost().
    ContainerDescription
    What does the Container give you?
  • Communication Support

    : The Container(Tomcat) provides an easy way for your Servlets to talk to your Web Server. You don't have to build a ServerSocket, listen on a port, create Streams, etc. The Container knows the protocol between the Web Server and itself, so that your Servlet does not have to worry about, say, the API between the Apache Web Server and your own web application code.
  • Lifecycle Management:

    The Container controls the life and death of you servlets. It takes control of loading the classes, instantiating and initializing the servlets, invoking the servlets methods, and making servlets instances available for garbage collection. With the Container in control, you do not have to worry about the resource management.
  • Multithreading Support:

    The Container automatically creates a new Java thread for every servlet request that it receives. When the Servlet's done running the HTTP service() method for that Client's request, the thread completes (dies). But you are still responsible for Thread safety and other synchronization issues. It's just that the work involved in creating and deleting threads is reduced.
  • Declarative Security:

    XML Deployment Descriptors allow you to configure Security without having to hard-code it into any of your servlets or other classes.
  • JSP Support:

    Container also takes care of translating the JSP code into real Java.
  • How the Container handles a request

    Step 1:

    User clicks on a link that has a URL to a servlet instead of a static web page
    Step1

    Step 2:

    The Container "sees" that the request is for a Servlet, so the container creates two objects: HttpServletRequest and HttpServletResponse
    Step2

    Step 3:

    The Container finds the correct Servlet based on the URL in the request, creates or allocates a thread for that request, and calls the servlet's service(HttpServletRequest req, HttpServletResponse resp) method, passing the request and response objects as arguments .
    Step3

    Step 4:

    Depending on the type of the request, the service() methods calls either the doGet() or doPost() methods. For this example, we assume that the request was a HTTP GET method. So the service() method calls the servlet's doGet(HttpServletRequest req, HttpServletResponse resp) method passing the request and the response objects as arguments.
    Step4

    Step 5:

    The doGet() method generates the dynamic page and stuffs the page into the response object. Remember that the Container still has a reference to the Response object.
    Step5

    Step 6:

    The thread completes, so the thread either dies or returns to a Container-managed thread pool. The container converts the response object into an HTTP Response, sends it back to the client, and then deletes the request and the response object.
    Step6
    What makes a Servlet a Servlet
    - Note that a Servlet class (in the below example image Ch2Servlet) does not have a main() method. It only has a doGet() method. In the below example, we are basically overriding the doGet method of the HttpServlet class.
    Servlet?
    - HttpServlet is an abstract class that to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:
  • doGet, if the servlet supports HTTP GET requests
  • doPost, for HTTP POST requests
  • doPut, for HTTP PUT requests
  • doDelete, for HTTP DELETE requests
  • init and destroy, to manage resources that are held for the life of the servlet
  • getServletInfo, which the servlet uses to provide information about itself
  • - There's almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above).
    - Source for the below text.
    - Servlet API classes reside in javax.servlet and javax.servlet.http.
    - These packages are distributed with Tomcat. Tomcat is a open source servlet container and webserver.
    - The javax.servlet package contains three interfaces:
    a) Servlet - init(), service(), destroy()
    b) ServletRequest
    c) ServletResponse
    - The javax.servlet.http package supplies interfaces that make it easy to build servlets that support HTTP requests and responses. Two important interfaces in javax.servlet.http are HttpServletRequest and HttpServletResponse.
    - The HttpServlet class extends GenericServlet and is used to develop servlets that handle HTTP requests.
    When a Client clicks on a URL containing a Servlet in Step 1, how does the Container know which Servlet to call?
    - //TODO: I no longer understand what is going on over here.Why do we need three names. Whats is the difference between the second and the third option? Maybe this SO Link has the answer.
    - Consider a compiled Servlet class that is present in the following directory: classes/registration/SignUpServlet.class
    - The Servlet can be called using any of the following 3 names:
  • File Path Name (XXXX.class name): This (classes/registration/SignUpServlet.class) is the ACTUAL name of the .class file that is stored on the server and denotes it's actual path in the directory.
  • Public URL Name: The name encoded into the HTML so that when the user clicks a link that is supposed to go to that servlet, this public URL is sent to the Server in the HTTP Request.
  • Deployment Name: It is a secret internal name (not known to the Client) that is given to the .class file. This can be the same as the File Path Name, but can be something completely different as well.
  • - Thus we can map the Public URL to a Deployment name and have that Deployment name refer to a .class file.
    - Why do we do this:
    • Flexibility: We can change the path of the .class file without breaking the path of every file that referenced this class file
    • Security: We do not want the Client to know the internal directory structure of the Server.
    How do we map URLs to Servlets: Deployment Descriptors
    - When you deploy your servlet into your web Container, you will create an XML document called the Deployment Descriptor to tell the container how to run your Servlets and JSPs.
    - We use two XML elements to map URLs to Servlets - one to map the Client-known Public URL Name to our own internal deployment name, and the other to map our own internal deployment name to the fully-qualified class-name.
    //TODO:Where is the DD file stored in the IntelliJ project that we created? I am pretty sure it is just the web.xml file in your project.
    - The two DD elements for URL Mappings are:
    • <servlet>: maps internal name to fully-qualified class name
    • <servlet-mapping>: maps internal name to public URL name
    - DD also helps us to customize other aspects of our web application like adding security roles, error pages, tag libraries. All this can be done without changing the source code.
    DeploymentDescriptor
    - Note that the <servlet-class> tag still contains only the class name and not the complete path of the the .class file. This is because the Container has a specific place that it will look for all Servlets for which you have specified a mapping in the DD.
    - There is a lot of other stuff that you can do using the web.xml file. Refer this Oracle link to see which elements can be defined using your deployment descriptor.
    What is MVC: Model-View-Controller
    - The essence of MVC is that you separate the business logic from the presentation, but put something in between them so that the business logic can stand on its own as a reusable Java class, and doesn't have to know anything about the view. In other words, the business logic should never go into the Servlet. Because the Servlet contains the JSP page, it means that the business logic is tied to the JSP page. We cannot re-use the business logic for some other kind of view, like a GUI. The business logic should always be in a standalone Java class that can be reused.
    - This is how the code looks without using MVC:
    MVC
    - Model-View-Controller takes the business logic out of the Servlet and puts it in a "Model" - a reusable plain old Java class. The Model is a combination of the business data and the methods that operate on the data.
    MVC
    - Thus for each Servlet, there will be a new business logic class that will be the Model, a JSP page that will be the View, and the original Servlet, bereft of any logic or HTML, that will form the Controller part of the puzzle.
    MVC
    - But now the problem is that there are a gazillion little Servlets, and all they are doing is updating the Model and then displaying the View. Lot of code duplication apparently...
    Overview of separation of concerns
    Table
    How does J2EE fit into all of this
    The Java 2 Enterprise Edition is kind of a super-spec - it incorporates other specifications, including the Servlets 2.4 Spec and the JSP 2.0 spec. That's for the Web Container. But the J2EE 1.4 spec also includes the Enterprise JavaBean 2.1 specification, for the EJB Container. In other words, the web container is for the web components (servlets and JSPs) whereas the EJB Container is for the business components.
    - A fully-compliant J2EE server must have both a web Container and an EJB Container (plus other things including a JNDI and JMS implementation). Tomcat is just a web Container!(?). It is still compliant with the portions of J2EE spec that address the web container. Tomcat is a web container, not a full J2EE application server, because Tomcat does not have an EJB Container.
    - As shown in the below figure, a J2EE application server consists of both a web container and an EJB Container. Tomcat is a web Container but not a full J2EE Application server. J2EE Application Server

    Chapter 3: Mini MVC Tutorial

    - The process for creating a Enterprise Application in IntelliJ can be found here.
    Architecture of the Web App
    MyBeerApp-Architecture
    Creating the Development Environment

    -index.jsp is the file that contains the first page that the user sees when they login into the http://localhost:8080/BeerV2_war_exploded/. Changing the name of index.jsp to some other name causes the app to stop working for some reason.
    - The web.xml is the Deployment Descriptor that we looked at in the previous chapter. br - When it's time to deploy our app, we will copy a portion of this into wherever our particular Container wants the pieces to go.

    Development-Environment
    Tomcat log when app was deployed successfully
    - This is an example of Tomcat Log generated when the Web-App was deployed successfully.
    Expand Gist Expand Code Snippet
    Creating the Deployment Environment:
    - Deploying an app requires both container-specific rules and requirements of the Servlets and JSP Specifications. Everything below the Beer-v1 directory is the same regardless of your container. Only the folder structure above that that is marked as Tomcat-specific will differ.
    - Note that the Beer-v1 directory represents the context root which Tomcat uses when resolving URLs.
    Deployment-Environment
    Building the App

    Step 1

    : The Client makes a request for the form.html page

    Step 2

    : The Container retrieves the form.html page

    Step 3

    : The Container returns the page to the browser where the user answers the question on the form and Clicks Submit
    Form
    - Clicking the SUBMIT button causes the HTML form to send a POST request to the server. This request is sent to the SelectBeer.do file (Line 20). Remember that there is no actual class named such. It's mapped to an internal Servlet name using the Deployment Descriptors.
    Expand Gist Expand Code Snippet
    - Note the URL to which the POST request is being sent to POST /BeerRecommender_war_exploded/SelectBeer.do. In the HTML, the /BeerRecommender_war_exploded/ isn't part of the path in the HTML, it just says: <form method="POST" action="SelectBeer.do"> But the browser prepends the /BeerRecommender_war_exploded/ on to the request because that's where the client request is coming from. In other words, the SelectBeer.do is relative to the root of the web app /BeerRecommender_war_exploded
    Request URL
    Form

    Step 4

    : The browser sends the request data to the Container. Now the Container has to figure out which is the actual Class to which the SelectBeer.do maps.
    - For this, the Container looks in the web.xml file (Deployment Descriptor). The container searches the DD and finds a <servlet-mapping> with a <url-pattern> that matches /SelectBeer.do where the / represents the context root of the web app, and SelectBeer.do is the logical name of the resource.
    - The container sees that the <servlet-name> for this <url-pattern> is 'Ch3 Beer'. But that isn't the name of the actual servlet class file. To a container a servlet is something that is named in the DD under the <servlet> tag. The 'name' of the servlet is simply the name used in the DD so that other parts of the DD can map to it.
    - So now the container looks inside the <servlet> tags for something with the <servlet-name> 'Ch3 Beer'.
    - The Container uses the <servlet-class> in the <servlet> tag to know which servlet class is responsible for handling this request. If the servlet has not been initialised, the class is laoded and the servlet is initialized.
    - The Container then starts a new thread to handle the request, and passes the request to the thread (to the servlet's service() method).
    Expand Gist Expand Code Snippet

    Step 5

    : The Container finds the correct Servlet and passes the request to the Servlet. This class acts as the Controller, calling the Model BeerExpert for the business logic, and the View result.jsp for the response.
    Expand Gist Expand Code Snippet

    Step 6

    : The Servlet calls the BeerExpert class for help.
    Expand Gist Expand Code Snippet

    Step 7

    : The BeerExpert class returns an answer that the Servlet class adds to the request object.
    The Container provides a mechanism called "Request Dispatching" that allows one container-manged component to call another container-managed component. This is what we use here - the Servlet gets the info from the model, saves it in the request object, then dipatches the request to the JSP.

    Step 8

    : The Servlet forwards the request to the JSP.
    Expand Gist Expand Code Snippet

    Step 9

    : The JSP gets the answer from the request object.

    Step 10

    : The JSP generates a page for the Container.

    Step 11

    : The Container returns the page to the User.

    Chapter 4: Request and Response - Being a Servlet

    - In the previous chapter we looked at the Container's overall role in the Servlet's life. The container creates the request and the response objects, creates or allocates a new thread for the servlet, and calls the servlet's service() method, passing the request and response objects references as arguments. In this Chapter we look at the Servlet's life in more detail.
    - The servlet lifecycle is pretty simple.. There is only one main state: initialized. If the servlet isn't initialized then it is either being initialized (by running it's constructor or the init() method), being destroyed (by running it's destroy()) method, or it simply does not exist.
    - A state diagram for the servlet would look something like this:
    Servlet state diagram
    What do the init, service, and destroy methods do?
    -

    init()

    : The method is called after the servlet instance has been created (using the the default no-args constructor) but before the servlet can service any client requests. You can override this method in case you have to get a database connection, or you have to register yourself with other objects.
    -

    service()

    : When the first Client request comes in, the Container starts a new thread or allocates a new thread from the pool and causes the servlet's service() method to be invoked. This method looks at the request, determines the HTTP method (GET, POST, etc.) and invokes the matching doGet() or doPost() methods respectively. Note that there are other methods in HTTP as well (HEAD, PUT, etc) and there are corresponding doXXXXX() methods for almost all of them. Refer the HttpServlet class below. You should not override the service() method. Your job is to override the doGet() or the doPost() methods, and let the service() implementation from the HttpServlet worry about calling the right one.
    -

    doPost()/doGet()

    : The service() method invokes the doGet() or the doPost() based on the HTTP method (GET, POST, and so on). This is where your code begins. All the stuff that your app is supposed to be doing goes in here. Always override at least one of these methods. Whichever ones you override tells the Container what you support. If you do not override doPost(), for example, then you are telling the Container that this servlet does not support the HTTP POST request.
    -

    destroy()

    : Called by the Servlet Container to take the Servlet out of service. This method is only called once all threads within the servlet's service method have exited or after a timeout period has passed. After the container calls this method, it will not call the service() method again on the Servlet.
    Servlet_LifeCycle
    - The Servlet moves from the does not exist to the initialized state beginning with the constructor. But the constructor makes only the object, not the Servlet. When an object becomes a servlet, it gets all the unique privileges that come with being a servlet, like the ability to use it's ServletContext to get information from the Container.
    Methods inherited by the Servlet that you create
    - So overall the process proceeds like this: (refer below diagram) Suppose my servlet is the MyServlet class. The Container calls MyServlet's init() method. But if I do not override init, the one from GenericServlet runs. Then when a request comes in, the Container starts or allocates a thread and calls the service() method, which I do not override. So the service method from the HttpServlet runs. The HttpServlet service method then calls my overridden doGet or doPost methods. So each time my doGet or doPost runs, it's in a different thread.
    - The Servlet inherits the following methods:
    Servlet_Inheritance
    Each request runs in a separate thread
    - Remember that each Client request runs in a separate thread. At any given time, you will have at least as many runnable threads as there are client requests.
    - You might hear things like "Each instance of the servlet..". This is incorrect. There aren't multiple instances of any servlet class (except SingleThreadModel, but that is a bad design pattern). The Container runs multiple threads to process multiple requests to a single servlet. And every Client request generates a new pair of request and response object.
    Threaded
    What happens if the same client makes multiple request? Is it one thread per client or one thread per request?
    - It is one thread per request. The Container doesn't care who makes the request. Every incoming request means a new thread/stack.

    thread-per-request vs thread-per-connection

    : Per request means when an HTTP request is made, a thread is created or retrieved from a pool to serve it. One thread serves the whole request. Thread per connection would be the same thing except the thread is used for an entire connection, which could be multiple requests and could also have a lot of dead time in between requests. Servlet containers are thread per request. Source on SO.

    Should I spawn new threads in a JAVA EE Container

    : If you're in a full Java EE container, threads may be managed for you in a way that makes it a bad idea to spawn your own. Source on SO. Also there are now Concurrency Utils that enable you to achieve this so that you do not have to do this manually. Source on SO.

    HttpServlet is in a different package from GenericServlet. How many servlet packages are there?

    Everything related to servlets is in either javax.servlet or javax.servlet.http. It's easy to tell the difference because things that have to do with HTTP are in the javax.servlet.http package whereas the generic servlet classes and interfaces are in javax.servlet.
    What does 'being a servlet' buy you?
    - Remember that the constructor just creates an object, not a servlet. To be a servlet, the object needs to be granted servletness. This is the task of the init() method. The init() method is called just once during the entire life of the servlet.
    - A servlet allows you to access the following:

    ServletConfig

    : This controls the deploy-time values you've configured for the servlet (one per servlet). Things that your servlet might want to access that you do not want to hard code, like maybe a database name. ServletConfig parameters won't change for as long as this servlet is deployed and running. To change them, you will have to re-deploy the servlet. This is also used to access ServletContext. The parameters are configured in the Deployment Descriptor.

    ServletContext

    :There is only one ServletContext per web app, NOT one per servlet. These are used to access web app parameters that are also configured in the Deployment Descriptor.
    What is a Request or a Response object?
    - The HttpServletRequest methods are about HTTP things like cookies, headers, and sessions. HttpServletRequest interface adds the methods that relate to the HTTP protocol. Same thing with the HttpServletResponse as well.
    - ServletRequest: A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest).
    - ServletResponse: Defines an object to assist a servlet in sending a response to the client. The servlet container creates a ServletResponse object and passes it as an argument to the servlet's service method.
    - HttpServletRequest: Extends the ServletRequest interface to provide request information for HTTP servlets. The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).
    - HttpServletResponse: Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies. The servlet container creates an HttpServletResponse object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).
    - Remember that HttpServletRequest and HttpServletResponse are interfaces as well. The implementation of these interfaces is left to the vendor. All you need to know is the methods that you can call on these objects. The actual class does not matter because you are referring to the request and the response objects only by the interface type.
    Servlet_Inheritance

    - There are 8 HTTP methods (actually 9 now). There is no mechanism in the servlet API for handling doConnect, so it is not a part of the HttpServlet.
    - Recall the difference between GET and POST that we studied earlier. The key difference between the two was that POST has a body, whereas in the GET request all of the parameters are sent in the header. Remember that GETis ONLY supposed to be getting things from the server. it should not make any changes to the server. POST on the other hand is used to send data to the server for update.
    - This makes GET an idempotent request: making the same GET request twice will cause no negative consequences on the server.
    - POST, on the other hand, is a non-idempotent request. The data sent to the server could be used to update some state that cannot be reversed. Think a financial transaction that cannot be reversed. Intuitive example in book. Basically, you want to ensure that your app logic can handle scenario where the same request comes in more than once by mistake.
    - Note that there is nothing stopping you from implementing the GET method in the doGet method as an non-idempotent method. But you would not want to do so...
    What determines whether a browser sends a GET or POST request:
    - Remember the POST is not the default. If you do not specify a method, by default the GET method will be used.
    Expand Gist Expand Code Snippet
    How do you send multiple parameters using the POST request
    - In the previous POST request that we sent in Step 3, the browser sent only one of the four options (light/amber/brown/dark) as the value of the parameter color1. But what if we wanted two or more parameters from the user. This is how we would do it:
    Expand Gist Expand Code Snippet
    - If in the previous case the POST request sent the values of the parameters as color1=light, in this example the parameters will be sent as color1=light&theSize=heavy. That is - the POST request will have both the parameters but separated by an ampersand.
    - The Servlet class would then use the parameters in the following manner:
    Expand Gist Expand Code Snippet
    How do you use multiple values for a single parameter
    - Excellent explanation of checkboxes on MDN here. A lot of good stuff there. Read the entire page. Basically each of the input of type checkbox should be given the same name attribute.
    - In the previous example, you had one parameter theSize associated with just a single value (either light, medium, or heavy). However, some form inputs like checkboxes can have more than one value. That means a single parameter like theSize will could have more than one value depending on how many boxes the user has checked off.
    - This is what the form looks like: Multiple values for Checkbox
    Expand Gist Expand Code Snippet
    And the corresponding Servlet class would look like this:
    Expand Gist Expand Code Snippet
    - The form data in the POST request will look like this when multiple checkboxes are selected:
    userName=&userEmailId=&beer_color_user_likes=light&user-newsletter=on&user-beer-sizes=12&user-beer-sizes=14
    - Assume on the front-end we selected the 12oz and 14oz checkboxes. In the below image you can see that beer_sizes in the servlet code contains the value associated with the checkboxes of 12oz and 14oz options.
    Multiple values for Checkbox
    Besides the parameters, what else can I get from the Request object:
    - You really should look at the full API for javax.servlet.ServletRequest and javax.servlet.http.HttpServletRequest.
    Expand Gist Expand Code Snippet

    - //TODO: Read up on the methods getInputStream and getReader. If one is called, then the other can't be called or something like that.
    - Note the presence of the three different methods:
  • getRemotePort: In this case, since it is the server asking, it's the Client that is the Remote. So getRemotePort means the Client's remote port. In other words, the port number on the Client from which the request was sent. Remember, if you are a servlet, remote means the Client.
  • getServerPort: This method asks "to which port was the request originally sent"
  • getLocalPort: This method asks "on which port did the request ultimately end up". There is a difference between the above two methods because although the requests are sent to a single port (where the server is listening), the server turns around and finds a different local port for each thread so that the app can handle multiple clients at the same time.
  • Understanding the Response Object
    - The Response is what goes back to the Client. Typically, you use the response object to get an output object (usually a Writer) and you use that Stream to write the HTML (or some other type of content) that goes back to the Client.
    - You call two methods on the response: setContentType and getWriter. After that you are simply doing I/O to write HTML (or something else) to the stream. But you can also use the response to set other headers, send errors, and add cookies.
    ServletResponse_Interface
    How do I send a application/jar type content in response instead of a normal HTML page
    - Instead of sending an HTML page, the response contains the bytes representing the JAR. You read the bytes of the jar file, and then write them to the response's output stream. For this we make use of the getResourceAsStream method. Note that there is another method called getResourceAsStream in the Class class as shown here on Java docs. Both are different from each other.
    - This SO Link goes into detail about ways to troubleshoot getResourceAsStream causing a NPE. There are a lot of linked questions on the page as well that should be helpful.
    - Answer by BalusC explaining different ways that you can access a file from your code. Do you understand what a 'classpath' actually means now?
    - Note the path where we placed the file:
    ServletResponse_Interface
    - This is what the servlet code looks like.
    Expand Gist Expand Code Snippet
    - We added a new mapping in the web.xml. And linked the servlet in the JSP file like this.
    - Note the '/' inside the url-pattern. Without that, we get an error saying invalid url.
    ServletResponse_Interface
    What does setting the setContentType do
    Source
    - Content types are included in HTTP responses because the same, byte for byte sequence of values in the content could be interpreted in more than one way. Remember that http can transport more than just HTML (js, css and images are examples), and in some cases, the receiver will not know what type of object it's going to receive. This is the same thing as setting the MIME type. Content type is an HTTP Header that must be included in the HTTP Response.
    - Remember to always call setContentType before you have called the method that gives you your output stream (getWriter or getOutputStream). That will guarantee you will not run into conflicts between the content type and the output stream.
    - Common MIME types are:
    • text/html
    • application/pdf
    • video/quicktime
    • application/java
    • image/jpeg
    • application/jar
    • application/octet-stream
    • application/x-zip
    What is the difference between ServletOutputStream and PrintWriter:
    - There are two ways in which you can write to a response object in a servlet.
    - You can either use the getWriter() or you can use the getOutputStream()
    Expand Gist Expand Code Snippet
    - So: to send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream(). To send character data, use the PrintWriter object returned by getWriter(). To mix binary and text data, for example, to create a multipart response, use a ServletOutputStream and manage the character sections manually.
    What is the difference between setHeader and addHeader methods
    - setHeader: Sets a response header with the given name and value. If the header had already been set, the new value overwrites the previous one. The containsHeader method can be used to test for the presence of a header before setting its value.
    - addHeader: Adds an additional value to the response header. Added value being the the current given name and value. This method allows response headers to have multiple values.
    - Along the same lines you have addIntHeader and setIntHeader.
    How can you make someone else handle the response
    - You can choose to have something else handle the response for your request. You can either redirect the request to a completely different URL. Or you can dispatch the request to some other component in your web app (usually a jsp).
    - We will look at both the methods in the following examples.
    Using a Redirect
    - This is a high-level explanation of how this works:
    Redirect
    Redirect
    - So things are going to get a bit murky now.
    - You need to specify a URL to redirect to. And you do it using response.sendRedirect("/yourRedirectUrl")
    - The URL can be specified in different ways, by which I mean, you can either give the full path of the URL (like "https://www.google.com"), or you can give the Relative URL.
    - Now the relative URL can be specified in two ways. Either the URL can or cannot start with a forward slash / character.
    - Imagine the client originally typed in https://www.ws.com/myApp/cool/bar.do. The request comes in into the servlet mapped to bar.do, and the servlet calls sendRedirect() with a RELATIVE URL that does NOT start with a '/': sendRedirect("foo/stuff.html"). The container will then build the full URL relative to the original request URL: https://www.ws.com/myApp/cool/foo/stuff.html. Hence if you don't start with a '/', then the request path is prepended to the front of foo/stuff.html
    - But if the argument to the sendRequest() DOES start with a '/' as in sendRedirect("/foo/stuff.html"), the container will build the complete URL relative to the WEB CONTAINER ITSELF, instead of the original URL of the request. So the new URL will be: https://www.ws.com/foo/stuff.html. foo is treated as a separate webapp from the myApp webapp in the previous case. Hence, in this case, the forward slash at the beginning means "relative to the root of this web container".
    Expand Gist Expand Code Snippet
    What is a 302 Found redirect
    - Source on SO here.
    - A response with 302 is a common way of performing URL redirection. Along with the 302 status code, the response should include a Location header with a different URI. Such header will be parsed by the user agent and then perform the redirection:
    302 Redirection Protocol
    - The RFC defines 302 Found as follows: The 302 (Found) status code indicates that the target resource resides temporarily under a different URI. Since the redirection might be altered on occasion, the client ought to continue to use the effective request URI for future requests. The server SHOULD generate a Location header field in the response containing a URI reference for the different URI. The user agent MAY use the Location field value for automatic redirection. The server's response payload usually contains a short hypertext note with a hyperlink to the different URI(s). Note: For historical reasons, a user agent MAY change the request method from POST to GET for the subsequent request. If this behavior is undesired, the 307 (Temporary Redirect) status code can be used instead.
    - On our page, the 302 behavior looks something like this:
    302 Redirection Protocol
    How do we set a different status code - like 301 for example
    - Refer this answer on SO.
    - Remember that you can set the headers manually as well. This is how we are achieving this.
    Expand Gist Expand Code Snippet
    How to put JSP files in a separate folder
    - So far in the examples that we have seen, all the the jsp files were present outside the WEB-INF folder. The problem with this is that, because the files are outside the WEB-INF folder, we can directly access them by going to the URL directly. What I mean is, we could directly type in http://localhost:8080/BeerRecommender_war_exploded/beer-form.html in the address bar, and that would take us to the form. No need to click on anything or to go through actual links. Now this is fine for the form, but becomes a problem when we navigate to the result.jsp page directly by typing in the address. It leads to 500 error because the request object is not populated yet.
    - So we want a structure that looks something like the below one:
    Basic Structure of JSP Files
    - Remember, any file under the WEB-INF folder is a protected resource. It will have to be accessed by calling /WEB-INF/ from a ServletContext. Source on SO.
    - So how do we do this? Read this SO answer here. The left image is currently the scenario 1 in the answer. We want it to change to scenario 3.
    Why do I have to prepend the path in JSPs with ${pageContext.request.contextPath}
    - Read on SO here.
    -
    What is a Request Dispatch
    - A redirect makes the Client do the work. Whereas a Request Dispatch makes something else on the server do the work.
    - Read about the differences between the two on SO here.
    RequestDispatch
    What is the Post-Redirect-Get Pattern
    - Excellent answer by BalusC on SO here.
    - //TODO: Write Code Example.

    Chapter 5: Attributes and Listeners - Being a Servlet

    How to pass init params to specific servlets? What are init-params in the ServletConfig?
    - Servlets can have initialization parameters. We use the <init-param> element to specify the name-value pairs. Note that the <init-param></init-param> should be inside the servlet element that you want to initialize with the particular value.
    - When the Container initializes a Servlet, it makes a unique ServletConfig for the Servlet. The Container reads the servlet init parameters from the DD and gives them to the ServletConfig, and then passes the ServletConfig to the servlet's init method.
    - Note that the Servlet init parameters are read only once - when the Container initializes the Servlet. Once the parameters are in the ServletConfig they won't be read again until/unless you redeploy the servlet.
    Servlet state diagram
    Servlet state diagram
    - The problem with the above approach is that, if now suppose we have to use the same emailId parameter in another servlet, we will have to copy the same value to the another servlet as well. Hence we also need to define a way in which we can access the same parameter across all servlets.
    How to make parameters available to entire web app including JSPs? What are context-params in ServletContext?
    - Context init params work just like servlet init parameters, except that context parameters are available to the entire web app, and not just a single servlet. That means any servlet or JSP can automatically access the context init parameters.
    Servlet state diagram
    Difference between the Servlet-Init parameters and the Context-Init parameters
    - Both of them make use of the same method to access the parameters, but the methods are called on different objects.
    - For accessing servlet-init/ServletConfig params : getServletConfig().getInitParameter("emailId");
    - For accessing context-init/ServletContext params: getServletContext().getInitParameter("adminEmailId"))
    - Both of these methods are from the GenericServlet class that is inherited by the HttpServlet which in turn is inherited by your Servlet class.
    - ServletConfig is one per servlet, whereas ServletContext is one per webapp. i.e. every servlet and JSP deployed as part of a single webapp has access to that same ServletContext. But every servlet has it's own ServletConfig.
    - A servlet-init parameter and a context-init parameter can have the same name. Remember, they are being read from completely different objects. Hence there is no issue of shadowing/name space conflict.
    Diff-servletInit-contextInit
    What are the methods in the ServletConfig class
    - ServletConfig is a servlet configuration object used by a servlet container to pass information to a servlet during initialization.
    - It has the following methods:
    Method Description
    String getInitParameter(String name) Gets the value of the initialization parameter with the given name.
    Enumeration<String> getInitParameterNames() Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters.
    ServletContext getServletContext() Returns a reference to the ServletContext in which the caller is executing. Same as running this.getServletContext
    String getServletName() Returns the name of this servlet instance.
    How can I use a Listener to read values from the web.xml and use it to add objects into the ServletContext for the entire webapp to read?
    - ServletContextListener docs.
    - The problem with using the context-init parameters is that you are only allowed values that are of type String. What if you wanted to do something more involved - like adding an object to your webapp that any servlet/JSP could access? Here we make use of a Listener that reads the value of the context init param from the DD, and using that string value, creates a new object and adds it to the ServletContext using setAttribute that is then passed to your web app. Any servlet/jsp can then get that attribute from the ServletContext object using getAttribute.
    - This is what you came up with:
    Listener Code Snippet
    - Here is the complete picture:
    - Note that THE code is mainly using the ServletContextListener. Both contextInitialized and contextDestroyed methods are overridden. I think it is mainly being used for logging purposes, to kind of try and understand what kind of branch the code is taking (I guess!). Nothing is being read from the ServletContextEvent.
    The HttpSessionListener interface
    - This is the only other EventListener being used in THE code.
    - HttpSessionListener docs.
    Different types of Listeners
    - There can be different types of listeners triggering on different types of events:
    What is an attribute
    - An attribute is an object bound into one of three other Servlet API objects: ServletContext, HttpServletRequest (ServletRequest), or HttpSession
    - An attribute is simply a name/value pair (where the name is a String and the value is an object) in a map instance variable.
    - In reality, we do not care how it is implemented - all we really care is about the scope in which the attribute exists. In other words, who can see it and how long does it live.
    What is the difference between an attribute and a parameter
    - An attribute is not a parameter: StackOverflow Source
    - We use request.getParameter() to extract request parameters (i.e. data sent by posting a html form). The request.getParameter() always returns String value and the data comes from client. The exception to this is ServletContext and the ServletConfig init-parameters which are string parameters that are configured in web.xml and exist on the server.
    Diff_betn_Attribute_And_Parameter
    All_Attributes
    What is the difference between the Context, Session, and Request Scopes
    - Context Attributes: A ServletContext attribute is an object bound into a context through the ServletContext.setAttribute() method and which is available to ALL Servlets (thus JSP) in that context, or to other contexts via the getContext() method. By definition a context attribute exists locally in the VM where they were defined. So, they're unavailable on distributed applications.
    - Session Attributes: Session attributes are bound to a Session, as a means to provide state to a set of related HTTP requests. Session attributes are available ONLY to those Servlets which join the session. They're also unavailable to different JVMs in distributed scenarios. Objects can be notified when they're bound/unbound to the Session implementing the HttpSessionBindingListener interface.
    - Request Attributes: Request attributes are bound to a specific request object, and they last as far as the request is resolved or while it keeps being dispatched from Servlet to Servlet. They're used more as communication channel between Servlets via the RequestDispatcher Interface (since you can't add Parameters...) and by the container. Request attributes are very useful in web apps when you must provide setup information between information providers and the information presentation layer (a JSP) that is bound to a specific request and need not be available any longer, which usually happens with sessions without a rigorous control strategy.
    - StackOverflow Source
    - These 3 attribute scopes are handled by the ServletContext, HttpSession, and ServletRequest interfaces. The API methods for these attributes are the same in every interface:
    • Object getAttribute(String name)
    • void setAttribute(String name, Object value)
    • void removeAttribute(String name)
    • Enumeration<String> getAttributeNames(String name)
    All_Attributes
    Expand Gist Expand Code Snippet
    Context Scope isn't Thread-Safe. Neither is Session Scope.
    - Everyone in the app has access to the Context Attributes. That means multiple servlets. And multiple servlets might have multiple threads, since requests are concurrently handled, each in a separate thread. This happens regardless of whether the requests are coming in from the same or different Servlets.
    - In order to make them thread-safe, you need an intrinsic lock on the ServletContext object. Every object has an intrinsic lock associated with it. By convention, a thread that needs exclusive and consistent access to an object's fields has to acquire the object's intrinsic lock before accessing them, and then release the intrinsic lock when it's done with them. A thread is said to own the intrinsic lock between the time it has acquired the lock and released the lock. As long as a thread owns an intrinsic lock, no other thread can acquire the same lock. The other thread will block when it attempts to acquire the lock.
    - This way everyone accessing the context has to first get the lock on the Context object. This ensures that only one thread is setting and getting the context attribute. But remember that this works only if ALL of the other code that manipulates the same context attribute ALSO synchronizes on the ServletContext. If even part of the code doesn't ask for the lock, then that code is free to hit the context attributes.
    //TODO: Why not get a lock just on the variable being changed? Instead of getting a lock on the entire ServletContex?
    //i.e. do: synchronized (this.getServletContext().getAttribute("UserCount")) ?
    Expand Gist Expand Code Snippet
    - Remember that Synchronization causes a lot of overhead and hurts concurrency. Make your synchronized block as small as possible. Get the lock, get in, get what you need, adn get the heckin heck out so that the lock can release and other threads can run that code.
    - Writing Servlet code:
    Thread Safety Tips
    Why is singlethreadmodel deprecated
    So what even is Thread-Safe
    - Only Request Scoped attributes and Local variables are Thread-Safe
    - Everything else is subject ot multi-threaded manipulation unless you do something about it.
    - Everything else includes:
    • Context Scoped Attributes
    • Session Scoped Attributes
    • Instance Variables in the Servlet
    • Static Variables in the Servlet
    - Note that instance variables are not thread-safe. If you have multiple clients making request to the same servlet, that means multiple threads are running that servlet code. And all of those threads have access to the servlet's instance variables. So instance variables are not thread-safe.
    - Can you make instance variables thread-safe: No. You should avoid using instance variables in your code.
    - Then what should you use if you need multiple instances of the Servlet to share something: It's incorrect to say "multiple instances of the Servlet" because there is always just ONE instance of the servlet. One instance. Many threads...
    - If you want all the threads to access a value, decide which attribute state makes the most sense and store the value in that attribute. Chances are you can solve the problem in one of two ways:
    • Declare the variable as a local variable inside the service method, rather than as an instance variable
    • Use an attribute in the most appropriate scope
    What is the use of Request Attributes and Request Dispatching
    - Request attributes make sense when you want some other component of the app to take over all or a part of the request. The controller communicates with the model and gets back the data that the view needs in order to build the response. There is no reason to put the data in a Session or a Context attribute, since it applies only to this request, so we put it in the request scope.
    - So how do we make another part of the component to take over the request - RequestDispatcher
    Expand Gist Expand Code Snippet
    - RequestDispatcher's have only two methods:
    • forward(ServletRequest request, ServletResponse response)
    • include(ServletRequest request, ServletResponse response)
    - You can get a RequestDispatcher in two ways: from the request or from the context. Regardless of where you get it, you ahve to tell it the web component ot which you are forwarding the request.
    RequestDispatcher

    Chapter 6: Session Management - Conversational State

    Web Servers have no short term memory. As soon as they send you a response, they forget who you are. The next time you make a request, they do not recognize you. In other words, they do not remember what you have requested in the past, and they don't remember what they've sent you in response. Nothing. Sometimes, that's fine. But sometimes you need to keep conversational state with the client across multiple requests. A shopping cart would not work if the client had to make all his choices and check out in a single request.
    How do we track the Client's requests over multiple sessions
    - The objective is to store all the choices that have been made by the Client over multiple requests. There are 3 ways in which this can be accomplished:
    • Use a stateful session enterprise java bean: Make your servlet become a Client to a stateful session bean, and each time a request comes in we locate that Client's stateful bean. Remember that for doing this you hosting provider should have full J2EE server with an EJB Container. Tomcat is just a web container, not a full J2EE container.
    • Use a Database: Have your hosting provider communicate with a database, like MySQL. Then all the client's data can be written to or read from the database. The downside is that it is extremely expensive to do this.
    • Use an HttpSession: We can use an HttpSession to hold the conversational state over multiple requests - i.e for the entire session with the user.
    How does the container know who the Client is
    - The HTTP Protocol is a Stateless Protocol. This means that the connection between the Client and the Container exists for a single request/response. The Container does not recognize that the Client making the second request is the same Client from a previous request. As far as the Container is concerned, each request is from a new Client.
    - The Container solves this problem by assigning a unique SessionID to each user.
    - On the Client's first request, the Container generates a unique session ID and gives it back to the Client with the response. The Client then sends back the session ID with each subsequent request. The Container sees the ID, finds the matching session, and associates the session with the request.
    - Attributes bound into a session are available to any other servlets that belong to the same ServletContext and handles a request identified as being a part of the same session.
    Sessions_Flowchart
    How do the Client and the Container exchange the SessionID info
    - The Container uses Cookies to do this.
    - All you have to do is tell the Container that you want to create or use a Session. The Container takes care of the rest. The Container generates the SessionID, creates a new Cookie object, stuffs the SessionID into the Cookie object, sets the Cookie as a part of the response. On subsequent requests, the Container gets the SessionID from the Cookie in the request, matches the SessionID with an existing session, and associates that session with the current request.
    - The HttpSession session = request.getSession() does the following:
    if(the request contains the SessionID object)
    find the Session matching that ID
    else if (there is no SessionID Cookie OR there is no session matching the current SessionID)
    create a new session
    How to check if the Session already exists
    - The no-args HttpSession session = request.getSession() method returns a session regardless of whether there is a pre-existing session or not. You can check if it is a new session by using session.isNew() method.
    - HttpSession session = request.getSession(false) will return null if there is no pre-existing session for the Client. You can use it if you have a scenario in which the servlet wants to use only a previously created session.
    - There are couple of points that you were confused about that need to be clarified:
    - You can check the cookies that are stored in the browser on Chrome - Inspect - Application - Cookies
    Here you will see the Cookies with the name JSESSION ID. This is the same id as the sessionId. While testing, if you see your app behaving abnormally (session seems to be behaving weirdly), first clear the cookies in your browser (Ctrl + Shift + Del) and then retry. If that does not work, go into your app and by inspecting elements, manually delete the cookies.
    - Note that a sessionId is assigned to you the moment you first log in into the website. In the dummy example that we had, the first page that the user was reaching was a index page. The doGet method was activated only when the user clicked a button on the index page to get the form. The point is that, line 4 of the below code will always contain a valid session.
    - Check this SO Post explaining things.
    - So in order to kill that session, we first call session.invalidate. Remember that this will not set the session to null as explained here in SO. So we get the session again, as on Line 8. This time the Container does not find any existing sessions and the session variable is in fact null. When we run the code, now, the if (session == null) block is executed.
    Expand Gist Expand Code Snippet
    What if the Client has disabled Cookies
    - If the Client does not use Cookies, you can use URL rewriting as a backup. URL rewriting allows the sessionID to be added to the end of the URL (instead of being sent as a Cookie).
    - URL rewriting kicks in only if cookies fail and you have explicitly encoded your URLs.
    - Read up on the encodeURL method
    - When a Container sees a call to getSession, and the Container does not have the SessionID associated with the Client's request, the Container knows that it must attempt to set up a new session with the Client. At this point the Container does not know whether the Cookies will work or not. Hence for the first response back to the Client, the Container tries both, Cookies and URL Rewriting.
    What are the key HttpSession methods
    HttpSessionMethods
    How does a Container know when it is safe to destroy Sessions
    - There are 3 ways that a Session can die:
    • It times out
    • You call invalidate() on the Session object
    • The application goes down or crashes

    a) Setting Session Timeout: There are two ways to set the session timeout
    • Setting Session Time out for a specific session: Use this if you want to change the session-timout value for a particular session instance without affecting the timeout length for any other sessions in the app.
      session.setMaxInactiveInterval(20*60)
      Only the session on which you call the method will be affected. Note that the argument to the method is in seconds.
    • Configuring Session Timeout in the DD: This has the same effect as calling setMaxInactiveInterval() on every session that is created.
      Expand Gist Expand Code Snippet
    b) Calling invalidate(): Invalidates this session then unbinds any objects bound to it. Like we discussed earlier, calling this method will not set the session object to null.
    invalidate_session
    //TODO: Why isn't the session invalidated in the second case? I can still get and print the values of the attributes. Why?
    Can I use the Cookie for things other than maintaining Sessions
    - Yes. Remember that the cookie is nothing more than a little piece of data (name/value) pair that is exchanged between the Client and the server. The Server sends the Cookie to the Client and the Client returns the cookie to the Server when teh Client has to make a new request to the Server.
    - By default, a Cookie lives only as long as the session. Once the client quits his browser, the cookie disappears. That's how the JSESSION cookie works. But you can tell a cookie to stay alive even AFTER the browser shuts down. These types of cookies are known as Persistent Cookies.
    How to use Cookies with the Servlet API
    - This is probably a convoluted example, but stick through it. First the JSP page. Note that there is no getCookie(String) method. You can only get Cookies in a Cookie array and then you have to loop over the array to find the one you want.
    Expand Gist Expand Code Snippet
    And then the Servlet class:
    Expand Gist Expand Code Snippet
    What kinds of listeners are we dealing with
    invalidate_session
    What is Session Migration
    - In a clustered environment, the Container might do load-balancing by taking client requests and sending them out JVMs. The JVMs themselves may or may not be on the same physical boxes, that is immaterial. The point is that the web app is in multiple places. This means that each time the same Client makes a request, the request could end up going to a different instance of the same servlet.
    - The question is: how does the Container manage the ServletConfig, ServletContext, and HttpSession objects in this case.
    - Only HttpSession objects (and their attributes) move from one VM to another.
    - There is one ServletContext per VM. There is one ServletConfig per Servlet, per VM. But there is only one HttpSession object for a given SessionId per web app, regardless of how many VM's the app is distributed across.
    - The key point here is that while the other parts of the app are replicated on each node/VM, the session objects (along with the session attributes) are moved.
    DistributedSessions
    SessionMigration
    //TODO: This is followed by something related to SessionListeners.
    HttpSessionActivationListener
    HttpSessionAttributeListener
    HttpSessionAttributeListener

    Chapter 7: Using JSP - Being a JSP

    The most important point for this chapter is simply: what role does the JSP place in the final servlet class? In other words, where do the elements in the JSP end up in the source code of the generated servlet?
    In the end a JSP is just a Servlet
    - In the end, your JSP becomes a full-fledged servlet running in your web-app. The only difference is that the servlet class is written for you by the Container. The Container takes what you have written in your JSP, translates it into a servlet class source (.java) file, then compiles that into a java servlet class. After that it all behaves just like a normal servlet class, i.e the Container loads the Servlet class, instantiates and initializes it, makes a separate thread for each request and calls the servlet's service() method.
    - When you deploy a web app witha JSP, the whole translation and compilation step happens only once in the JSP's life. Once it has been translated and compiled, it is just like any other servlet. And just like any other servlet, once that servlet has been loaded and initialized, the only thing that happens at request time is creation or allocation of a thread for the service method. So the above picture is only for the very first request that the container has to handle.
    CompilationOfServlet
    How to import packages into JSP
    - A directive is a way for you to give special instructions to the Container at page translation time.
    - Directives come in three flavors:
    • page
    • include
    • taglib
    - For importing packages into the JSP, we will use the page directive.
    - Importing a single package can be done as follows: <%@ page import = "java.util.List" %>. Notice that there is no semicolon at the end of the import statement.
    - Importing a multiple packages can be done as follows: <%@ page import = "java.util.List,java.util.Map"%>. Note that packages are separated by comma and the quotes go around the entire list of packages.
    3 JSP element types
    - We can now introduce 3 different JSP element types:
    • Scriptlet <% %> : Between these tags goes the java code that you want to write in the JSP page.
      So we can write <% out.println(Counter.getCount()); %>.
    • Directive <%@ %> : used for writing import statements, among other things, in the JSP. No semi-colon at the end.
    • Expression <%= >: it automatically prints out whatever you put between the tags. This is meant as a replacement for out.println in JSP. So, instead of writing, say, <% out.println(Counter.getCount()); %>, we would just write <%= Counter.getCount() %>. Note that the expression does not need a semicolon at the end either. A n expression cannot use a method that does not have a return type, i.e has void as return type because then there won't be anything to print.
    - In case you are wondering, the object out in the above example is passed implicitly to your JSP page, just in case you want to pass it to some other object that does not have direct access to the output stream for the response.
    What really happens to your JSP Code
    - Let's see where the different JSP elements land in the servlet's class file:
    CompilationOfServlet
    - All scriptlet and expression code lands in a service method. That means that variables declared in a scriptlet are ALWAYS local variables.
    - Also note that the code from the JSP is placed inside the _jspService method that takes as argument the HttpServletRequest request object. Hence you wan write your JSP assuming that it is going to be a part of a servlet. This is also an example of "implicit" object. Something that we see in the next paragraph.
    How do we declare instance variables in a JSP
    - There is another JSP element known as a declaration: for example <%! int count = 0;%>.
    - Note that this requires a semicolon at the end. JSP declarations are for declaring members of the generated servlet class. This means, both, variables and methods. In other words, anything between the <%! %> tag is added to the class outside the service method. That means that you can declare, both, static variables (what?) and methods.
    JSP2Servlet_Decalrations
    What implicit objects are passed to the JSP
    API Implicit Object
    JspWriter out
    HttpServletRequest request
    HttpServletResponse response
    HttpSession session
    ServletContext application
    ServletConfig config
    Throwable exception
    PageContext pageContext
    Object page
    - We were already familiar with the 3 scopes: request, session, and application. This introduces another scope known as the pageContext.
    - A pageContext encapsulates the other implicit objects. This way if you give some other helper object a reference to the PageContext, the helper can use that reference to get all the OTHER implicit object and attributes from all the scopes.
    Everything in one place
    JSP Element Usage What is it used for Usage Example
    Scriptlet <% ;%> Used to write Java Code <% out.println(Counter.getCount()); %>
    Directive <%@ %> Used for writing import statements <%@ page import = "java.util.List" %>
    Expression <%= %> Printing out stuff <%= Counter.getCount() %>
    Declaration <%! ;%> Declaring methods and instance variables in the JSP <%! int count = 0;%>
    ExpressionLanguages ${ } Invokes Java Code ${applicationScope.mail}
    Actions <jsp: />, <c: /> They are 2 types: standarad and other
    Scope In a Servlet In a JSP (using implicit objects)
    Application/Context getServletContext.setAttribute("foo", barObject) application.setAttribute("foo", barObject)
    Request request.setAttribute("foo", barObject) request.setAttribute("foo", barObject)
    Session request.getSession().setAttribute("foo", barObject) session.setAttribute("foo", barObject)
    Page Does not apply pageContext.setAttribute("foo", barObject)
    - Comments can be added either using:
    • //Your comment : in a scriptlet or a declaration. However, outside of this the string "//" would just be parsed like normal HTML comment and you would see your comment printed on the page
    • <!-- HTML Comment -->: Use this if you want the comments to stay as a part of the HTML response to the Client
    • <%-- JSP Comment --%>: Comments will be hidden. They are stripped off when the JSP is converted into Java.
    Now that you know how to write java code in JSP, never do it
    - Java code in JSP is considered hard to change and maintain.
    - Instead we make use of Expression Language or EL. The purpose of EL is to offer a simeple way to invoke Java code - but the code itself belongs somewhere else. That means in a regular old Java class that's either a JavaBean, a class with static methods, or something called a Taghandler.
    - In other words you do not write method code into your JSP. You write the Java methods somewhere else and call it using EL.
    - You can use <scripting-invalid> true </scripting-invalid> to disable scripting elements for ALL JSPs. There is a specific format for this. Refer text.
    //TODO: Complete the exercises and the Coffee Cram questions from this Chapter.

    Chapter 8: Scriptless JSP - Script-free pages


    Servlet and JSP : A Tutorial Kurniawan, Budi

    Interesting Links
    Chapter -1: Tomcat
    Chapter 0: Introduction
    Chapter 1: Servlets


    Interesting Links
    - How Browsers Work
    - Proxy, reverse proxy, and HTTP Tunneling

    Chapter -1: Tomcat

    Downloading and Configuring Tomcat
    - In the bin directory, you will find programs to start and stop Tomcat. The webapps directory is important because you can deploy your applications there. In addition, the conf directory contains configuration files, including the server.xml and tomcat-users.xml files. The lib directory is also of interest since it contains the Servlet and JSP APIs that you need to compile your servlets and custom tags.
    - Once you've downloaded and extracted a Tomcat binary, you can start Tomcat by running the startup.bat (on Windows) or the startup.sh file (on Unix/Linux/Mac OS). Both files reside under the bin directory of Tomcat's installation directory. By default, Tomcat runs on port 8080, so you can test Tomcat by directing your browser to this address: http://localhost:8080
    Defining a Context
    - More information on the Context can be found here on the Tomcat docs. Good read. Go through the Host section under Containers as well. That is relevant too.
    - To deploy a servlet/JSP application to Tomcat, you need to define a Tomcat context either explicitly or implicitly. Each Tomcat context represents a web application in Tomcat.
    - There are several ways of defining a Tomcat context explicitly, including:
    a) Creating an XML file in Tomcat's conf/Catalina/localhost directory: If you decide to create an XML file for each context, the file name is important as the context path is derived from it. For example, if you place a commerce.xml file in the conf/Catalina/localhost directory, the context path of your application will be commerce and a resource can be invoked using this URL: http://localhost:8080/commerce/resourceName.
    - A context file must contain a Context element as its root element. Most of the times the element does not have child elements and is the only element in the file. For example, here is an example context file, consisting of a single line: <Context docBase="C:/apps/commerce" reloadable="true"/>. The only required attribute is docBase, which specifies the location of the application. The reloadable attribute is optional, but if it is present and its value is set to true, Tomcat will monitor the application for any addition, deletion, or update of a Java class file and other resources. When such a change is detected, Tomcat will reload the application. Setting reloadable to true is recommended during development but not in production. When you add a context file to the specified directory, Tomcat will automatically load the application. When you delete it, Tomcat will unload the application.
    b) Adding a Context element in Tomcat's conf/server.xml file: Another way of defining a context is by adding a Context element in the conf/server.xml file. To do this, open the file and create a Context element under the Host element. Unlike the previous method, defining a context here requires that you specify the path attribute for your context path.
    Expand Gist Expand Code Snippet
    - Generally, managing contexts through server.xml is not recommended as updates will only take effect after you restart Tomcat. However, if you have a bunch of applications that you need to test quickly, like when you are learning to write servlets and JSP pages, you may find working with server.xml almost ideal as you can manage all your applications in a single file.
    - We looked at two ways to deploy an application explicitly, but we can also deploy it implicitly. You can do it by by copying a war file or the whole application to Tomcat's webapps directory.

    Chapter 0: Introduction

    Introduction
    - Java Servlet technology, or Servlet for short, is the underlying technology for developing web applications in Java. Sun Microsystems released it in 1996 to compete with the Common Gateway Interface (CGI), the then standard for generating dynamic content on the web. The main problem with the CGI was the fact that it spawned a new process for every HTTP request. This made it difficult to write scalable CGI programs because creating a process took a lot of CPU cycles. A servlet, on the other hand, is much faster than a CGI program because a servlet stays in memory after serving its first request, waiting for subsequent requests.
    - Servlets are Java classes that run on a servlet container. A servlet container or servlet engine is like a web server but has the ability to generate dynamic contents, not only serve static resources.
    Servlet/JSP Application Architecture
    - A servlet is a Java program. A servlet application consists of one or more servlets. A JSP page is translated and compiled into a servlet.
    - A servlet application runs inside a servlet container and cannot run on its own. A servlet container passes requests from the user to the servlet application and responses from the servlet application back to the user. Most servlet applications include at least several JSP pages. As such, it's more appropriate to use the term "servlet/JSP application" to refer to a Java web application than to leave JSP out.
    Show Image Show Image Button
    Servlet_JSP_Application_Architecture
    - The web server and the web client communicate in a language they both are fluent in: the Hypertext Transfer Protocol (HTTP). Because of this, a web server is also called an HTTP server.
    - A servlet/JSP container is a special web server that can process servlets as well as serve static contents. In the past, people were more comfortable running a servlet/JSP container as a module of an HTTP server such as the Apache HTTP Server because an HTTP server was considered more robust than a servlet/JSP container. In this scenario the servlet/JSP container would be tasked with generating dynamic contents and the HTTP server with serving static resources. Today servlet/JSP containers are considered mature and widely deployed without an HTTP server. Apache Tomcat and Jetty are the most popular servlet/JSP containers and are free and open-source.
    - Servlet and JSP are two of a multitude of technologies defined in the Java Enterprise Edition (EE). Other Java EE technologies include Java Message Service (JMS), Enterprise JavaBeans (EJB), JavaServer Faces (JSF), and Java Persistence. The complete list of technologies in the Java EE version 6 (the current version) can be found here.
    - To run a Java EE application, you need a Java EE container, such as GlassFish, JBoss, Oracle WebLogic, and IBM WebSphere. You can deploy a servlet/JSP application in a Java EE container, but a servlet/JSP container is sufficient and is more lightweight than a Java EE container. Tomcat and Jetty are not Java EE containers, so they cannot run EJB or JMS.
    The Hypertext Transfer Protocol (HTTP)
    - The HTTP protocol enables web servers and browsers to exchange data over the Internet or an intranet. In HTTP, it is always the client that initiates a connection, a server is never in a position to contact a client. To locate a resource, an Internet user clicks a link that contains a Uniform Resource Locator (URL) or enter one in the Location box of the browser. For instance, this is a URL: http://google.com/index.html. The first part of the URLs is http, which identifies the protocol. Not all URLs use HTTP. For instance, these two URLs are valid even though they are not HTTP-based URLs: mailto:joe@example.com, ftp://marketing@ftp.example.org.
    - In general, a URL has this format: protocol://[host.]domain[:port][/context][/resource][?query string] or protocol://IP address[:port][/context][/resource][?query string]. The parts in square brackets are optional.
    - Both of these are valid URLs: http://yahoo.ca or http://192.168.1.9. You can find the IP address by doing ping google.com. For an IPv6 address, you need to wrap it inside a square bracket as explained here. Note that you need to have IPv6 working on your OS, and every device in the path to the destination (including proxy servers if you use one).
    - Also note this as explained here: An IP address is not necessarily unique to a specific Web site. For many years Web providers have been using the HTTP 1.1 Host header to distinguish web sites and serve multiple web sites from a single IP address. Your web browser sends a Host header to the Web server telling it the domain name of the site you requested, and the server responds with the correct page. If you give an IP address only, the server has no way to determine which site (among the possibly many behind the IP address) you want. In this situation some sites return a generic page, and some return an error code to the browser.
    - The host part may be present and identify a totally different location on the Internet or an intranet. For instance, http://yahoo.com (no host) brings you to a different location than http://mail.yahoo.com (with a host). Over the years www has been the most popular host name and become the default. Normally, http://www.domainName is mapped to http://domainName.
    - 80 is the default port of HTTP. Therefore, if a web server runs on port 80, you don't need the port number to reach the server. 443 is the default port for HTTPS. Sometimes, however, a web server doesn't run on port 80 and you need to type the port number. For example, Tomcat by default runs on port 8080, so you need to supply the port number: http://localhost:8080. localhost is a reserved name typically used to refer to the local computer, i.e. the same computer the web browser is running on.
    - We also have absolute and relative URLs. In your browser's address bar, a URL doesn't have any context, so you must provide a full (or absolute) URL, like the ones we saw above. You don't need to include the protocol (the browser uses HTTP by default) or the port (which is only required when the targeted Web server is using some unusual port), but all the other parts of the URL are necessary. But when a URL is used within a document, such as in an HTML page, things are a bit different. Because the browser already has the document's own URL, it can use this information to fill in the missing parts of any URL available inside that document. We can differentiate between an absolute URL and a relative URL by looking only at the path part of the URL. If the path part of the URL starts with the / character, the browser will fetch that resource from the top root of the server, without reference to the context given by the current document. This is the most common use case for an absolute URL within an HTML document. The browser will use the same protocol and the same domain name as the one used to load the document hosting that URL. Look at examples here on MDN.
    - The context part in a URL refers to the application name, but this is also optional. A web server can run multiple contexts (applications) and one of them can be configured to be the default context. To request a resource in the default context, you skip the context part in a URL. A context can have one or more default resources (ordinarily index.html or index.htm or default.htm). A URL without a resource name is considered to identify a default resource. Of course, if more than one default resource exists in a context, the one with the highest priority will always be returned when a client does not specify a resource name.
    - After a resource name comes one or more query string. A query string is a key/value pair that can be passed to the server to be processed.
    HTTP Request
    - An HTTP request consists of three components:
    a) Method-Uniform Resource Identifier (URI)-Protocol/Version
    b) Request headers
    c) Entity body
    - This is what a sample HTTP request looks like:
    Show Image Show Image Button
    HTTP_Request
    - The Method-Uniform Resource Identifier (URI)-Protocol/Version appears as the first line of the request. Here POST is the request method, /examples/default.jsp the URI, and HTTP/1.1 the Protocol/Version section. An HTTP request can use one of the many request methods specified in the HTTP standards. HTTP 1.1 supports seven request types: GET, POST, HEAD, OPTIONS, PUT, DELETE, and TRACE. The URI specifies an Internet resource. It is usually interpreted as being relative to the server's root directory. Thus, it should always begin with a forward slash / .
    - In an HTTP request, the request header contains useful information about the client environment and the entity body of the request. For instance, it may contain the language the browser is set for, the length of the entity body, and so on. Each header is separated by a carriage return/linefeed (CRLF) sequence. Between the headers and the entity body is a blank line (CRLF) that is important to the HTTP request format. The CRLF tells the HTTP server where the entity body begins. In some Internet programming books, this CRLF is considered the fourth component of an HTTP request. In the previous HTTP request, the entity body is simply the following line: lastName=Blanks&firstName=Mike
    HTTP Response
    - Similar to an HTTP request, an HTTP response also consists of three parts:
    a) Protocol-Status code-Description
    b) Response headers
    c) Entity body
    Show Image Show Image Button
    HTTP_Request
    - The first line of the response header is similar to the first line of the request header. It tells you that the protocol used is HTTP version 1.1, and that the request succeeded (200 is the success code). The response headers contain useful information similar to the headers in an HTTP request. The entity body of the response is the HTML content of the response itself. The headers and the entity body are separated by a sequence of CRLFs.

    Chapter 1: Servlets

    The javax.servlet Package
    - Contains classes and interfaces that define the contract between a servlet and a servlet container.
    Show Image Show Image Button
    HTTP_Request
    - At the center of Servlet technology is Servlet, an interface that all servlet classes must implement either directly or indirectly.
    - The Servlet interface defines a contract between a servlet and the servlet container. The contract boils down to the promise by the servlet container to load the servlet class into memory and call specific methods on the servlet instance. There can only be one instance for each servlet type in an application.
    - A user request causes the servlet container to call a servlet's service method, passing an instance of ServletRequest and an instance of ServletResponse. The ServletRequest encapsulates the current HTTP request so that servlet developers do not have to parse and manipulate raw HTTP data. The ServletResponse represents the HTTP response for the current user and makes it easy to send response back to the user.
    - For each application the servlet container also creates an instance of ServletContext. This object encapsulates the environment details of the context (application). There is only one ServletContext for each context. For each servlet instance, there is also a ServletConfig that encapsulates the servlet configuration.
    The Servlet interface
    - This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence:
    1) The servlet is constructed, then initialized with the init method.
    2) Any calls from clients to the service method are handled.
    3) The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.
    - An important point to note is thread safety. A servlet instance is shared by all users in an application, so class-level variables are not recommended, unless they are read-only or members of the java.util.concurrent.atomic package.
    - The Servlet interface defines the following 5 methods here on the Oracle site:
    a) void init(ServletConfig config) throws ServletException: The servlet container invokes this method the first time the servlet is requested. This method is not called at subsequent requests. You use this method to write initialization code. When invoking this method, the servlet container passes a ServletConfig. Normally, you will assign the ServletConfig to a class level variable so that this object can be used from other points in the servlet class.
    b) void service(ServletRequest req, ServletResponse res) throws ServletException, IOException : The servlet container invokes this method each time the servlet is requested. You write the code that the servlet is supposed to do here. The first time the servlet is requested, the servlet container calls the init method and the service method. For subsequent requests, only service is invoked.
    c) void destroy() : The servlet container invokes this method when the servlet is about to be destroyed. This occurs when the application is unloaded or when the servlet container is being shut down. Normally, you write clean-up code in this method
    d) String getServletInfo() : This method returns the description of the servlet. You can return any string that might be useful or even null.
    e) ServletConfig getServletConfig(): This method returns the ServletConfig passed by the servlet container to the init method. However, in order for getServletConfig to return a non-null value, you must have assigned the ServletConfig passed to the init method to a class level variable.
    Application Directory Structure
    - This is what the application directory is supposed to look like:
    Show Image Show Image Button
    ApplicationDirectory
    - The app01a directory at the top of the structure is the application directory. Under the application directory is a WEB-INF directory. It in turn has two subdirectories:
    a)

    classes

    : Your servlet classes and other Java classes must reside here. The directories under classes reflect the class package. In Figure 1.2 there is one class deployed, app01a.MyServlet.
    b)

    lib

    : Deploy jar files required by your servlet application here. The Servlet API jar file does not need to be deployed here because the servlet container already has a copy of it. In this application, the lib directory is empty. An empty lib directory may be deleted.
    - Any resource you put under the application directory is directly accessible to the user by typing the URL to the resource. If you want to include a resource that can be accessed by a servlet but not accessible to the user, put it under WEB-INF.
    - The directory name is also important because this also appears in the URL to your servlet. See the URL that we are using to access the site below. In Intellij, this project name forms a part of the "Application Context". Go to Run - Edit Configurations - Deployment. There you will see the Application Context field. In your webapp, when you do servletRequest.getContextPath(), it is the value of this "Application Context" that will be returned.
    - The recommended method for deploying a servlet/JSP application is to deploy it as a war file. A war file is a jar file with war extension. You can create a war file using the jar program that comes with the JDK or tools like WinZip. You can then copy the war file to Tomcat's webapps directory. When you start or restart Tomcat, Tomcat will extract the war file automatically. Deployment as a war file will work in all servlet containers.
    - Note that Servlet 3.0 onwards, they have started using the @WebServlet(name = "WelcomeServlet", urlPatterns = {"/welcome"}) annotation instead of writing this configuration in the web.xml file. You would access this link by doing http://localhost:8080/app01a/welcome.
    ServletRequest
    - ServletRequest docs.
    - For every HTTP request, the servlet container creates an instance of ServletRequest and passes it to the servlet's service method. The ServletRequest encapsulates information about the request.
    - getParameter(String name) is the most frequently used method in ServletRequest. A common use of this method is to return the value of an HTML form field. getParameter can also be used to get the value of a query string. For example, if a servlet is invoked using this URI http://domain/context/servletName?id=123, you can retrieve the value of id from inside your servlet using this statement: String id = request.getParameter("id");. Note that getParameter returns null if the parameter does not exist.
    ServletResponse
    - ServletResponse docs.
    - Prior to invoking a servlet's service method, the servlet container creates a ServletResponse and pass it as the second argument to the service method. The ServletResponse hides the complexity of sending response to the browser.
    - One of the methods defined in ServletResponse is the getWriter method, which returns a java.io.PrintWriter that can send text to the client. There is also another method that you can use to send output to the browser: getOutputStream. However, this method is for sending binary data.
    - Before sending any HTML tag, you should set the content type of the response by calling the setContentType method, passing "text/html" as an argument. This is how you tell the browser that the content type is HTML. Most browsers by default render a response as HTML in the absence of a content type.
    ServletConfig
    - ServletConfig docs.
    - The servlet container passes a ServletConfig to the servlet's init method when the servlet container initializes the servlet. The ServletConfig encapsulates configuration information that you can pass to a servlet through @WebServlet or the deployment descriptor. Every piece of information so passed is called an initial parameter. An initial parameter has two components: key and value.
    - To retrieve the value of an initial parameter from inside a servlet, call the getInitParameter method on the ServletConfig passed by the servlet container to the servlet's init method.
    Expand Gist Expand Code Snippet
    - Alternatively, instead of using the annotations, you can do the setup using the deployment descriptor, ie. web.xml file. Utilizing the deployment descriptor for this purpose is easier than using @WebServlet since the deployment descriptor is a text file and you can edit it without recompiling the servlet class. The deployment descriptor also allows you to override values specified in a servlet annotation.
    Expand Gist Expand Code Snippet
    ServletContext
    - ServletContext docs.
    - The ServletContext represents the servlet application. There is only one context per web application. In a distributed environment where an application is deployed simultaneously to multiple containers, there is one ServletContext object per Java Virtual Machine. In this situation, the context cannot be used as a location to share global information (because the information won't be truly global). Use an external resource like a database instead.
    - The ServletContext is there so that you can share information that can be accessed from all resources in the application and to enable dynamic registration of web objects. The former is done by storing objects in an internal Map within the ServletContext. Objects stored in ServletContext are called attributes.
    GenericServlet
    - GenericServlet docs.
    - In the above example, we saw how implementing the Servlet interface caused us to implement all the 5 methods defined on the interface even if we did not have the need for all of them. In its place, we can extend the GenericServlet which provides default implementations of the methods except the service method.
    - GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet may be directly extended by a servlet, although it's more common to extend a protocol-specific subclass such as HttpServlet. It also assigns the ServletConfig in the init method to a class level variable so that it can be retrieved by calling getServletConfig.
    Expand Gist Expand Code Snippet
    HTTP Servlets
    - Most, if not all, servlet applications you write will work with HTTP. This means, you can make use of the features offered by HTTP.
    Show Image Show Image Button
    ApplicationDirectory
    HttpServlet
    - HttpServlet docs.
    - The HttpServlet class extends the GenericServlet class. The HttpServletRequest interface extends ServletRequest and HttpServletResponse extends ServletResponse.HttpServlet overrides the service method in GenericServlet and adds another service method with the following signature: protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException.
    - To summarize, there are two features in HttpServlet that you do not find in GenericServlet:
    a) Instead of the service method, you will override doGet, doPost, or both of them. In rare cases, you will also override any of these methods: doHead, doPut, doTrace, doOptions, doDelete.
    b) You will work with HttpServletRequest and HttpServletResponse, instead of ServletRequest and ServletResponse.
    HttpServletRequest
    - HttpServletRequest Docs.
    - HttpServletRequest represents the servlet request in the HTTP environment. It extends the ServletRequest interface and adds several methods. Some methods added are as follows:
    a) String getContextPath(): Returns the portion of the request URI that indicates the context of the request.
    b) Cookie[] getCookies(): Returns an array containing all the Cookie objects the client sent with this request. This method returns null if no cookies were sent.
    c) String getHeader(String name): Returns the value of the specified request header as a String. If the request did not include a header of the specified name, this method returns null. If there are multiple headers with the same name, this method returns the first header in the request. The header name is case-insensitive. You can use this method with any request header.
    d) String getMethod(): Returns the name of the HTTP method with which this request was made, for example, GET, POST, or PUT.
    e) String getQueryString(): Returns the query string that is contained in the request URL after the path. This method returns null if the URL does not have a query string. For instance, if this is the URL: http://localhost:8080/ServletsTutorial/QueryStringExample?firstName=Java&lastName=InterviewPoint, then the value returned by this method will be firstName=Java&lastName=InterviewPoint.
    f) HttpSession getSession(): Returns the current session associated with this request, or if the request does not have a session, creates one.
    g) HttpSession getSession(boolean create): Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session. If create is false and the request has no valid HttpSession, this method returns null.
    HttpServletResponse
    - HttpServletResponse docs.
    - Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies. Here are some of the methods defined in it:
    a) void addCookie(Cookie cookie): Adds the specified cookie to the response. This method can be called multiple times to set more than one cookie.
    b) void addHeader(String name, String value): Adds a response header with the given name and value. This method allows response headers to have multiple values.
    c) void sendRedirect(String location): Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer. The buffer will be replaced with the data set by this method. Calling this method sets the status code to SC_FOUND 302 (Found). This method can accept relative URLs; the servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading '/' the container interprets it as relative to the current request URI. If the location is relative with a leading '/' the container interprets it as relative to the servlet container root. If the location is relative with two leading '/' the container interprets it as a network-path reference.
    Working with HTML Forms
    - Input: The value of an HTML input field (a text field, a hidden field, or a password field) or text area is sent to the server as a string. An empty input field or text area sends an empty string. As such, ServletRequest.getParameter that takes an input field name never returns null.
    - Select: An HTML select element also sends a string to the server. If none of the options in the select element is selected, the value of the option that is displayed is sent. A multiple-value select element (a select element that allows multiple selection and is indicated by <select multiple>) sends a string array and has to be handled by ServletRequest.getParameterValues().
    - Checkbox: A checkbox is a bit extraordinary. A checked checkbox sends the string "on" to the server. An unchecked checkbox sends nothing to the server and ServletRequest.getParameter(fieldName) returns null. Note that by "nothing" we mean that there will be no parameter in the HttpServletRequest that will correspond to the name attribute of the checkbox. Hence, doing ServletRequest.getParameter(fieldName) returns null. - Radio Buttons: Radio buttons send the value of the selected button to the server. If none of the buttons is selected, nothing is sent to the server and ServletRequest.getParameter(fieldName) returns null. Similar to the above case, by "nothing is sent to the server", we mean that there will be no parameter in the HttpServletRequest that will correspond to the name attribute of the radio button.
    - If a form contains multiple input elements with the same name, all values will be submitted and you have to use ServletRequest.getParameterValues() to retrieve them. ServletRequest.getParameter() will only return the last value.
    - Below is the form that we are discussing in the above example:
    Expand Gist Expand Code Snippet
    - Note that refreshing the page that is sent back as the response once you click on "Submit" on the form causes the form to be resubmitted. You can avoid this by doing the Post/Redirect/Get pattern as has been described in this SO Question: How to prevent form resubmission when page is refreshed (F5 / CTRL+R). There are some other ways described in there as well where you directly manipulate the history object of the browser. Why does doing this solve the problem? Read this comment on "Prevent Back button from showing POST confirmation alert" to find out. Suppose your browser GETs page A, which has a POST form on it. Your browser history has GET A in it. You post the form to B, and are redirected to GET C. You browser history now has GET A, GET C in it. It should not record POST B as browsers should not record the page in the history if it gets a 303 redirect. Now when you refresh the page, browser will do GET C. Even if you press the "Back" button on C, you will end up on A. Hence the form should not be resubmitted in this case, and no warning should appear either. In the above gist, you can see the commented out code snippet in order to see how to send a redirect. Note the path that we are using. It does not start with a "/".
    - Another SO Question: Stop data inserting into a database twice and Preventing form resubmission on the same topic.

    Chapter 2: Session Management

    The javax.servlet Package
    -