Search This Blog

Showing posts with label JSP. Show all posts
Showing posts with label JSP. 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

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
 
 

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, 200, 700));  
  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 }  

Example of Downloading file from the server using JSP

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.
  1. <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.
  1. <%    
  2.   String filename = "home.jsp";   
  3.   String filepath = "e:\\";   
  4.   response.setContentType("APPLICATION/OCTET-STREAM");   
  5.   response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");   
  6.   
  7.   java.io.FileInputStream fileInputStream=new java.io.FileInputStream(filepath + filename);  
  8.             
  9.   int i;   
  10.   while ((i=fileInputStream.read()) != -1) {  
  11.     out.write(i);   
  12.   }   
  13.   fileInputStream.close();   
  14. %>   



Ref. Javatpoint.com

JSP Cookies

JSP Cookies Example
         
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:
Cookie(java.lang.String name, java.lang.String value)
Cookie objects have the following methods.
Method
Description
getComment()
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.
<%@ page language="java" %>
<html>
<head>
<title>Cookie Input Form</title>
</head>
<body>
<form method="post" action="setcookie.jsp">
<p><b>Enter Your Name: </b><input type="text" name="username"><br>
<input type="submit" value="Submit">

</form>

</body>
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:
<%@ page language="java" import="java.util.*"%>
<%
String username=request.getParameter("username");
if(username==null) username="";


Date now = new Date();
String timestamp = now.toString();
Cookie cookie = new Cookie ("username",username);
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);


%>

<html>
<head>
<title>Cookie Saved</title>
</head>
<body>
<p><a href="showcookievalue.jsp">Next Page to view the cookie value</a><p>

</body>
Above code sets the cookie and then displays a link to view cookie page. Here is the code of display cookie page (showcookievalue.jsp):
<%@ page language="java" %>
<%
String cookieName = "username";
Cookie cookies [] = request.getCookies ();
Cookie myCookie = null;
if (cookies != null)
{
for (int i = 0; i < cookies.length; i++)
{
if (cookies [i].getName().equals (cookieName))
{
myCookie = cookies[i];
break;
}
}
}

%>
<html>
<head>
<title>Show Saved Cookie</title>
</head>
<body>


<%
if (myCookie == null) {
%>
No Cookie found with the name <%=cookieName%>
<%
} else {
%>
<p>Welcome: <%=myCookie.getValue()%>.
<%
}
%>
</body>
When user navigates to the above the page, cookie value is displayed.

JSP Session

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:
<%@ page language="java" %>
<html>
<head>
<title>Name Input Form</title>
</head>
<body>
<form method="post" action="savenametosession.jsp">
<p><b>Enter Your Name: </b><input type="text" name="username"><br>
<input type="submit" value="Submit">

</form>

</body>
 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:
<%@ page language="java" %>
<%
String username=request.getParameter("username");
if(username==null) username="";

session.setAttribute("username",username);
%>

<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:
<%@ page language="java" %>
<%
String username=(String) session.getAttribute("username");if(username==null) username="";
%>
<html>
<head>
<title>Show Saved Name</title>
</head>
<body>
<p>Welcome: <%=username%><p>

</body>
The function session.getAttribute("username") is used to retrieve the user name saved in the session.

Wednesday, 8 January 2014

File Upload in 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 />
<form action="UploadServlet" method="post"
                        enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="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:
 
File Upload: 
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 type
   String contentType = request.getContentType();
   if ((contentType.indexOf("multipart/form-data") >= 0)) {

      DiskFileItemFactory factory = new DiskFileItemFactory();
      // maximum size that will be stored in memory
      factory.setSizeThreshold(maxMemSize);
      // Location to save data that is larger than maxMemSize.
      factory.setRepository(new File("c:\\temp"));

      // Create a new file upload handler
      ServletFileUpload upload = new ServletFileUpload(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 items
         Iterator 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 () ) 
         {
            FileItem fi = (FileItem)i.next();
            if ( !fi.isFormField () ) 
            {
            // Get the uploaded file parameters
            String fieldName = fi.getFieldName();
            String fileName = fi.getName();
            boolean isInMemory = fi.isInMemory();
            long sizeInBytes = fi.getSize();
            // Write the file
            if( fileName.lastIndexOf("\\") >= 0 ){
            file = new File( filePath + 
            fileName.substring( fileName.lastIndexOf("\\"))) ;
            }else{
            file = new File( 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.
 
File Upload: 
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.

Ref. => javatpoint.com