Servlets

SERVLETS

import javax.servlet.*;
import javax.servlet.http.*
public class TestServlet extends HttpServlet/GenericServlet throws IOException{

public void init();//instance methods derived from GenericServlet

public void init(ServletConfig);//instance methods derived from GenericServlet

public void service();//instance methods derived from GenericServlet

public void destroy();//instance methods derived from GenericServlet
}

GenericServlet is not specific to any protocol.
HttpServlet class is specific to http protocol which is derived from GenericServlet.
The JVM creates an instance of the Servlet by using Reflection using:
servletClass.newInstance()
and then calls the lifecyle methods.
init method can be executed on the first request or on the deployment time. This is configured from the WebServer.
destroy gets executed when the Servlet has not been accessed

SSI – Server Side Includes. These are .shtml file which are supported starting with Servlet 1.0. The SSI defines shtml file with content of html +

servlet tag. In the servlet tag, you have a code attribute which takes the name of the servlet.
<html>
.
.
<servlet code=”HelloServlet” >
<param name=”n1″ value=”v1″ />
</servlet>
.
.
</html>

The output of the servlet is included in the html.  All the servers don’t support html.  In that case only text content is displayed. Not used often.

Servlet Chaining – Not part of Servlet Specification. Supported by JRun and Java Web Server, not all web servers. The servlets have to be

configured in the server. Servlets are executed in a sequence using aliases. Eg. http://localhost:8080/App/chain. The last servlet in the chain will

give the output to the client. The output of one servlet becomes the input to the next servlet in the chain but the last servlet will give the input to the

client. The benefit of Servlet chaining is filtering. Eg. Put out.println() in one servlet, the next servlet will pick it up and get the input to this

out.println and convert it to some other language; so it can be used for internalization.

Servlet Collaboration : Introduced in Servlet Spec 2.1
This is programmatically done. You have an instance called requestDispatcher. It comes from ServletContext interface. To the rq, pass the URI

and not the URL. The URL consists of protocol+domainName+portNumber+applicationName+path where as URI is only the path. You can use

rq to include or forward.  URI always begins with a slash. Dispatch to any servlet or page that belongs to the same context page.

Eg.
ServletContext context = getServletContext();
RequestDispatcher rq = context.getRequestDispatcher(/Servlet/s2);
rq.setAttribute(“name”,object);

rq.setAttribute(“test”,”1″) and request parameter “test” that comes from the client are two different variables because you get one with the

rq.getAttribute and the other with the rq.getParameter. However, if you have request with the same parameter names, it depends on the server

how it implements it. It might take the last parameter or get the parametrs as a String array.

rq.include(request,response)
rq.forward(request,response);

include – inlining servlet.  When include is called during runtime the specified servlet s2 will get invoked. It comes back to the caller Servlet and

executes the contents of the caller Servlet. Output from S1 and S2 will be embedded.  The control comes back to the caller servlet.

forward – forwarding servlet. The control never comes back to the calling servlet. You cannot have out.println() before the forward. Only last

servlet in the forward will give the output to the client.

Reditrecting Servlets (Send Redirect): Generally used when the page is changed and you want to direct to a new page.
Eg.
response.setRedirect(URL);
It is a URL and not a URI. It is not an error if you do out.println() before sendRedirect but you won’t see the output because it is quick. In

sendRedirect the header properties of the client are changed giving it a new location. The code is 302. It is a seperate request from the client

again.

Client Pull: This is similar to sendRedirect but with a timestamp. A meta-tag property httpeqiv=”refresh” content=”10″ url=”url”.
In the Servlet, set the refresh header of the client.
response.setHeader(“Refresh”,10,url);
Because of the refresh with the amount of time, you can have out.println and the client can see the output.
url is optional and it calls the same url again.
Handling Exceptions in Servlet:
1. Use a response.sendError
try{
 //open dbconnection
connection.open()
}catch(SQLException sqe(){
response.sendError(404, “Database Unavailable”);
//OR if you want to send a stacktrace to the client using the ByteArrayOutputStream(it expands by it size automatically)
response.sendError(404, sqle.printStackTrace(PrintWriter object));
//OR
throw new MyServletException(msg)’. In this case have the throws ServletExcetpion in the method definition
}
No statement after response.sendError is executed. The drawback with response.sendError is the error code and message might not match.

2.  Inherit the ServletException or IOException

public class MyServletException extends ServletException{

public MyServletException(String msg){
super(msg);
}
}
Container takes care of forwarding to the appropriate error page defined in the web.xml for the particular error code specified.

3. Logging:
log(sqle.printStackTrace()). This goes in log file configured in the WebServer
Configuring the error page:

<exception>
 <exception-type>MyServletException</exception-type>
 <location>error.html</location>
</exception>

OR

<exception>
 <error-code>404</error-code>
 <location>error.html</location>
</exception>

Servlet Session Tracking:

There are four ways to do session tracking:
1. Hidden Fields :  Form is mandatory to carry across the hidden fields and to get back the requests. These will be matched to check if it is the

same user.
2. URL Rewriting
2.1 QueryString: The query string should always be attached to the url . eg. url?var1=val1&var2=val2.
2.2 ExtraPath Info. http://localhost:8080/MyApp/Servlet/s2 . Along with this addon the data that has to be carried across
http://localhost:8080/MyApp/Servlet/s2/data/data1/data2
2.3 Custom Method. eg. $url?$var=$val
In s2, req.getPathInfo to get the data.

3. Cookies
Information stored at client machine. Cookies contains name, value pair; the domain name; path; time to live for cookie and if it should travel

through http or https. The cookies have restriction from the browser. eg. no. of cookies that can be stored. By default the expiration of cookie is

set to -1. It means it is available until the browser is opened. 0 means cookie is not stored. Cookies get auto deleted once it reaches expiration

time.
 
4. HttpSession
Setting up Tomcat:

1. Set the environment variables:
set catalina_home
set java_home

2. Run Tomcat server by executing catalina_home/bin/startup.cmd

3. Create a web application directory under web apps.

webapps
 -myapp
  htmls
  js
  css
 -WEB-INF
  web.xml
  -classes
Eg. javac -D ../classes/HelloServlet.java
Edit the web.xml specify servlet tag

One Servlet Context is one web application