Search This Blog

Showing posts with label Servlet. Show all posts
Showing posts with label Servlet. Show all posts

Thursday, 7 May 2015

Java Collection Introduction

Java Collection Introduction


 A collection is an object that contains a group of objects.
Each object in a collection is called an element. Every collection contains a group of objects.
Each different type of collection manages their elements in its own way.
The Collections Framework consists of interfaces, implementation classes, and some utility classes to handle most types of collections.
Java Collections are designed to work only with objects.
All collection classes in Java are declared generic.

Architecture of the Collection Framework

The Java Collections Framework has three main components:
  • Interfaces
  • Implementation Classes
  • Algorithm Classes
An interface in Java Collections Framework represents a specific type of collection.
For example, the List interface represents a list. The Set interface represents a set. The Map interface represents a map.
The data structures defined by interfaces rather than a class has the following advantages: we can provide different implementation for the same interfaces.
The Java Collections Framework also provides implementations of collection interfaces.
We should always try to define the type of the class using interfaces, rather than using their implementation classes.
The following code shows how to use the implementation class ArrayList to create a list:
List<String> names = new ArrayList<>();
If possible we should avoid using the following way to create a list object.
ArrayList<String> names = new ArrayList<>();



Operations

We can perform different actions on a collection.
  • searching through a collection
  • converting a collection of one type to another type
  • copying elements from one collection to another
  • sorting elements of a collection in a specific order

Friday, 18 July 2014

AJAX with Servlets/JSP using JQuery and JSON



 To do this, let us get introduced to JSON(Javascript Object Notation), in addition to JQuery and AJAX. JSON is derived from Javascript for representing simple data structures and associative arrays, called objects. Here in our scenario, we are going to use a JSON library in Servlet to convert Java objects (lists,maps,arrays.etc) to JSON strings that will be parsed by JQuery in the JSP page and will be displayed on the web page.


There are many JSON libraries available that can be used to pass AJAX updates between the server and the client. I am going to use google's gson library in this example. 

Now, let us create a simple JSP page with two drop down lists, one that contains values for countries and the other that is going to be populated with values for states based on the value of country selected in the first drop down list. Whenever the value is selected in the "country" drop down list, the "states" drop down list will be populated with corresponding state values based on the country selected. This has to be done without a page refresh, by making AJAX calls to the servlet on the drop down list change event.

Here are the steps to reproduce in Eclipse,

1. First of all create a "Dynamic Web Project" in Eclipse.
2. Create a new JSP page under "Webcontent" folder and copy paste the below code in it.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AJAX calls to Servlet using JQuery and JSON</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    $(document).ready(function() {
        $('#country').change(function(event) {  
        var $country=$("select#country").val();
           $.get('ActionServlet',{countryname:$country},function(responseJson) {   
            var $select = $('#states');                           
               $select.find('option').remove();                          
               $.each(responseJson, function(key, value) {               
                   $('<option>').val(key).text(value).appendTo($select);      
                    });
            });
        });
    });          
</script>
</head>
<body>
<h1>AJAX calls to Servlet using JQuery and JSON</h1>
Select Country:
<select id="country">
<option>Select Country</option>
<option value="India">India</option>
<option value="US">US</option>
</select>
<br/>
<br/>
Select State:
<select id="states">
<option>Select State</option>
</select>
</body>
</html>


3. Download google's GSON library from here and place it in your project's WEB-INF/lib folder.
4. Create a servlet in the name 'ActionServlet' (since I have used this name in the jquery code above') in the src directory. Copy and paste the below code in the doGet() method of the servlet and add the import statement in the header section of the servlet.


import com.google.gson.Gson;

protected void doGet(HttpServletRequest request,   HttpServletResponse response) throws ServletException, IOException {
String country=request.getParameter("countryname");
Map<String, String> ind = new LinkedHashMap<String, String>();
    ind.put("1", "New delhi");
    ind.put("2", "Tamil Nadu");
    ind.put("3", "Kerala");
    ind.put("4", "Andhra Pradesh");
    
    Map<String, String> us = new LinkedHashMap<String, String>();
    us.put("1", "Washington");
    us.put("2", "California");
    us.put("3", "Florida");
    us.put("4", "New York");
    String json = null ;
    if(country.equals("India")){
     json= new Gson().toJson(ind);   
    }
    else if(country.equals("US")){
     json=new Gson().toJson(us);  
    }
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);     
}

}


In the above code, we create two maps for two countries, and return the one based on the country parameter passed to the servlet in the AJAX call made by the JQuery's get() method. Here we convert the map objects to json strings in order to send the response back to the JSP page.

5. Make sure you have done servlet mapping properly in web.xml file. An example of this is given below,

<servlet>
    <servlet-name>ActionServlet</servlet-name>
    <servlet-class>ajaxdemo.ActionServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ActionServlet</servlet-name>
    <url-pattern>/ActionServlet/*</url-pattern>
</servlet-mapping>

In the above code,'ajaxdemo' is the package name in which I have created the servlet. Replace it with your package structure to make the servlet work properly.



Thats it! You are now all set to run the project with Tomcat. When you run this project, the second drop down list will be populated automatically when you change the value in the first drop down list. 

Output Screenshots:

First drop down list changing,


On selecting 'India' in the first drop down list,


On selecting 'US' in the first drop down list,




Please leave your comments and queries about this post in the comment sections in order for me to improve my writing skills and to showcase more useful posts. 

Tuesday, 10 June 2014

Interview Questions

jdbc Interview Questions and Answers
Jsp Interview Questions and Answers
EJB 3.0 Interview Questions and Answers
corejava Interview Questions and Answers
Servlet Interview Questions and Answers
JMS Interview Questions and Answers
J2ME Interview Questions and Answers
CVS interview questions and answers
JMX interview questions and answers
AWT interview questions and answers
Core Java interview questions and answers
Eclipse interview questions and answers
Hibernate interview questions and answers
IBM WebSphere interview questions and answers
J2ME interview questions and answers
J2SE interview questions and answers
Java Applet interview questions and answers
Java Beans interview questions and answers
Java EJB Programming interview questions and answers
Java Enterprise Edition(J2EE) interview questions and answers
Java JSP Programming interview questions and answers
Java Message Service(JMS) interview questions and answers
Java Networking - Sockets And RMI interview questions and answers
Java Patterns interview questions and answers
Java Security interview questions and answers
Java Servlet Programming interview questions and answers
Java Swing Programming interview questions and answers
Java Threads interview questions and answers
Java interview questions and answers
JBoss interview questions and answers
JDBC interview questions and answers
JMS interview questions and answers
JSF interview questions and answers
RMI interview questions and answers
Spring Framework interview questions and answers
Struts interview questions and answers

Java Enterprise Edition(J2EE) Interview Questions and Answers

 
 

Java Enterprise Edition(J2EE) Interview Questions and Answers

 
 
 
 
 
Download Link

Jsp Interview Questions and Answers

 

JSP Interview Questions and Answers

 
 
 
Download Link
 
 

Servlet Interview Questions and Answers

 

            Servlet Interview Questions and Answers

 
                     

Thursday, 9 January 2014

how to write data into PDF using Servlet

Example to write data into PDF using servlet

Let's see the simple example of writing data into PDF using servlet. In this example, we have mentioned the content type application/pdf that must be specified to display data in the PDF format.
ServletPDF.java
  1. package com.javatpoint;  
  2. import java.io.*;  
  3. import java.util.*;  
  4. import javax.servlet.*;  
  5. import javax.servlet.http.*;  
  6. import com.darwinsys.spdf.PDF;  
  7. import com.darwinsys.spdf.Page;  
  8. import com.darwinsys.spdf.Text;  
  9. import com.darwinsys.spdf.MoveTo;  
  10.   
  11. public class ServletPDF extends HttpServlet {  
  12.   
  13. public void doGet(HttpServletRequest request,  
  14.         HttpServletResponse response) throws IOException {  
  15.   
  16. PrintWriter out = response.getWriter();  
  17. response.setContentType("application/pdf");  
  18.   
  19. response.setHeader("Content-disposition","inline; filename='rajvishwakarma15@blogspot.pdf'");  
  20.   
  21. PDF p = new PDF(out);  
  22. Page p1 = new Page(p);  
  23. p1.add(new MoveTo(p, 200700));  
  24. p1.add(new Text(p, "rajvishwakarma15@blogspot.com"));  
  25. p1.add(new Text(p, "by Raj Vishwakarma"));  
  26.           
  27. p.add(p1);  
  28. p.setAuthor("Ian ");  
  29.   
  30. p.writePDF();  
  31.   
  32. }  
  33. }  

Ref. javatpoint.com

Expression Language (EL) in JSP

Expression Language (EL) in JSP


There are many implicit objects, operators and reserve words in EL.The Expression Language (EL) simplifies the accessibility of data stored in the Java Bean component, and other objects like request, session, application etc.
It is the newly added feature in JSP technology version 2.0.
EL helps you to save your programming time.

Syntax for Expression Language (EL)

  1. ${ expression }  

Implicit Objects in Expression Language (EL)

There are many implicit objects in the Expression Language. They are as follows:
Implicit ObjectsUsage
pageScopeit maps the given attribute name with the value set in the page scope
requestScopeit maps the given attribute name with the value set in the request scope
sessionScopeit maps the given attribute name with the value set in the session scope
applicationScopeit maps the given attribute name with the value set in the application scope
paramit maps the request parameter to the single value
paramValuesit maps the request parameter to an array of values
headerit maps the request header name to the single value
headerValuesit maps the request header name to an array of values
cookieit maps the given cookie name to the cookie value
initParamit maps the initialization parameter
pageContextit provides access to many objects request, session etc.

Simple example of Expression Language that prints the name of the user

In this example, we have created two files index.jsp and process.jsp. The index.jsp file gets input from the user and sends the request to the process.jsp which in turn prints the name of the user using EL.

index.jsp

  1. <form action="process.jsp">  
  2. Enter Name:<input type="text" name="name" /><br/><br/>  
  3. <input type="submit" value="go"/>  
  4. </form>  

process.jsp

  1. Welcome, ${ param.name }  

Example of Expression Language that prints the value set in the session scope

In this example, we printing the data stored in the session scope using EL. For this purpose, we have used sessionScope object.

index.jsp

  1. <h3>welcome to index page</h3>  
  2. <%  
  3. session.setAttribute("user","sonoo");  
  4. %>  
  5.   
  6. <a href="process.jsp">visit</a>  

process.jsp

  1. Value is ${ sessionScope.user }