Showing posts with label Servlet. Show all posts
Showing posts with label Servlet. Show all posts

Tuesday, May 1, 2012

Step by step guide to implement Hello world servlet

In this example we will see how to do coding, compiling, deploying, and running a simple Hello World servlet which will just print "Hello World" in the browser.

To learn life cycle of servlet, click here

We will useTomcat server to run our HelloWorld servlet. To download tomcat, click here

Lets create our project folder in webapps lets say TestServlet

Example:
C:\apache-tomcat-7.0.11\webapps\TestServlet

Now lets create our first hello world servlet, lets say HelloWorldServlet.java

HelloWorldServlet.java

C:\apache-tomcat-7.0.11\webapps\TestServlet\WEB-INF\classes\HelloWorldServlet.java
/* HelloWorldServlet.java */

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloWorldServlet extends HttpServlet {
 
 public void doGet(HttpServletRequest request, HttpServletResponse response) {
  doPost(request,response);
 }
 
 public void doPost(HttpServletRequest request, HttpServletResponse response) {
  PrintWriter pw = null;
  try {
   pw = response.getWriter();
  } catch (IOException e) {
   e.printStackTrace();
  }
  pw.println("<html>");
  pw.println("<body>");
  pw.println("<h2>Hello World!!</h2>");
  pw.println("</body>");
  pw.println("</html>");
 }

}

Monday, August 15, 2011

Servlet Life Cycle




1. Loading and instantiating a servlet

When we start up a servlet container, it looks for deployment descriptors (web.xml) which includes an entry for each of the servlets it uses. An entry specifies the name of the servlet and a Java class name for the servlet. The servlet container creates an instance of the given servlet class using the method Class.forName(className).newInstance().


2. Initializing a servlet

Once the container creates the servlet instance, it calls the init(ServletConfig) method on this newly created instance. The ServletConfig object contains all the initialization parameters that we specify in the deployment
descriptor of the web application. The framework guarantees that the servlet container will call the init() method once and only once on a servlet instance.

3. Servicing client requests

After the servlet instance is properly initialized, it is ready to service client requests. When the servlet container receives requests for this servlet, it will dispatch them to the servlet instance by calling the Servlet.service(ServletRequest, ServletResponse) method.

4. Destroying a servlet

If the servlet container decides that it no longer needs a servlet instance, it calls the destroy() method on the servlet instance. Once this method is called, the servlet instance will be out of service and the container will never call the service() method on this instance. The servlet container cannot reuse this instance in any way. From this state, a servlet instance may only go to the unloaded state. Before calling the destroy() method, the servlet
container waits for the remaining threads that are executing the servlet’s service() method to finish.

A servlet container may destroy a servlet if it is running low on resources and no request has arrived for a servlet in a long time. Similarly, if the servlet container maintains a pool of servlet instances, it may create and destroy the instances from time to time as required. A servlet container may also destroy a servlet if it is shutting down.

5. Unloading a servlet

Once destroyed, the servlet instance may be garbage collected, in which case the servlet instance is said to be unloaded. If the servlet has been destroyed because the servlet container is shutting down, the servlet class will also be unloaded.


Conclusion 
Before a servlet can service the client requests, a servlet container must take certain steps in order to bring the servlet to a state in which it is ready to service the requests. The first step is loading and instantiating the servlet class; the servlet is now considered to be in the loaded state. The second step is initializing the servlet instance. Once the servlet is in the initialized state, the container can invoke its service() method whenever it receives a request from the client. There may be times when the container will call the destroy() method on the servlet instance to put it in the destroyed state. Finally, when the servlet container shuts down, it must unload the servlet instance.

Preinitializing a servlet

Usually, a servlet container does not initialize the servlets as soon as it starts up. It initializes a servlet when it receives a request for that servlet for the first time. This is called lazy loading. Although this process greatly improves the startup time of the servlet container, it has a drawback.

If the servlet performs many tasks at the time of initialization, such as caching static data from a database on initialization, the client that sends the first request will have a poor response time.

In many cases, this is unacceptable. The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor (web.xml) to make the servlet container load and initialize the servlet as soon as it starts up.

This process of loading a servlet before any request comes in is called preloading, or preinitializing, a servlet.

Saturday, January 24, 2009

JSP : Simple File Uploading Codes.

We will see how to upload a file using JSP, you can upload a file to your desire location with desire name. Please see the simple self explanatory codes below.

Please add below mentioned jar files in your applications classpath.





1st HTML interface (can be used in JSP as well)

FileUploadingInterface.HTML


<HTML>
<HEAD>
<TITLE>File Uploading Interface</TITLE>
</HEAD>
<BODY>
<center>
<h3>Simple File Uploading Example</h3>
<form action="ProcessUploadedFile.jsp" method="post" enctype="multipart/form-data">
Name <input type="text" name="userName"> (optional) </br></br>
File <input type="file" name="file1"> </br></br> <!-- Here You Can Add more numbers of Files For Uploading -->
<input type="submit" value="Submit">
</form>
</center>
</BODY>
</HTML>



2nd JSP code


ProcessUploadedFile.jsp


<%@ page import="java.io.*" %>
<%@ page import="java.util.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

if (!isMultipart)
{
}
else
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = null;
try
{
items = upload.parseRequest(request);
}
catch (FileUploadException e)
{
e.printStackTrace();
}

Iterator itr = items.iterator();

while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();

//Get Other Form Fileds Values in this Block
if (item.isFormField())
{
String itemName = item.getFieldName();
String itemValue = item.getString();
String name = "";
if (itemName.equals("userName"))
name = item.getString();

out.println("User Name "+name);
}
//Get File type Values Here, it could be one or multiple File
else
{
try
{
String itemName = item.getName();

//userFieldName is what u provided in html file
String userFieldName = item.getFieldName();

if(itemName != null)
{
if(itemName.equals(""))
{
//If Nothing Uploaded
out.println("No File Uploaded");
}
else
{
//Provide Destination Folder, Where Uploaded File to be saved
boolean folderMade = (new File("d:/UploadedFileFolder")).mkdirs();

// This is required to filter out file name from complete file path.
int idx = itemName.lastIndexOf("\\");

String filename = "";

if(idx > -1)
{
//in case of IE, it sends complete path. Hence only file name must be filtered out.
idx=idx+1;
filename = itemName.substring(idx);
}
else
{
//in case of other borwsers, its just filename
filename = itemName;
}

File savedFile = new File("d:/UploadedFileFolder/"+filename);
item.write(savedFile);

//Get path of the saved file
String path = savedFile.getPath();

out.println("File Uploaded Sucessfully "+path);

}
}
}//try
catch(Exception e)
{
e.printStackTrace();
}
}//else
}//while
}//else
%>