Saturday, January 23, 2016

Servlets and JSP-1

          I am posting some bullet points on Servlets and JSP's . You can use them to brush up your J2EE basics.

Servlets and JSP:

1.  TCP is responsible for making sure that a file sent from one network node to another ends up as a complete file at the destination, even though the file is split into chunks when it’s sent.
2.  IP is the underlying protocol that moves/routes the chunks (packets) from one host to another on their way to the destination .
3.  HTTP, then, is another network protocol that has Web-specific features, but it depends on TCP/IP to get the complete request and response from one place to another.


HTTP conversation is a simple Request/Response sequence

 Request :
   HTTP Method (Header of each method can contain data such as which browser) , post request has a Request body
   Url
   Parameters
 
 Response:
   Status:
   Content Type
   Content
 
Why POST than GET

 1. Get the amount of data send is limited. - Long search words
 2. The values are exposed in url - Better not send passwords
 3. GET can be bookmarked however POST cannot be .


Servlet extend HTTPServlet and has doGet and doPost methods.



About WEB-INF

A special directory exists within the application hierarchy named  WEB-INF. This directory contains all things related to the application that aren’t in the document root of the application. The  WEB-INF node is not part of the public document tree of the application. No file contained in the WEB-INF directory may be served directly to a client by the container. However, the contents of the WEB-INF directory are visible to servlet code using the getResource and getResourceAsStream method calls on the ServletContext, and may be exposed using the RequestDispatcher calls.



Servlets are not thread safe.  It can be made thread safe by synchronizing service method



A ServletConfig object


One ServletConfig object per servlet.
Use it to pass deploy-time information to the servlet (a database or enterprise bean lookup name, for example) that you don’t want to hard-code into the servlet (servlet init parameters).

Use it to access the ServletContext.

Parameters are configured in the Deployment Descriptor.

A ServletContext

One ServletContext per web app. (They should have named it AppContext.)
Use it to access web app parameters (also configured in the Deployment Descriptor).
Use it as a kind of application bulletin-board, where you can put up messages (called attributes) that other parts of the application can access (way more on this in the next chapter).
Use it to get server info, including the name and version of the Container, and the version of the API that’s supported.







Q: Why would I ever want to get an InputStream from the request?
A:
A: With a GET request, there’s nothing but the request header info. In other words, there’s no body to care about. BUT... with an HTTP POST, there’s body info. Most of the time, all you care about from the body is sucking out the parameter values (for example, “color=dark”) using request.getParameter(), but those values might be large. It is also possible to create a servlet that handles a computer-driven request in which the body of the request holds textual or binary content to be processed. In this case you can use the getReader or getInputStream methods. These streams will only contain the body of the HTTP request and not the headers.



BULLET POINTS

The Container initializes a servlet by loading the class, invoking the servlet’s no-arg constructor, and calling the servlet’s init() method.
The init() method (which the developer can override) is called only once in a servlet’s life, and always before the servlet can service any client requests.
The init() method gives the servlet access to the ServletConfig and ServletContext objects, which the servlet needs to get information about the servlet configuration and the web app.
The Container ends a servlet’s life by calling its destroy() method.
Most of a servlet’s life is spent running a service() method for a client request.
Every request to a servlet runs in a separate thread! There is only one instance of any particular servlet class.
Your servlet will almost always extend javax.servlet.http. HttpServlet, from which it inherits an implementation of the service() method that takes an HttpServletRequest and an HttpServletResponse.
HttpServlet extends javax.servlet.GenericServlet—an abstract class that implements most of the basic servlet methods.
GenericServlet implements the Servlet interface.
Servlet classes (except those related to JSPs) are in one of two packages: javax.servlet or javax.servlet.http.
You can override the init() method, and you must override at least one service method (doGet(), doPost(), etc.).


The HttpServlet’s doGet() and doPost() methods take an HttpServletRequest and an HttpServletResponse.
The service() method determines whether doGet() or doPost() runs based on the HTTP Method (GET, POST, etc.) of the HTTP request.
POST requests have a body; GET requests do not, although GET requests can have request parameters appended to the request URL (sometimes called “the query string”).
GET requests are inherently (according to the HTTP spec) idempotent. They should be able to run multiple times without causing any side effects on the server. GET requests shouldn’t change anything on the server. But you could write a bad, non-idempotent doGet() method.
POST is inherently not idempotent, so it’s up to you to design and code your app in such a way that if the client sends a request twice by mistake, you can handle it.
If an HTML form does not explicitly say “method=POST”, the request is sent as a GET, not a POST. If you do not have a doGet() in your servlet, the request will fail.
You can get parameters from the request with the getParameter(“paramname”) method. The return value is always a String.
If you have multiple parameter values for a given parameter name, use the getParameterValues(“paramname”) method that returns a String array.
You can get other things from the request object including headers, cookies, a session, the query string, and an input stream.



You use the Response to send data back to the client.
The most common methods you’ll call on the response object (HttpServletResponse) are setContentType() and getWriter().
Be careful—many developers assume the method is getPrintWriter(), but it’s getWriter().
The getWriter() method lets you do character I/O to write HTML (or something else) to the stream.
You can also use the response to set headers, send errors, and add cookies.
In the real world, you’ll probably use a JSP to send most HTML responses, but you may still use a response stream to send binary data (like a JAR file, perhaps) to the client.
The method you call on your response for getting a binary stream is getOutputStream().
The setContentType() method tells the browser how to handle the data coming in with the response. Typical content types are “text/html”, “application/pdf”, and “image/jpeg”.
You don’t have to memorize content types (also known as MIME types).
You can set response headers using addHeader() or setHeader(). The difference depends on whether the header is already part of the response. If it is, setHeader() will replace the value, but addHeader will add an additional value to the existing response. If the header is not already part of the response, then setHeader() and addHeader() behave in exactly the same way.
If you don’t want to respond to a request, you can redirect the request to a different URL. The browser takes care of sending the new request to the URL you provide.
To redirect a request, call sendRedirect(aStringURL) on the response.
You cannot call sendRedirect() after the response is committed! In other words, if you’ve already written something to the stream, it’s too late to do a redirect.
A request redirect is different from a request dispatch. A request dispatch (covered more in another chapter) happens on the server, while a redirect happens on the client. A request dispatch hands the request to another component on the server, usually within the same web app. A request redirect simply tells the browser to go a different URL.








Redirect vs RequestDispatcher

Redirect - Client does the work
response.sendRedirect()

RequestDispatcher - Server does the work
RequestDispatcher view = req.getRequestDispatcher("New.jsp");
view.forward(req,res);





You cannot get initParameters in constructor
when you override init you override no-args init.  servlet has two versions of init - init() and init(ServletConfig). Second one calls the first. Hence while overriding init(), You will have ServletConfig.


If we want a parameter through out the application , We use Context-params

-for particular servlet
<init-param>
  <param-name> firstparam </param-name>
  <param-value> firstValue</param-value>
</init-param>
</servlet>

getServletConfig().getInitParameter("foo");


Across application

<context-param>
   <param-name>firstparam</param-name>
   <param-value>firstValue</param-value>
</context-param>

outside servlet tag inside web-app>


getServletContext().getInitParameter("foo");



If the app is distributed, there’s one ServletContext per JVM!


Usecase :
  ServletContext parameters are Strings , But you need to create a DataSource Reference object to be accessible to all the Servlet .  This cannot be done normally. What we need here is a Listener which listens to the Context initialization event.  Which will run on context initialization which happens only once.
 
 
  javax.servlet.ServletContextListener
 
 
  two methods - public void contextInitiallized(ServletContextEvent) ->ServletContextEvent.getServletContext will give you ServletContext.
Having got ServletContext you can set Attribute in that.
 
 


No comments:

Post a Comment