Wednesday, December 10, 2014

Request Dispatcher: Servlets

Request Dispatching is a mechanism to forward/redirect a request to another resource.

Here target resource can be one of the following:
1. a servlet/jsp in the same web application (using HttpServletRequest or ServletContext)
2. a servlet/jsp in different web application in the same web container (using ServletContext)
3. invoking other web container's page using redirect

Getting RequestDispatcher object:

There are three ways to get RequestDispatcher object.

1. using request's getRequestDispatcher()
RequestDispatcher dispatcher = request.getRequestDispatcher("<resource name>");

2. using ServletContext's getRequestDispatcher()
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("<resource name>");

3. using ServletContext's getNamedDispatcher()
RequestDispatcher dispatcher = getServletContext().getNamedDispatcher(<resource name>);

Differences between request and context's getRequestDispatcher() methods:

1. request: we can forward to only any other servlet/jsp in the same web application
context: we can forward to any other servlet/jsp in the same web application or different web application in the same web container
2. request: target resource path can be absolute or relative
context: target resource path must be absolute

Difference between forward and include:
When forward() is used, we get the response written by Forwarded Servlet(Second servlet) only.
But with include(), we get both the servlet's written response.

Lets say there are two servlets - FirstServlet and SecondServlet, like below:

FirstServlet.java:

package com;

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

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

import javax.servlet.RequestDispatcher;

public class FirstServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
PrintWriter out = response.getWriter();

out.println("From FirstServlet: before forward() to second servlet");

RequestDispatcher dispatcher = request.getRequestDispatcher("second");
dispatcher.forward(request, response); //OBSERVE THIS LINE

out.println("From FirstServlet: after forward() to second servlet");
out.flush();
}
}

SecondServlet.java:

package com;

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

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

public class SecondServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
PrintWriter out = response.getWriter();

out.println("From SecondServlet: response from Second Servlet");
}
}

output with forward():
    From SecondServlet: response from Second Servlet

output with include():
    From FirstServlet: before forward() to second servlet
    From SecondServlet: response from Second Servlet
    From FirstServlet: after forward() to second servlet


getNamedDispatcher():


This is also obtained using request object. So using getNameDispatcher(), we can forward our request to any other servlet/jsp in the same web container, by mentioning its logical name, which is defined inside <servlet-name> tag.

sendRedirect():

This is used to forward the request to another web container's page.
public void sendRedirect(String url)

Lets say a servlet is redirecting request to google.com.
So when we send request to servlet, it will send back the http status code as 302(Moved Temporarily) to browser, with target url. Then browser will make another request to sent URL. This is not visible to user, so user assumes that response is directly coming from second url.


Friday, December 5, 2014

Getting installed tomcat version Information

Once the tomcat is installed in your machine and you want to know the version information related to tomcat, then you can execute the "ServerInfo" java class.

1. cd to tomcat installation directory, i.e., CATALINA_HOME

cd "c:\Program Files\Apache Software Foundation\Tomcat 6.0\

2. Run the ServerInfo class as below:

java -cp lib\catalina.jar org.apache.catalina.util.ServerInfo

This should show the information like below:

Server version: Apache Tomcat/6.0.37
Server built:   Apr 29 2013 11:34:47
Server number:  6.0.0.37
OS Name:        Windows 7
OS Version:     6.1
Architecture:   amd64
JVM Version:    1.6.0_45-b06
JVM Vendor:     Sun Microsystems Inc.

Monday, December 1, 2014

web.xml tags

1. Loading a servlet as welcome file
We use <welcome-file-list> to configure the welcome file(like html, jsp) corresponding to application. But if we want to execute a servlet as a welcome file, then we need to give the respective servlet's URL pattern in the <welcome-file> tag.
eg:


2. load-on-startup tag:

Sunday, November 23, 2014

Upload file to Server: Using Servlet and Javascript

Folder Structure:

Project root
---src
------com
---------FileLocationContextListener.java
---------UploadFileServlet.java
WebContent
---resources
------js
---------ImgUploader.js
---WEB-INF
------web.xml
---file.jsp

FileLocationContextListener.java
package com;

import java.io.File;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class FileLocationContextListener implements ServletContextListener {

@Override
public void contextInitialized(ServletContextEvent sce) {
// String rootPath = System.getProperty("catalina.home");
String rootPath = "C:/Users/Suresh/Desktop/temp";
ServletContext ctx = sce.getServletContext();
String relativePath = ctx.getInitParameter("tempfile.dir");

File file = new File(rootPath + File.separator + relativePath);
System.out.println(file.getAbsolutePath());
if(! file.exists()) {
boolean dirCreated = file.mkdir();
System.out.println("Directory created?" + dirCreated);
}

System.out.println("File Directory created to be used for storing files");
ctx.setAttribute("FILES_DIR_FILE", file);
ctx.setAttribute("FILES_DIR", rootPath + File.separator + relativePath);
}

@Override
public void contextDestroyed(ServletContextEvent sce) {
//do cleanup if needed
}
}

UploadFileServlet.java
package com;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFileServlet extends HttpServlet {
private ServletFileUpload uploader = null;

public void init() throws ServletException {
DiskFileItemFactory fileFactory = new DiskFileItemFactory();
File filesDir = (File) this.getServletContext().getAttribute("FILES_DIR_FILE");
fileFactory.setRepository(filesDir);
this.uploader = new ServletFileUpload(fileFactory);
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(! ServletFileUpload.isMultipartContent(request))
throw new ServletException("Content type is not multipar/form-data");

response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.write("<html><head></head><body>");

try {
List<FileItem> fileItemsList = uploader.parseRequest(request);
Iterator<FileItem> fileItemsIterator = fileItemsList.iterator();

while(fileItemsIterator.hasNext()) {
FileItem fileItem = fileItemsIterator.next();

System.out.println("FieldName=" + fileItem.getFieldName());
System.out.println("FileName=" + fileItem.getName());
System.out.println("Content Type=" + fileItem.getContentType());
System.out.println("Size in bytes=" + fileItem.getSize());

File file = new File(this.getServletContext().getAttribute("FILES_DIR") + File.separator + fileItem.getName());
System.out.println("Absolute Path at server=" + file.getAbsolutePath());
fileItem.write(file);
out.write("File " + fileItem.getName() + " uploaded successfully.");
out.write("<br>");
out.write("<a href='UploadFileServlet?fileName=" + fileItem.getName() + "'>Download</a>");
}
} catch(Exception e) {
e.printStackTrace();
}

out.write("</body></html>");
}
}

ImgUploader.js

function fileUpload(form, action_url, div_id) {
// Create the iframe...
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "upload_iframe");
iframe.setAttribute("name", "upload_iframe");
iframe.setAttribute("width", "0");
iframe.setAttribute("height", "0");
iframe.setAttribute("border", "0");
iframe.setAttribute("style", "width: 0; height: 0; border: none;");

// Add to document...
form.parentNode.appendChild(iframe);
window.frames['upload_iframe'].name = "upload_iframe";

iframeId = document.getElementById("upload_iframe");

// Add event...
var eventHandler = function() {

if (iframeId.detachEvent)
iframeId.detachEvent("onload", eventHandler);
else
iframeId.removeEventListener("load", eventHandler, false);

// Message from server...
if (iframeId.contentDocument) {
content = iframeId.contentDocument.body.innerHTML;
} else if (iframeId.contentWindow) {
content = iframeId.contentWindow.document.body.innerHTML;
} else if (iframeId.document) {
content = iframeId.document.body.innerHTML;
}

document.getElementById(div_id).innerHTML = content;

// Del the iframe...
setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
}

if (iframeId.addEventListener)
iframeId.addEventListener("load", eventHandler, true);
if (iframeId.attachEvent)
iframeId.attachEvent("onload", eventHandler);

// Set properties of form...
form.setAttribute("target", "upload_iframe");
form.setAttribute("action", action_url);
form.setAttribute("method", "post");
form.setAttribute("enctype", "multipart/form-data");
form.setAttribute("encoding", "multipart/form-data");

// Submit the form...
form.submit();

document.getElementById(div_id).innerHTML = "Uploading...";
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>ImgUploadProj</display-name>
  <welcome-file-list>
    <welcome-file>file.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
  <param-name>tempfile.dir</param-name>
  <param-value>tmpfiles</param-value>
  </context-param>
  <listener>
  <listener-class>com.FileLocationContextListener</listener-class>
  </listener>
  <servlet>
  <servlet-name>Image Upload Servlet</servlet-name>
  <servlet-class>com.UploadFileServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  <servlet-name>Image Upload Servlet</servlet-name>
  <url-pattern>/upload.file</url-pattern>
  </servlet-mapping>
</web-app>

file.jsp

<html>
<head>
<script type="text/javascript" src="resources/js/ImgUploader.js"></script>
<link rel="stylesheet" type="text/css" href="resources/css/styles.css">
</head>
<body>
<form>
<div class="upload">
<!--input type="file" name="datafile"
onchange="fileUpload(this.form,'upload.file','upload'); return false;" /-->
<input type="file" name="datafile" />
<br>
<button type="button"
onclick="fileUpload(this.form,'upload.file','upload'); return false;">Upload
File</button>
</div>
</form>
</body>
</html>

Monday, August 11, 2014

Servlets and JSP Interview Questions

1. Different HTTP status codes and their significance with examples?

There are 5 types of status codes
a) 1xx - Information
eg: 100 - Continue, 101 - Switching protocols
b) 2xx - Success
eg: 200 - OK
c) 3xx - Redirection
eg: 301 - Moved Permanently
d) 4xx - Client Error
eg: 401 - Unauthorized, 403 - Forbidden, 404 - Not Found,
e) 5xx - Server Error
eg: 500 - Internal Server Error, 502 - Bad Gateway, 503 - Service Unavailable

2. Difference between page directive include, jsp include action and c:import?
<%@ include file="Header.html"/>
<jsp:include page="Header.jsp"/>
<c:import url="http://www.cdnetworksuresh.com/files/file1.html" />

c:import can include external web container urls also, along with static/dynamic file/pages in the same web application.
//TODO:

3. Why do we need to use c:out tag to print a variable instead of printing the EL directly in jsp?
To avoid Cross site Scripting vulnerability.

4. Lets say we have two servlets - FirstServlet.java and SecondServlet.java.
Now my requirement is that once request comes to FirstServlet(url pattern: /first), I have to forward that request to SecondServlet(url pattern: /second) using RequestDispatcher.
Obviously in web.xml, we need to have an entry for FirstServlet.
Do we need to have entry for SecondServlet as well?

Ans: Yes. Since when trying to forward the request to another Servlet using RequestDispatcher, there should be some way to get the Servlet Corresponding to mentioned url pattern. This can be done only through web.xml. So it is mandatory to have <servlet> entry for SecondServlet as well in web.xml

5. Where the compiled jsp class is present in eclipse workspace?
eg: D:\eclipsews\myws\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\ServletProj\org\apache\jsp\jspPage_jsp.java

6. What is the web.xml entry to access a jsp defined under WEB-INF/ folder?
Ans: The files present under /WEB-INF/ folder are secured/protected. User cannot access them directly.
To access a jsp file placed directly under WEB-INF/ folder can be accessed as follows: (mention the jsp file location completely, starting with /WEB-INF)
<servlet>
<servlet-name>One Jsp</servlet-name>
<jsp-file>/WEB-INF/one.jsp</jsp-file>
</servlet>

<servlet-mapping>
<servlet-name>One Jsp</servlet-name>
<url-pattern>/one</url-pattern>
</servlet-mapping>

7. What are corresponding HTTP methods of Restful web services(CRUD) operations?
Create: POST
Retrieve/Read: GET
Update: PUT
Delete: DELETE

Wednesday, June 18, 2014

Showing an Image/Icon in place of html input type file Browse button

When we use html input type file component, we get a button and file text in the page, like below:

 

To show an icon/button/image in place of above content, we can use javascript and css.
Using CSS we show image and using javascript, we submit the form:


Files:

upload.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="resources/css/fileUpload.css"/>
<script type="text/javascript" src="resources/js/fileUpload.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Upload File Demo</title>
</head>
<body>
    <form>
        <div class="upload">
            <input type="file" name="datafile"
                onchange="fileUpload(this.form,'upload.file','upload'); return false;" /></br>
        </div>
    </form>
</body>
</html>


fileUpload.css:
div.upload {
    background: url('../images/images.jpeg');
    background-repeat: no-repeat;
    background-size:50px 50px;
}

div.upload input {
    display: block !important;
    width: 157px !important;
    height: 57px !important;
    opacity: 0 !important;
    overflow: hidden !important;
}


fileUpload.js
function fileUpload(form, action_url, div_id) {
    // Create the iframe...
    var iframe = document.createElement("iframe");
    iframe.setAttribute("id", "upload_iframe");
    iframe.setAttribute("name", "upload_iframe");
    iframe.setAttribute("width", "0");
    iframe.setAttribute("height", "0");
    iframe.setAttribute("border", "0");
    iframe.setAttribute("style", "width: 0; height: 0; border: none;");

    // Add to document...
    form.parentNode.appendChild(iframe);
    window.frames['upload_iframe'].name = "upload_iframe";

    iframeId = document.getElementById("upload_iframe");

    // Add event...
    var eventHandler = function() {

        if (iframeId.detachEvent)
            iframeId.detachEvent("onload", eventHandler);
        else
            iframeId.removeEventListener("load", eventHandler, false);

        // Message from server...
        if (iframeId.contentDocument) {
            content = iframeId.contentDocument.body.innerHTML;
        } else if (iframeId.contentWindow) {
            content = iframeId.contentWindow.document.body.innerHTML;
        } else if (iframeId.document) {
            content = iframeId.document.body.innerHTML;
        }

        document.getElementById(div_id).innerHTML = content;

        // Del the iframe...
        setTimeout('iframeId.parentNode.removeChild(iframeId)', 250);
    }

    if (iframeId.addEventListener)
        iframeId.addEventListener("load", eventHandler, true);
    if (iframeId.attachEvent)
        iframeId.attachEvent("onload", eventHandler);

    // Set properties of form...
    form.setAttribute("target", "upload_iframe");
    form.setAttribute("action", action_url);
    form.setAttribute("method", "post");
    form.setAttribute("enctype", "multipart/form-data");
    form.setAttribute("encoding", "multipart/form-data");

    // Submit the form...
    form.submit();
}

 

Monday, June 16, 2014

Navigation menu content switcher: html/jsp, css, javascript

Goal:
We have a flat navigation bar with menu options: Home, Careers, Contact Us.
When ever user clicks on any of these options, corresponding content has to be shown below.

It is achieved using simple javascript function.

Please find all the files content below:

1. switcher.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css"
    href="resources/css/SwitcherStyles.css" />
<script type="text/javascript" src="resources/js/SwitcherJs.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Switcher Demo</title>
</head>
<body>
    <div>
        <ul>
            <li><a href="#" id="a1" onclick="changeMenu(this.id);">Home</a></li>
            <li><a href="#" id="a2" onclick="changeMenu(this.id);">Careers</a></li>
            <li><a href="#" id="a3" onclick="changeMenu(this.id);">Contact
                    Us</a></li>
        </ul>
    </div>
    <div id="div-home" style="display: block;">
        <p>
            This is the content related to <b>Home</b>
        </p>
    </div>
    <div id="div-careers" style="display: none;">
        <p>
            This is the content related to <b>Careers</b>
        </p>
    </div>
    <div id="div-contactus" style="display: none;">
        <p>
            This is the content related to <b>Contact Us</b>
        </p>
    </div>
</body>
</html>


2. Javascript: SwitcherJs.js

function changeMenu(id) {
    var homeDiv = document.getElementById("div-home");
    var careersDiv = document.getElementById("div-careers");
    var contactUsDiv = document.getElementById("div-contactus");
   
    if("a1" == id) {
        homeDiv.style.display = 'block';
        careersDiv.style.display = 'none';
        contactUsDiv.style.display = 'none';
    } else if("a2" == id) {
        homeDiv.style.display = 'none';
        careersDiv.style.display = 'block';
        contactUsDiv.style.display = 'none';
    } else if("a3" == id) {
        homeDiv.style.display = 'none';
        careersDiv.style.display = 'none';
        contactUsDiv.style.display = 'block';
    }
}


3. CSS: SwitcherStyles.css

li {
    display: inline;
    padding: 20px;
}

a {
    text-decoration: none;
    color: #00F;
    padding: 8px 8px 8px 8px;
}

a:HOVER {
    color: #F90;
    background-color: #FFF;
}

ul {
    border: 1px solid;
    margin: 0px;
    padding: 8px 0px;
}


Demo Screenshots:











Monday, June 9, 2014

Showing icon for a web site: Using link tag in html page

We can show icon for a website in browser using link tag like below in the html page:

<link rel="SHORTCUT ICON" href="resources/images/icon.ico">

Include this line in the head section of the html page.

image extension must be .ico