Monday 18 April 2016

How to declare and initialize a List (ArrayList and LinkedList) with values in Java mkniit.blogspot.in

Initializing a list while declaring is very convenient for quick use, but unfortunately, Java doesn't provide any programming constructs e.g. collection literals, but there is a trick which allows you to declare and initialize a List at the same time. This trick is also known as initializing List with values. If you have been using Java programming language for quite some time then you must be familiar with syntax of array in Java and how to initialize an array in the same line while declaring it as shown below:

String[] oldValues = new String[] {"list" , "set" , "map"};

or even shorter :

String[] values = {"abc","bcd", "def"};

Similarly, we can also create List  and initialize it at the same line, popularly known asinitializing List in one line exampleArrays.asList() is used for that purpose which returns a fixed size List backed by Array. By the way don’t confuse between Immutable or read only List which doesn’t allow any modification operation including set(index)which is permitted in fixed length List.Here is an example of creating and initializing Listin one line:


Java program to Create and initialize List in one line

How to create and initialize List in one line in Java with ArrayHere is a Java program which creates and initialize List in one line using Array.Arrays.asList() method is used to initialize List in one line and it takes an Array which you can create at the time of calling this method itself.Arrays.asList() also use Generics to provide type-safety and this example can be written using Generics as well.


import java.util.Arrays;
import java.util.List;

/**
 * How to create and initialize List in the same line,
 * Similar to Array in Java.
 * Arrays.asList() method is used to initialize a List
 * from Array but List returned by this method is a
 * fixed size List and you can not change its size.
 * Which means adding and deleting elements from the
 * List is not allowed.
 *
 * @author Javin Paul
 */

public class ListExample {

    public static void main(String args[]) {
 
      //declaring and initializing array in one line
      String[] oldValues = new String[] {"list" , "set" , "map"};
      String[] values = {"abc","bcd""def"};
 
      //initializing list with array in java
      List init = Arrays.asList(values);
      System.out.println("size: " + init.size()
                          +" list: " + init);
 
      //initializing List in one line in Java
      List oneLiner = Arrays.asList("one" , "two""three");
      System.out.println("size: " + init.size()
                       +" list: " + oneLiner);
 
      // List returned by Arrays.asList is fixed size
      // and doesn't support add or remove


      // This will throw java.lang.UnsupportedOperationException
      oneLiner.add("four"); 


      // This also throws java.lang.UnsupportedOperationException
      //oneLiner.remove("one"); 
    }
}

Output:
size: 3 list: [abc, bcd, def]
size: 3 list: [one, two, three]
Exception in thread "main" java.lang.UnsupportedOperationException
        at java.util.AbstractList.add(AbstractList.java:131)
        at java.util.AbstractList.add(AbstractList.java:91)
        at test.ExceptionTest.main(ExceptionTest.java:32)

As shown in above example it's important to remember that List returned byArrays.asList() can not be used as regular List for further adding or removing elements. It's kind of fixed length Lists which doesn't support addition and removal of elements. Nevertheless its clean solution for creating and initializing List in Java in one line, quite useful for testing purpose.

If you want to convert that fixed length List into a proper ArrayList, LinkedList or Vector any other Collection class you can always use the copy constructor provided by Collection interface, which allows you to pass a collection while creating ArrayList or LinkedList and all elements from source collection will be copied over to the new List. This will be the shallow copy so beware, any change made on an object will reflect in both the list.

How to declare and initialize a List in one line


Here is how you can convert this fixed length list to ArrayList or LinkedList in Java:

package beginner;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;


/**
 * Java Program to create and initialize ArrayList LinkedList in same line
 * 
 * @author WINDOWS 8
 *
 */
public class HelloWorldApp {

    public static void main(String args[]) {
      
        List<String> pairs = Arrays.asList(new String[]{"USD/AUD", "USD/JPY", "USD/EURO"});
        ArrayList<String> currencies = new ArrayList<>(pairs);
        LinkedList<String> fx = new LinkedList<>(pairs);
        
        System.out.println("fixed list: " + pairs);
        System.out.println("ArrayList: " + currencies);
        System.out.println("LinkedList: " + fx);
    }
}

Output:
fixed list: [USD/AUD, USD/JPY, USD/EURO]
ArrayList: [USD/AUD, USD/JPY, USD/EURO]
LinkedList: [USD/AUD, USD/JPY, USD/EURO]

This is pretty neat and I always this trick you create the Collection I want with values. You can use this to create ArrayList with values, Vector with values, or LinkedList with values. In theory, you can use this technique to create any Collection with values.

Related Java Collection tutorials from Javarevisited Blog
Difference between LinkedList and ArrayList in Java



RELATED TOPICS
Read More »

What is JSESSIONID in J2EE Web application - JSP Servlet? mkniit.blogspot.in

What is JSESSIONID in JSP Servlet
JSESSIONID is a cookie generated by Servlet container like Tomcat or Jetty and used for session management in J2EE web application for http protocol. Since HTTP is a stateless protocol there is no way for Web Server to relate two separate requests coming from same client and Session management is the process to track user session using different session management techniques like Cookies andURL Rewriting. If Web server is using cookie for session management it creates and sends JSESSIONID cookie to the client and than client sends it back to server in subsequenthttp requestsJSESSIONID and session management is a not only a popular Servlet interview question but also appear in various JSP interviews. Along with What is JSESSIONIDinterviewer are also interested in when and how JSESSIONID is created in Servlet and JSP which we will see in next section.



When JSESSIONID created in Web application?
What is JSESSIONID in JSP Servlet HTML web application
In Java J2EE application container is responsible for Session management and by default uses Cookie. When a user first time access your web application, session is created based upon whether its accessing HTML, JSP or Servlet. if user request is served by Servlet than session is created by callingrequest.getSession(true) method. it accepts a boolean parameter which instruct to create session if its not already existed. if you callrequest.getSession(false) then it will either return null if no session is associated with this user or return the associated HttpSession object. IfHttpRequest is for JSP page than Container automatically creates a new Session with JSESSIONID if this feature is not disabled explicitly by using page directive %@ page session="false" %>. Once Session is created Container sendsJSESSIONID cookie into response to the client. In case of HTML access, no user session is created. If  client has disabled cookie than Container uses URL rewriting for managing session on which jsessionid is appended into URL as shown below:

https://localhost:8443/supermart/login.htm;jsessionid=1A530637289A03B07199A44E8D531427

When HTTP session is invalidated(), mostly when user logged off, old JSESSIONID destroyed and a newJSESSIONID is created when user further login.

How to monitor HTTP request to check JSESSIONID

You can check value of JSESSIONID coming in as cookie by monitoring HTTP request. If you are running Tomcat Server in NetBeans IDE in your development environment than you can use HTTP Server Monitor to check http requests. You just need to enable it while starting Tomcat Server form Netbeans. After than with each request you can see all details like request headers, session, cookies etc in HTTP Server monitor screen. If you look on JSESSIONID cookie it will look like:

cookie  JSESSIONID=1A530637289A03B07199A44E8D531427

You can also enable http request and response in Client side by using tools like ethereal or Wireshark. This tool can monitor all http traffic from and to your machine and by looking on request data you can see JSESSIONID cookie and its value.

That's all on What is JSESSIONID and How JSESSIONID is created inside J2EE application. We have seen that both Servlet and JSP can be responsible for Session creation but its done by Container. you can retrieve value of SessionIDwhich is represented by JSESSIONID cookie when you call request.getSession(). Session management in web applications are complex topic especially when it comes to clustering and distributed session. On the other handJSESSIONID is one of those basics which as J2EE web application developer you should be aware of.

Other JSP and Servlet tutorial from Javarevisited Blog



RELATED TOPICS
Read More »

How to disable submit button in HTML JavaScript to prevent multiple form submission mkniit.blogspot.in GNIITSOLUTION

Avoiding multiple submission of HTML form or POST data is common requirement in Java web application. Thankfully, You can prevent multiple submission by disabling submit button in HTML and JavaScript itself, rather than handling it on server side. This is very common requirement while developing web application using Servlet and JSP or anyother web technology. At same time there are lot of information and noise available in web and its very hard to find simple approach to disable submit button. When I search for simple way to disable submit button in HTML and JavaScript, I was overwhelmed by responses on forums and various online community. Those are good for intermediate HTML and JavaScript developer but a beginner might just get overwhelmed by amount of information presented and rather confused to use which approach will work, how exactly should I disable submit button to prevent multiple form submissions etc. That drives me to write this post and summarize the simplest possible approach to disable submit button using HTML and JavaScript. I see there could be issues related to browser compatibility which we can talk once we know the simplest approach and my intention is to add those issues and there remedy as and when I know about it to keep this article update, relevant and simple. By the way How to avoid multiple submission of HTML form is also a popular JSP Interview question and worth preparing.


How to disable submit button using JavaScript

You don't need to do a lot just add  this.disabled='disabled' on onclick event handler of button like below:

<form action="submit.jsp" method="post" >
<input type="submit" name="SUBMIT" value="Submit Form"onclick="this.disabled='disabled'" />
</form>

This JavaScript code will disable submit button once clicked. Instead of this, which represent current element similar toJava this keyword, You can also use document.getElementById('id') but  this is short and clear.

Now some browser has problem to submit data from disabled button. So, its better to call form.submit() from onclickitself to submit form data, which makes your code to onclick="this.disabled=true;this.form.submit().Particularly, on Internet Explorer a disabled submit button doesn't submit form data to server. You can also change value or text of submit button from submit to "Submitting...." to indicate user that submit is in progress. Final JavaScript code should look like:

<form action="submit.jsp" method="post" >
<input type="submit" name="SUBMIT" value="Submit Form"onclick="this.value='Submitting ..';this.disabled='disabled'; this.form.submit();"/>
</form>

That's all you need to disable submit button using HTML and JavaScript to prevent multiple submission.

Once you are comfortable with simple way of disabling submit button you may go and explore multiple ways to prevent multiple form submissions or disable submit button. As I said if you are beginner to JavaScript or HTML than it takes some time to get hold of these tricks. If you are using Internet explorer and not calling this.form.submit() then only button will be disabled but form will not be submitted so always call this.form.submit().


form.submit() doesn't include submit button name in request

how to disable submit button to avoid multiple submission of form in JavascriptThere is a caveat while using JavaScript to submit form, it doesn't include name of submit button as request parameter. If you are checking for name of submit button on server side your code will fail. For example, following code which is checking for SUBMIT button as request parameter usinSpring MVCWebUtils class.

if(WebUtils.hasSubmitParameter(request, "SUBMIT")){
 //form has been submitted start processing.
}

This code will fail if form is submitted by this.form.submit(), rather than clicking submit button. Traditionally name of submit button is included in HTTP request only if form is submitted by clicking submit button otherwise no. Fortunately there is a workaround to this problem, You can call document.form_name.submit_name.click() to simulate click on submit button. This will include name of submit button iHTTP  POST request and above Spring MVC example will work as expected. If you don't have multiple buttons on screen and only have one submit button than you can also use HTML hidden input field to send name of  submit button as shown in below example:

<input type="hidden" value="meta data" name="SUBMIT" id="submit_hidden" />

Since code is only checking for any named parameter with name SUBMIT it will work.

What if you have multiple submit button in one screen

There are cases when you have multiple HTML button in one screen like "Accept" or "Decline", "Yes or "No" , Accept" or "Reject" etc. In this case, clicking one button should disable both buttons because there are intended for one operation. In order to disable multiple submit button in onclick, You need to explicitly disable those buttons. As in following example, if you have two buttons with name accept and decline , we are disabling both when any of the button get clicked.

<input type="submit"
       id="accept"
       name="ACCEPT"
       value="Accept"          
       onclick="this.disabled='disabled';
                document.getElementById('reject').disabled='disable';
                this.form.submit();" />

<input type="submit"
       id="reject"
       name="REJECT"
       value="Reject"    
       onclick="this.disabled='disabled';
               document.getElementById('accept').disabled='disable';
               this.form.submit();" />

This code may get clutter if you have more than two buttons and its best to write JavaScript function to disable all submit button on that group.

That’s all on How to disable submit button in HTML and prevent multiple form submissions on Server. Anyway there are multiple ways to accomplish this, both on client side and server side. I prefer to do this on client side using JavaScript to avoid server round trip. Let us know how do you prevent multiple form submission in your web application.
JavaScript Unit TestingRelated Book - JavaScript Unit Testing
Given important of Unit testing in software development, and with growing importance of JavaScript in web development, I always feel need of good book on unit testing my JavaScript code.JavaScript Unit testing is a good read to fill that gap.
Other Java web tutorials and Interview questions you may like



RELATED TOPICS
Read More »

5 Difference between Application Server and Web Server in Java mkniit.blogspot.com

Application server and web server in Java both are used to host Java web application. Though both application server and web server are generic terms, difference between application server and web server is a famous J2EE interview question. On  Java J2EE perspective main difference between web server and application server is support of EJB. In order to run EJB or host enterprise Java application (.ear) file you need an application server likeJBossWebLogicWebSphere or Glassfish, while you can still run your servlet and JSP or java web application (.war)file inside any web server like Tomcat or Jetty.

This Java interview question are in continuation of my previous post on interviews like Top 10 Spring interview questionsand  Top 10 Struts interview question.  Here we will see some difference between application server and web server in point format which will help you to answer this question in any java interview.

Application Server vs Web Server

1. Application Server supports distributed transaction and EJB. While Web Server only supports Servlets and JSP.
2. Application Server can contain web server in them. most of App server e.g. JBoss or WAS has Servlet and JSP container.

3. Though its not limited to Application Server but they used to provide services like Connection poolingTransaction management, messaging, clustering, load balancing and persistence. Now Apache tomcat also provides connection pooling.


4. In terms of logical difference between web server and application server. web server is supposed to provide http protocol level service while application server provides support to web service and expose business level service e.g. EJB.

5. Application server are more heavy than web server in terms of resource utilization.

Personally I don't like to ask questions like Difference between Application Server and Web Server. But since its been asked in many companies, you got to be familiar with some differences. Some times different interviewer expect different answer but I guess on Java's perspective until you are sure when do you need an application server and when you need a web server, you are good to go.

Other Java Interview questions post you may like:




RELATED TOPICS
Read More »