Archives: Servlet

Java Servlet – Logging with Log4j Example

Java Servlet – URL Rewriting Example

[code lang=”java”]import;

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

public class ShoppingCartViewerRewrite extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter out = res.getWriter();

out.println("<HEAD><TITLE>Current Shopping Cart Items</TITLE></HEAD>");

// Get the current session ID, or generate one if necessary
String sessionid = req.getPathInfo();
if (sessionid == null) {
sessionid = generateSessionId();

// Cart items are associated with the session ID
String[] items = getItemsFromCart(sessionid);

// Print the current cart items.
out.println("You currently have the following items in your cart:<BR>");
if (items == null) {
} else {
for (int i = 0; i < items.length; i++) {
out.println("<LI>" + items[i]);

// Ask if the user wants to add more items or check out.
// Include the session ID in the action URL.
out.println("<FORM ACTION=\"/servlet/ShoppingCart/" + sessionid + "\" METHOD=POST>");
out.println("Would you like to<BR>");
out.println("<INPUT TYPE=SUBMIT VALUE=\" Add More Items \">");
out.println("<INPUT TYPE=SUBMIT VALUE=\" Check Out \">");

// Offer a help page. Include the session ID in the URL.
out.println("For help, click <A HREF=\"/servlet/Help/" + sessionid + "?topic=ShoppingCartViewerRewrite\">here</A>");


private static String generateSessionId() throws UnsupportedEncodingException {
String uid = new java.rmi.server.UID().toString(); // guaranteed unique
return URLEncoder.encode(uid, "UTF-8"); // encode any special chars

private static String[] getItemsFromCart(String sessionid) {
return new String[] { "a", "b" };

Java Servlet – File Upload Example

[code lang=”html”]<html>
<p>Commons File Upload Example</p>
<form action="Commonsfileuploadservlet" enctype="multipart/form-data" method="POST">
<input type="file" name="file1"><br>
<input type="Submit" value="Upload File"><br>
[code lang=”java”]import;
import java.util.Iterator;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class CommonsFileUploadServlet extends HttpServlet {
private static final String TMP_DIR_PATH = "c:\\tmp";
private File tmpDir;
private static final String DESTINATION_DIR_PATH ="/files";
private File destinationDir;

public void init(ServletConfig config) throws ServletException {
tmpDir = new File(TMP_DIR_PATH);
if(!tmpDir.isDirectory()) {
throw new ServletException(TMP_DIR_PATH + " is not a directory");
String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(realPath);
if(!destinationDir.isDirectory()) {
throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");

DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();

// Set the size threshold, above which content will be stored on disk.
fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB

// Set the temporary directory to store the uploaded files of size above threshold.

ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
// Parse the request
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem);
// Handle Form Fields.
if(item.isFormField()) {
out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
} else {

//Handle Uploaded files.
out.println("Field Name = "+item.getFieldName()+
", File Name = "+item.getName()+
", Content type = "+item.getContentType()+
", File Size = "+item.getSize());

// Write file to the ultimate location.
File file = new File(destinationDir,item.getName());
} catch(FileUploadException ex) {
log("Error encountered while parsing the request",ex);
} catch(Exception ex) {
log("Error encountered while uploading file",ex);



[code lang=”xml”]<servlet>