Tuesday, 29 November 2011

add remove() function to array of javascript

Array.prototype.indexOf = function(e){
    for (var i = 0; i < this.length; i++) {
        if (e==this[i]) {
            return i;

  return -1;

Array.prototype.remove = function(elem) {
    var match = -1;
    while ((match = this.indexOf(elem)) > -1) {
        this.splice(match, 1);

How to create an unique array using javascript

Array.prototype.indexOf = function(e){
    for (var i = 0; i < this.length; i++) {
        if (e==this[i]) {
            return i;

  return -1;

Array.prototype.unique = function () {
    var values = this;
    var uniqueValues = [];
    for (var i = values.length; i--;) {
        var val = values[i];
        if (uniqueValues.indexOf(val) === -1) {
    return uniqueValues;

How to reset the start value of Oracle Sequence?

Alter Sequence SEQ_TX_ID Increment By 1000;
Select SEQ_TX_ID.NextVal From Dual;
Alter Sequence SEQ_TX_ID Increment By 1;

Spring MVC error page

It’s always recommended to display a custom friendly error page instead of the default long java plain exception code in tomcat.So what do you do in Spring MVC Web application? 1) Declare SimpleMappingExceptionResolver in Spring’s bean configuration file.
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
    <property name="exceptionMappings">
            <prop key="java.lang.Exception">error</prop>
2) Define "error.jsp"
    <link rel="stylesheet" href="<%=request.getContextPath()%>/styles/smoothness/jquery-ui-1.8.12.custom.css" type="text/css"/>
    <script type="text/javascript" src="<%=request.getContextPath()%>/scripts/jquery-1.5.1.min.js"></script>
    <script type="text/javascript" src="<%=request.getContextPath()%>/scripts/jquery-ui-1.8.12.custom.min.js"></script>
        <div class="ui-widget">
            <div class="ui-state-error ui-corner-all" style="padding: 0 .7em;">
                <p><span class="ui-icon ui-icon-alert" style="float: left; margin-right: .3em;"></span>
                    <strong>Alert:</strong> An error has occurred. Please contact our administrator for details.</p>
                <p><strong>Cause:</strong></p> ${exception.message}
3) Exmaple

How to validate Date format in Javascript?

Validate the input Date text is very common in web application. My solution is combine Regular Express and Date object. Using regular express to validate the text under the special pattern(yyyy-MM-dd etc.). Using Date object to validate the year,month, day is reasonable.

function dateValidator(text) {
    var pattern = /^([1-9]\d{3})-(0[1-9]|1[0-2])-([0-2][1-9]|3[0-1])$/;
    if (pattern.test($.trim(text))) {
        var datePart = text.split('-');
        var year = parseInt(datePart[0], 10);
        var month = parseInt(datePart[1], 10) - 1;
        var day = parseInt(datePart[2], 10);
        var date = new Date(year, month, day, 0, 0, 0);

        var y = date.getFullYear();
        var m = date.getMonth();
        var d = date.getDate();

        if ( year == y && month== m && day == d) {
           return true;
    return false;

Friday, 25 November 2011

how to customize icon for JQuery-UI buttons

Step1: define css


Sunday, 13 November 2011

How to avoid web page duplicated submit?

Solution 1) PRG (Post/Redirect/Get) Pattern

Solution 2) Synchronizer Token Pattern (From book "java/j2ee interview")

The basic idea of this pattern is to set a use once only token in a “session”, when a form is requested and the
token is stored in the form as a hidden field. When you submit the form the token in the request (i.e. due to hidden field) is compared with the token in the session. If tokens match, then reset the token in the session to null or increment it to a different value and proceed with the model & database update. If you inadvertently resubmit the form by clicking the refresh button, the request processing servlet (i.e. PurchaseServlet) first tests for the presence of a valid token in the request parameter by comparing it with the one stored in the session. Since the token was reset in the first submit, the token in the request (i.e 123) would not match with the token in the session (i.e. null or 124). Since the tokens do not match, an alternate course of action is taken like forwarding to an error.jsp page.

HTTP Sessions-From book java/j2ee interview

A session identifies the requests that originate from the same browser during the period of conversation. All the servlets can share the same session. The JSESSIONID is generated by the server and can be passed to client through cookies, URL re-writing (if cookies are turned off) or built-in SSL mechanism. Care should be taken to minimize size of objects stored in session and objects stored in session should be serializable.

Session tracking uses cookies by default. What would you do if the cookies are turned off?
If cookies are turned off, you can still enable session tracking using URL rewriting. This involves including the session ID within the link as the name/value pair as shown below.

Adding session ID to each and every link is cumbersome and hence is simplified by the following methods: response.encodeURL(givenURL) to associate a session ID with a given URL and if you are using redirection then response.encodeRedirectURL(givenURL).
public class CRMServlet extends HttpServlet {
   protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
     req.getSession().setAttribute("key", "ItemNo-1245");
     String url = resp.encodeURL("/myWebCtxt/purchase.do");
     PrintWriter pw = resp.getWriter();
     pw.println("Sample encoded URL -->purchase");
When you invoke the method encodeURL(givenURL) with the cookies turned on, then session ID is not appended to the URL. Now turn the cookies off and restart the browser. If you invoke the encodeURL(givenURL) with the cookies turned off, the session ID is automatically added to the URL as follows:

How do you upload a file to your web application? -From book java/j2ee interview

Upload file via web application then the default encoding and GET methods are not suitable for file upload and a form containing file input fields must specify the encoding type “multipart/formdata”and the POST method in the <form>tag as shown below:
When the user clicks the “Upload” button, the client browser locates the local file and sends it to the server using HTTP POST. When it reaches your server, your implementing servlet should process the POST data in order to extract the encoded file. Unfortunately, application servers implementing the Servlet and JSP specifications are not required to handle the multipart/form-data encoding. Fortunately there are number of libraries available such
as Apache Commons File Upload, which is a small Java package that lets you obtain the content of the uploaded file from the encoded form data. The API of this package is flexible enough to keep small files in memory while large files are stored on disk in a “temp” directory. You can specify a size threshold to determine when to keep in memory and when to write to disk.

how do you download a file from your web application? - From book java/j2ee interview

Files can be downloaded from a web application by using the right combination of
//set the header to a non-standard value for attachments to be saved by the browser with the
//Save-As dialog so that it is unrecognized by the browsers because often browsers try to do
//something special when they recognize the content-type.
//use Content-Disposition “attachment” to invoke “Save As” dialog and “inline” for displaying
//the file content on the browser without invoking the “Save As” dialog.
response.setHeader(“Content-disposition”, “attachment;filename=” + fileName);

@RequestMapping(value = "get_zip_archive")
public ResponseEntity<byte[]> getZippedLogFilesArchive(@RequestParam("tempFileName") String tempFileName) throws IOException {
    final File zipFile = new File(TEMP_DIR, tempFileName);
    try {
        final HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Disposition", "attachment; filename=" + tempFileName);
        return new ResponseEntity<byte[]>(Files.toByteArray(zipFile), headers, HttpStatus.OK);
    } finally {

--jsp page--
function downloadReport(id) {
 window.location = "downloadReportData?id=" + id;