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
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.
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)
${ expression }
Implicit Objects in Expression Language (EL)
There are many implicit objects in the Expression Language. They are as follows:
Implicit Objects
Usage
pageScope
it maps the given attribute name with the value set in the page scope
requestScope
it maps the given attribute name with the value set in the request scope
sessionScope
it maps the given attribute name with the value set in the session scope
applicationScope
it maps the given attribute name with the value set in the application scope
param
it maps the request parameter to the single value
paramValues
it maps the request parameter to an array of values
header
it maps the request header name to the single value
headerValues
it maps the request header name to an array of values
cookie
it maps the given cookie name to the cookie value
initParam
it maps the initialization parameter
pageContext
it 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
<form action="process.jsp">
Enter Name:<input type="text" name="name" /><br/><br/>
Example of Downloading file from the server using JSP
In this example, we are going to download the jsp file. But you may download any file. For downloading the file from the server, you should specify the content type named APPLICATION/OCTET-STREAM.
index.jsp
This file provides a link to download the jsp file.
<a href="download.jsp">download the jsp file</a>
download.jsp
In this example, we are downloading the file home.jsp which is located in the e: drive. You may change this location accordingly.
This tutorial shows how to handle cookies in JSP pages. In this tutorial you will learn how to add cookies through jsp page and then show the value of the same cookie in another JSP page.
Let's understand the cookies. Cookies are short pieces of data sent by web servers to the client browser. The cookies are saved to clients hard disk in the form of small text file. Cookies helps the web servers to identify web users, by this way server tracks the user. Cookies pay very important role in the session tracking.
Cookie Class
In JSP cookie are the object of the class javax.servlet.http.Cookie. This class is used to creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.
The getCookies() method of the request object returns an array of Cookie objects. Cookies can be constructed using the following code:
Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.
getMaxAge()
Returns the maximum specified age of the cookie.
getName()
Returns the name of the cookie.
getPath()
Returns the prefix of all URLs for which this cookie is targeted.
getValue()
Returns the value of the cookie.
setComment(String)
If a web browser presents this cookie to a user, the cookie's purpose will be described using this comment.
setMaxAge(int)
Sets the maximum age of the cookie. The cookie will expire after that many seconds have passed. Negative values indicate the default behavior: the cookie is not stored persistently, and will be deleted when the user web browser exits. A zero value causes the cookie to be deleted
setPath(String)
This cookie should be presented only with requests beginning with this URL.
setValue(String)
Sets the value of the cookie. Values with various special characters (white space, brackets and parentheses, the equals sign, comma, double quote, slashes, question marks, the "at" sign, colon, and semicolon) should be avoided. Empty values may not behave the same way on all browsers.
Example Using Cookies
No we will write code in JSP file to set and then display the cookie.
Create Form
Here is the code of the form (cookieform.jsp) which prompts the user to enter his/her name.
Above form prompts the user to enter the user name. User input are posted to the setcookie.jsp file, which sets the cookie. Here is the code of setcookie.jsp file:
This JSP Tutorial shows you how to track the session between different JSP pages. In any web application user moves from one page to another and it becomes necessary to track the user data and objects throughout the application. JSP provide an implicit object "session", which can be use to save the data specific the particular to the user.
In this tutorial we will create an application that takes the user name from the user and then saves into the user session. We will display the saved data to the user in another page.
Here is the code of the JSP file (savenameform.jsp) that takes the input from user:
The above page prompts the user to enter his/her name. Once the user clicks on the submit button, savenametosession.jsp is called. The JSP savenametosession.jsp retrieves the user name from request attributes and saves into the user session using the functionsession.setAttribute("username",username);. Here is the code of savenametosession.jsp:
<html>
<head>
<title>Name Saved</title>
</head>
<body>
<p><a href="showsessionvalue.jsp">Next Page to view the session value</a><p>
</body>
The above JSP saves the user name into the session object and displays a link to next pages (showsessionvalue.jsp). When user clicks on the "Next Page to view session value" link, the JSP pageshowsessionvalue.jsp displays the user name to the user. Here is the code of showsessionvalue.jsp:
A JSP can be used with an HTML form tag to allow users to upload files to the server. An uploaded file could be a text file or binary or image file or any document.
Creating a File Upload Form:
The following HTM code below creates an uploader form. Following are the important points to be noted down:
The form method attribute should be set to POST method and GET method can not be used.
The form enctype attribute should be set to multipart/form-data.
The form action attribute should be set to a JSP file which would handle file uploading at backend server. Following example is using uploadFile.jsp program file to upload file.
To upload a single file you should use a single <input .../> tag with attribute type="file". To allow multiple files uploading, include more than one input tags with different values for the name attribute. The browser associates a Browse button with each of them.
<html><head><title>File Uploading Form</title></head><body><h3>File Upload:</h3>
Select a file to upload: <br/><formaction="UploadServlet"method="post"enctype="multipart/form-data"><inputtype="file"name="file"size="50"/><br/><inputtype="submit"value="Upload File"/></form></body></html>
This will display following result which would allow to select a file from local PC and when user would click at "Upload File", form would be submitted along with the selected file:
FileUpload:Select a file to upload:
NOTE: Above form is just dummy form and would not work, you should try above code at your machine to make it work.
Writing Backend JSP Script:
First let us define a location where uploaded files would be stored. You can hard code this in your program or this directory name could also be added using an external configuration such as a context-param element in web.xml as follows:
<web-app>
....
<context-param><description>Location to store uploaded file</description><param-name>file-upload</param-name><param-value>
c:\apache-tomcat-5.5.29\webapps\data\
</param-value></context-param>
....
</web-app>
Following is the source code for UploadFile.jsp which can handle multiple file uploading at a time. Before proceeding you have make sure the followings:
Following example depends on FileUpload, so make sure you have the latest version ofcommons-fileupload.x.x.jar file in your classpath. You can download it fromhttp://commons.apache.org/fileupload/.
FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jar file in your classpath. You can download it from http://commons.apache.org/io/.
While testing following example, you should upload a file which has less size than maxFileSizeotherwise file would not be uploaded.
Make sure you have created directories c:\temp and c:\apache-tomcat-5.5.29\webapps\data well in advance.
<%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %>
<%File file ;int maxFileSize =5000*1024;int maxMemSize =5000*1024;ServletContext context = pageContext.getServletContext();String filePath = context.getInitParameter("file-upload");// Verify the content typeString contentType = request.getContentType();if((contentType.indexOf("multipart/form-data")>=0)){DiskFileItemFactory factory =newDiskFileItemFactory();// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);// Location to save data that is larger than maxMemSize.
factory.setRepository(newFile("c:\\temp"));// Create a new file upload handlerServletFileUpload upload =newServletFileUpload(factory);// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );try{// Parse the request to get file items.List fileItems = upload.parseRequest(request);// Process the uploaded file itemsIterator i = fileItems.iterator();out.println("<html>");out.println("<head>");out.println("<title>JSP File upload</title>");out.println("</head>");out.println("<body>");while( i.hasNext ()){FileItemfi=(FileItem)i.next();if(!fi.isFormField ()){// Get the uploaded file parametersString fieldName =fi.getFieldName();String fileName =fi.getName();boolean isInMemory =fi.isInMemory();long sizeInBytes =fi.getSize();// Write the fileif( fileName.lastIndexOf("\\")>=0){
file =newFile( filePath +
fileName.substring( fileName.lastIndexOf("\\")));}else{
file =newFile( filePath +
fileName.substring(fileName.lastIndexOf("\\")+1));}fi.write( file );out.println("Uploaded Filename: "+ filePath +
fileName +"<br>");}}out.println("</body>");out.println("</html>");}catch(Exception ex){System.out.println(ex);}}else{out.println("<html>");out.println("<head>");out.println("<title>Servlet upload</title>");out.println("</head>");out.println("<body>");out.println("<p>No file uploaded</p>");out.println("</body>");out.println("</html>");}
%>
Now try to upload files using the HTML form which you created above. When you would try http://localhost:8080/UploadFile.htm, it would display following result which would help you uploading any file from your local machine.
FileUpload:Select a file to upload:
If your JSP script works fine, your file should be uploaded in c:\apache-tomcat-5.5.29\webapps\data\ directory.