Saturday, October 30, 2010

How to upload file with Java Servlet


This is a simple example of how to upload files using JSP and Servlet 3.0 which is a part of Java EE 6. While in earlier versions of Servlets we had to use commons fileupload or other libraries, this feature has been integrated into the Servlet 3.0 specification. Here is the code for a simple servlet and a JSP file that makes a file upload request to the servlet.


  1. FileUploadServlet.java
    package com.blogspot.aoj.servlet3;

    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;

    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;

    import org.apache.log4j.Logger;

    @WebServlet(urlPatterns = "/fileUpload")
    @MultipartConfig
    public class FileUploadServlet extends HttpServlet {
    private static Logger logger = Logger.getLogger(FileUploadServlet.class);

    public FileUploadServlet() {
    super();
    }

    protected void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    for (Part part : request.getParts()) {
    logger.info(part.getName());
    InputStream is = request.getPart(part.getName()).getInputStream();
    int i = is.available();
    byte[] b = new byte[i];
    is.read(b);
    logger.info("Length : " + b.length);
    String fileName = getFileName(part);
    logger.info("File name : " + fileName);
    FileOutputStream os = new FileOutputStream("c:/temp/logs/" + fileName);
    os.write(b);
    is.close();
    }

    }

    private String getFileName(Part part) {
    String partHeader = part.getHeader("content-disposition");
    logger.info("Part Header = " + partHeader);
    for (String cd : part.getHeader("content-disposition").split(";")) {
    if (cd.trim().startsWith("filename")) {
    return cd.substring(cd.indexOf('=') + 1).trim()
    .replace("\"", "");
    }
    }
    return null;

    }

    protected void doPost(HttpServletRequest request,
    HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
    }

    }
    Note:
    • There is no need to use a deployment descriptor the @WebServlet annotation is enough, which uses the urlPatterns property to define servlet mappings
    • The @MultipartConfig is used to indicate that the servlet expects requests wofmultipart/form-data MIME type which is required for file upload. Using@MultipartConfig allows you to use the request.getParts get the parts of the request
    • The getFileName method gets the file name from the content-disposition header.
  2. upload.jsp
    <html>
    <head>
    <title>File Upload with Servlet 3.0</title>
    </head>
    <body>
    <form action="fileUpload" enctype="multipart/form-data" method="post">
    <input type="file" name="uploadFile" /> <input type="submit" /></form>
    </body>
    </html>


Wednesday, December 16, 2009

Overview of JSTL SQL Tags (JSTL Tags part - 3)


SQL Tags:
The tags are used to achieve common database related tasks such as selection, insertion, deletion, updation from within the jsp pages, without using any java code.

1). <sql:query>
This tag is used to query databases.
Syntax:
<sql:query sql="sqlQuery"
var="varName" [scope="{page|request|session|application}"]
[dataSource="dataSource"]
[maxRows="maxRows"]
[startRow="startRow"] />

2). <sql:update>
This tag is used to execute SQL INSERT, UPDATE or DELETE statement. It is also used to execute Data Definition Language statements.
Syntax:
<sql:update sql="sqlUpdate"
[dataSource="dataSource"]
[var="varName"]
[scope={page|request|session|application}" ] />

3). <sql:setDataSource>
This tag is used to export a data source either as a scoped variable or as the data source configuration variable.
<sql: setDataSource
{dataSource="dataSource" | url = "jdbcUrl"
[driver="driverClassName"]
[user="userName"]
[password="password"]}
[var="varName"]
[scope="{page|request|session|application}"] />

4). <sql:param>
This tag is used to set the values of parameter.
Syntax:
<sql:param value="value"/>
5). <sql:dateParam>
Sets the values of parameter markers in a SQL statement for values of type java.util.Date. It also works as a subtag of <sql:query> and <sql:update> tags.
Syntax:
<sql:dateParam value = "value" [type="{timestamp|time|date}"] />
6). <sql:transaction>
This tag is used to set a transaction context for <sql:query> and <sql:update> subtags.
Syntax:
<sql:transaction [dataSource="dataSource"]
[isolation=isolationLevel]>
<sql:query> and <sql:update> statements
</sql:transaction>

isolationLevel ::= "read_committed"
| "read_uncommitted"
| "repeated_read"
| "serializable"


Monday, December 14, 2009

Overview of JSTL Formatting Tags (JSTL Tags part - 2)


Formatting Tags

The formatting tags are used for internationalization and localization of the jsp pages. Internationalization provides support for various languages and data formats. By localization web applications becomes capable of supporting specific regions or locale.



1). <fmt:message>
This tag is used to output locale sensitive strings. The param subtag along with message provides an argument to the compound message in parent message tag. One param tag must be specified for each variable in the compound message or pattern. Replacement takes place in order of the param tags.
Syntax: <fmt:message key = "messageKey"
[bundle="resourceBundle"]
[var="varName"]
[scope="{page|request|session|application}"] />

2). <fmt:setLocale>
This tag is used to set the default locale within a specific JSP scope.
<fmt:setLocale value = "en_US" />
3). <fmt:bundle>
This tag is used to create an i18n localization context to be used by its body content.
Syntax: <fmt:bundle basename = "basename="basename"
[prefix="prefix"]>
body content
</fmt:bundle>

It creates an i18n localization context and loads its resource bundle into that context. The name of the resource bundle is specified with the basename attribute.
4). <fmt:setBundle>
This tag creates an i18n localization context and loads its resource bundle into that context. The name of the resource bundle is specified with the basename attribute.
Syntax: <fmt:setBundle basename = "basename"
[var="varname"]
[scope="{page|request|session|application}"]/>

5). <fmt:param>

This tag is used for parametric replacement to <fmt:message> tag.
Syntax: <fmt:param value="messageParameter"/>

6). <fmt:requestEncoding>

This tag is used to set the request's character encoding
Syntax: <fmt:requestEncoding [value="charsetName"]/>

7). <fmt:timeZone>

This tag is used to specify the time zone in which time information is to be formatted or parsed in its body content.
Syntax: <fmt:timeZone value="timeZone">
body content
</fmt:timeZone>

8). <fmt:setTimeZone>

This tag is used to store specified time zone in a scoped variable or the time zone configuration variable.
Syntax: <fmt:setTimeZone value="timeZone"
[var="varName"]
[scope="{page|request|session|application}"] />

9). <fmt:formatNumber>

This tag is used to format a numeric value in a locale-sensitive or customized manner as a number, currency etc.
Syntax: <fmt:formatNumber value = "numericValue"
[type="{number|currency|percent}"]
[pattern="customPattern"]
[currencyCode="currencyCode"]
[currencySymbol="currencySymbol"]
[goupingUsed="{true|false}"]
[scope="{page|request|session|application}"] />

10). <fmt:parseNumber>
This tag is used to parse the string representation of numbers, currencies, and percentages that were formatted in a locale-sensitive or customized manner.
Syntax: <fmt:parseNumber value="numericValue"
[type="{number|currency|percent}"]
[pattern="customPattern"]
[parseLocale="parseLocale"]
[integerOnly="{true|false}"]
[var="varName"]
[scope="{page|request|session|application}"]/>

11). <fmt:formatDate>
This tag is used to format date and time according to the locale.
Syntax: <fmt:formatDate value="date"
[type="{time|date|both}"]
[dateStyle="{default|short|medium|long|full}"]
[timeStyle="{default|short|medium|long|full}"]
[pattern="customPattern"]
[timeZone="timeZone"]
[var="varName"]
[scope={page|request|session|application}"] />

12). <fmt:parseDate>
Parses the string representation of dates and time that were formatted for a specific locale.
Syntax: <fmt:parseDate value = "dateString"
[type="{time|date|both}"]
[dateStyle="{default|short|medium|long|full}"]
[timeStyle="{default|short|medium|long|full}"]
[pattern="customPattern"]
[timeZone="timeZone"]
[parseLocale="parseLocale"]
[var="varName"]
[scope={page|request|session|application}"] />


Overview of JSP Initialization Parameters


Here is the procedure to specify the initialization parameters for JSP
Web.xml - is used to specify the initialization parameters.
init.jsp - is used to retrieve and show the initialized parameters



Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
<servlet>
<servlet-name>InitJSP</servlet-name>
<jsp-file>/init.jsp</jsp-file>
<init-param>
<param-name>testParam</param-name>
<param-value>hello from web.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>InitJSP</servlet-name>
<url-pattern>/Init</url-pattern>
</servlet-mapping>
</web-app>

The HTML that is used to access the above parameters…


init.jsp
<html>
<head>
<title>Initialization Parameters in JSP</title>
</head>
<body>
Initialization parameter retrieved from the web.xml is:
<br>
<%= pageContext.getServletConfig().getInitParameter("testParam") %>
</body>
</html>


Tuesday, December 1, 2009

Hibernate Overview


Hibernate is Object Relation Mapping (ORM) library made for Java and also available for .Net. It is a Open Source Project, Licensed under LGPL  and component of JBoss Enterprise Middle Suite.
What is the need ? Applications on the Web or on the Desktop need to save data and retrieve data from the database.  ORM is technique for converting data between Object Oriented Languages and Relational Databases. It allows developer to deal with data as objects, something they like doing to make reading and writing of data simpler. Tools have been developed which create Object Mapping automatically , making it easier and faster to develop applications. Using such tools also bring architecture uniformity.


                                                                        Architecture
Java Application connects to POJO objects. These POJO (hibernate) classes use configuration and mapping files written in XML and JDBC/ODBC drivers  to connect and perform operations on a database.
Advantages
·         Open Source.
·         Widely Used and Mature with Active Community.
·         Commercial Support Available for Jboss.
·         Flexible , Easy to Learn and use.
Features
·         Persistent Classes follows Object Oriented Paradigm.
·         Express Query in  SQL(Structured Query Language), HQL(Hibernate Query Language) or Native SQL.
·         Access data using Use POJO(Plain Old Java Objects).
·         Can execute  inside or outside a container. Application Server is not required.
·         Perfect solution of Application which can be Web or Desktop.
·         Application code is database independent. Until of course you use Native SQL
·         Configurable by using XML File.
·         Can be used with or without database.
·         Scalable and works in Clustered Environment.
·         Smaller memory footprint
·         Ability to use Native SQL helps in improving performance.
·         EJB3.0 is similar to hibernate 3.0 making it easier to migrate.
Limitations
·         Does not do automatic instance pooling.
·         Does not have locking or synchronization for data.
·         Relies on database management system to deal with concurrent access.
·         Heavy use of Java Reflection is less of a performance issue, due to improved JVM.
·         Stored Procedures need to return a value , if multiple values are returned first one is selected
·         Any modifications to the database require regeneration of code, potentially wiping your changes.
·         Mapping of Old or Complex databases where the tables have composite keys, and data is spread across tables with different keys is difficult.

In Conclusion it is a great tool which can be used for mapping databases, saving and retrieving data, in simpler faster way with ability to write the Native SQL if performance is needed.


Monday, November 16, 2009

JSTL Tags (part - 1)


JSTL tags
The JSTL 1.1 API Specification consists of following packages:
Tag
Description
Core (javax.servlet.jsp.jstl.core)
General purpose actions
Format (javax.servlet.jsp.jstl.fmt)
Internationalization and Localization
SQL (javax.servlet.jsp.jstl.sql)
Common database tasks
Tag Library Validator(javax.servlet.jsp.jstl.tlv)
Tag Library Validators
Description of JSTL Tags
Core Tags: 
These tags provides the core functionality that a programming language is supposed to provide, such as codition, iteration etc.
1). <c:out>
This tag is used to evaluate an expression and output the result to the current JspWriter object.
Syntax: <c:out value="value" [escapeXml="{true|false}"]  [default="defaultValue"] />
2). <c:forEach>
This tag provide functionality to iterate over an array or collection without using java code.
Syntax: <c:forEach [var="varName"] items = "collection"  [varStatus="varStatusName"] [begin="start"] [end="end"] [step="step"]>
   .... body..
</c:forEach>

3.) <c:if>
This is used for conditional branching within the jsp page based on some test.
Syntax: <c:if  test ="testCondition" var="varName" [scope="{page|request|session|application}"] />
4). <c:set>
This tag is used to set attributes within specified scopes in jsp pages
Syntax: <c:set value="val" var="varname" [scope="{page|request|session|application}"] />
5).  <c:remove>
This tag is used to remove a scoped variable.
Syntax: <c:remove var="varName" [scope="{page|request|session|application}"] />
6).  <c:url>
This tag is used for session management and URL rewriting.
Syntax: <c:url value="value" [context="context"] [var="varName"] [scope="{page|request|session|application}"] />
7).  <c:import>
This is used to include external resources inside the jsp page.
<c:choose>, <c:when> and <c:otherwise> tags
These tags are used for conditional branching, that is provided by switch.... case statement in most programming languages. <c:choose> is used for mutually exclusive conditional execution.
Syntax: <c:choose>..body..... (<when> and <otherwise> subtags) </c:choose>
<c:when> represents an alternative within a <c:choose> action.
Syntax: <c:when test="testCondition">  .... body </c:when>
<c:otherwise> represents the last alternative within a <c:choose> action.
Syntax: <c:otherwise> ..... conditional block..</c:otherwise>
8).  <c:catch>
This tag provide a try...catch like mechanism inside jsp pages without using scriptlets.
Syntax: <c:catch [var="varName"]> .... nested actions </c:catch>
9).  <c:redirect>
This provides same functionality as the sendRedirect() method of HttpServletRequest interface. It is used to redirect control to other pages within the web application.
Syntax: <c:redirect url="value" [context="context"] />
10).  <c:param>
This tag is used to add request parameters to a URL. It is also used as a nested tag, within the <c:import>, <c:url> and <c:rediret> tags.
Syntax: <:param name = parameterName" value = "parameterValue" />
11).  <c:forEachToken>
This tag when provided with delimiters can be used to iterate over tokens. Its functionality is like that of StringTokenizer.
Syntax: <c:forTokens items = "tokenString" delims="delimiter"
            [var="variableName"] [varStatus="variableStatusName"] [begin="start"  [end="end"]  [step="step"]> ........ body content..</c:forTokens>