• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

JSP

What is JavaServer Pages (JSP)?

April 18, 2017 By j2eereference Leave a Comment

What is JavaServer Pages?

JavaServer Pages was launched by Sun Microsystems in the year 1999. JavaServer Pages is called as JSP in short. JSP is an expedient technology that enables the developers to build dynamic web pages. Generally, stand alone Java code is embedded within static HTML page to form JSP. Additional JSP tags will be used to specialise the functionality of a web page. Rather than HTML, JSP pages can also be formed from XML or other document types. JSP files can be deployed and executed with the help of a web server like tomcat.

Why to use JSP?

  • JSP provides significantly enhanced performance since JSP embeds dynamic elements within HTML Pages itself

  • JSP files will always be compiled before it is being handled by the server for further processing

  • JSP are constructed over Java Servlets and they are translated into servlets during execution. Thus, JSP gets access to all the predominant API’s of Enterprise Java, together with EJB, JDBC, JAXP, JNDI, and much more

  • Simple applications can have only JSP pages. Complex applications can have JSP as part of MVC (Model View Controller). In MVC Architecture, JSP acts as a View Component wherein JavaBeans will play the role of a Model and Servlets will be the Controller

  • Most importantly, JSP is a vital portion of J2EE, a complete environment for building enterprise applications. This indicates that JSP can be used in diverse applications ranging from simple straightforward applications to the most complicated and demanding

Sample JSP Page

Here is a simple JSP Page that displays “Have a Great Day” ten times:

J2EEReference.com Sample JSP Page
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>J2EEReference.com Sample JSP Page</title>
</head>
<body>
 
<h1> Sample JSP Page from J2EEReference.com</h1>
 
<% for(int index=0;index<10;index++){ %>
<h5> Have a Great Day!</h5>
<%}%>
 
</body>
</html>

Output of the above program is:

J2EEREFERENCE.COM JSP OUTPUT

Related Posts

  • Differences between Point to Point Messaging Model and Publish Subscribe Messaging Model
  • Point to Point Messaging Model Architecture
  • Publish Subscribe Messaging Model Architecture
  • How JMS is different from RPC?
  • Different types of messages available in JMS API
  • Advantages of Java Message Service (JMS)
  • Java Message Service and JMS Programming Model
  • Java EE or J2EE Architecture

Filed Under: J2EE, JSP Tagged With: JavaServer Pages, JSP

JSP Page Directives

April 24, 2011 By j2eereference

Almost all the JSP file contains the page directive which gives the information to the JSP engine about the entire source file.

Syntax for writing page directives

<% page

[language=” java “]

[extends = “package.class”]

[import={package.class  | package.*}]

[session=”true | false”]

[buffer=”none |8kb |sizekb”]

[autoflush=”true | false”]

[isThreadsafe=”true | false”]

[info=”text”]

[errorPage=”relative URL ”]

[contentType=”mimeType [;charset=characterset] “ | “text/html;charset=ISO-8859-1”]

[iserrorPage=”true | false”]

%>

Below are the attributes used in the page directives.

1.        language=”java”

This specifies the scripting language used in the scriptlets,declarations, expressions in the JSP file. Java is the only allowed value.

2.       extends=”package.class”

This will tell the JSP engine about the classes  which are to be extended in the particular JSP page.

3.       import=”package.class | package.*”

This attribute contains a list of java packages or classes that the JSP should import. More than one package can be imported by using comma separated list.

Below packages are implicitly imported in all the JSP page.

Java.lang.*

Javax.servlet.*

Javax.servlet.jsp.*

Javax.servlet.http.*

4.       session=”true | false”

This attribute specifies whether the client must join as Http session in order to use the JSP page. If the value is true , the session object refers to the current  or new session.  The default value is true.

5.       buffer=”none|8kb|sizekb”

This attribute specifies the buffer size in kilobytes used by the out object to handle output sent from the compiled JSP page to the client web browser. The default value is 8 kb . If you specify the buffer size,the output is buffered with the size specified .

6.       autoFlush=”true|false”

This attribute specifies whether the buffered output should be flushed automatically when the buffer is full. The default value is true. If it is set to true the buffer will be flushed otherwise , an exception will be raised when the buffer overflows.

7.       isThreadSafe=”true|false”

this attribute specifies whether the thread safety is implemented in the JSP file or  not. The default value is true.which means the JSP container can send multiple, concurrent client request to the JSP page.

8.       info=”text”

This specifies a text string that is incorporated into the compiled JSP page. This can be retrieved using the Servlet.getServletInfo() method.

9.       errorPage=”relativeURL”

This attribute specifies the pathname to a JSP file to where it has to send the exception.

10.   isErrorPage=”true|false”

this specifies the whether this JSP file display an error page. If set to true you can use the exception object in the JSP file . The default value is false.

11.   contentType=”mimeType [;charset=characterset] “ | “text/html;charset=ISO-8859-1”

The default mime type is text/html and the default character set is ISO-8859-1.

Filed Under: JSP

JSP FAQ

January 4, 2011 By j2eereference Leave a Comment

What is a scriptlet?

A scriptlet contains Java code that is executed every time a JSP is invoked. When a JSP is translated to a servlet, the scriptlet code goes into the service() method. Hence, methods and variables written in scriptlets are local to the service() method. A scriptlet is written between the  <% and %> tags and is executed by the container at request processing time.

What are JSP declarations?

JSP declarations are used to declare class variables and methods in a JSP page. They are initialized when the class is initialized. Anything defined in a declaration is available for the whole JSP page. A declaration block is enclosed between the <%! and %> tags. A declaration is not included in the service() method when a JSP is translated to a servlet.

What is a JSP expression?

A JSP expression is used to write an output without using the out.print statement. It can be said as a shorthand representation for scriptlets. An expression is written between the  <%= and %>tags. It is not required to end the expression with a semicolon, as it implicitly adds a semicolon to all the expressions within the expression tags.

Can we implement an interface in a JSP?

No.We cannot implement an interface in JSP

What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?

request.getRequestDispatcher(path): We need to give the relative path of the resource.

context.getRequestDispatcher(path): We need to give the absolute path of the resource.

How to implement a thread-safe JSP page?

JSPs can be made thread-safe by having them implement the SingleThreadModel interface by using <%@ page isThreadSafe=”false” %> directive in the page.

Difference between the session and cookie?

Sessions are always stored in the server side whereas cookies are always stored in the client side.

Difference between <%@include:> and <jsp:include> ?

Both are used to insert files into a JSP page.
<%@include:> is a directive which statically inserts the file at the time the JSP page is translated into a servlet.
<jsp:include> is an action which dynamically inserts the file at the time the page is requested.

Difference between forward and sendRedirect ?

Both requestDispatcher.forward() and response.sendRedirect() is used to redirect to new url. forward is an internal redirection of user request within the web container to a new URL without the knowledge of the user. The request object and the http headers remain same.  But sendRedirect is normally an external redirection of user request outside the web container. sendRedirect sends response header back to the browser with the new URL. The browser send the request to the new URL with fresh http headers.

How can we open excel documents from JSP ? 

Need to add Page directive with attribute contentType:
<%@ page contentType=”application/vnd.ms-excel” %>

How can we open word documents from JSP ? 

Add Page directive with attribute contentType:
<%@ page contentType=”application/msword” %>

How does JSP handle run-time exceptions?

 You can use the errorPage attribute of the page directive to handle run-time exceptions which automatically get  forwarded to the error page.

 For example:

<%@ page errorPage=”error.jsp” %>
If JSP page catch any run time exception redirects the browser to the JSP page which we have defined as error.jsp

How to prevent the output of the JSP from being cached by the browser?

You need to set the HTTP header attributes to prevent the output by the JSP page from being cached by the browser

<%
response.setHeader(“Cache-Control”,”no-store”); //HTTP 1.1
response.setHeader(“Pragma”,”no-cache”); //HTTP 1.0
%>

What are the implicit objects?

Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are:

–request
–response
–pageContext
–session
–application
–out
–config
–page
–exception

 What are the JSP scripting elements ? 

There are three scripting language elements:

declarations.

scriptlets.

 expressions.

How to prevent creating Session in the JSP page ?

<%@ page session=”false”>
By default, a JSP page will automatically create a session.

How to include static files within a JSP page ?

You can include static pages in the JSP page using the below code.
<%@ include file=”header.jsp” %>
or
<%@ include file=”footer.html” %>

Filed Under: JSP

JSP Quiz

January 3, 2011 By j2eereference Leave a Comment




 

JSP Quiz

This is the JSP Quiz Page.
Start
Congratulations - you have completed JSP Quiz. You scored %%SCORE%% out of %%TOTAL%%. Your performance has been rated as %%RATING%%
Your answers are highlighted below.
Question 1
What is the output of the following code? <% session.setAttribute("name", "John"); %> <%= session.getAttribute("John") %>
A
John
B
null
Question 2
What is the signature of method jspInit of JspPage?
A
void jspInit()
B
void jspInit(HttpServletRequest, HttpServletResponse) throws IOException, ServletException
C
void jspInit(HttpServletRequest, HttpServletResponse)
Question 3
Which statements is incorrect?
A
HttpServlet.init() throws ServletException
B
HttpServlet.destroy() throws ServletException
C
HttpServlet.service() thrwos ServletException and IOException
Question 4
The methods jspInit and jspDestroy of JspPage may be overriden by a JSP author
A
True
B
False
Question 5
JavaServer Pages are processed by ?
A
IIS
B
Web Server
C
JSP Container
D
The asp.dll component
Question 6
When a JSP is executed, of the following, what is most likely to be sent to the client ?
A
The source JSP file
B
HTML
C
The source Servlet file
D
The compiled Servlet file
Question 7
What is the return type of the getLastModified method of HttpServlet?
A
java.util.Date
B
int
C
long
D
java.sql.Date.
Question 8
What is the output of the following code? <% session.setAttribute("name", "John"); %> <%= session.getAttribute("name") %>
A
null
B
John
Question 9
What is the signature of method _jspService of HttpJspPage?
A
void _jspService(HttpServletRequest, HttpServletResponse)
B
void _jspService(HttpServletRequest, HttpServletResponse) throws IOException, ServletException
C
void _jspService()
Question 10
JavaServer Pages are processed by software on the ?
A
Servver
B
Client
Question 11
The method _jspService of HttpJspPage should not be overriden by a JSP author
A
True
B
False
Question 12
What is the signature of method jspDestroy of JspPage?
A
void jspDestroy(HttpServletRequest, HttpServletResponse)
B
void jspDestroy(HttpServletRequest, HttpServletResponse) throws IOException, ServletException
C
void jspDestroy()
Question 13
Which one of the following is a valid argument for a JSP page directive?
A
caching="sizekb|none"
B
extender="package.class"
C
contentType="text/html"
D
importer="package.class"
E
isThreadSafe="yes|no"
Once you are finished, click the button below. Any items you have not completed will be marked incorrect. Get Results
There are 13 questions to complete.
←
List
→
Return
Shaded items are complete.
12345
678910
111213End
Return
You have completed
questions
question
Your score is
Correct
Wrong
Partial-Credit
You have not finished your quiz. If you leave this page, your progress will be lost.
Correct Answer
You Selected
Not Attempted
Final Score on Quiz
Attempted Questions Correct
Attempted Questions Wrong
Questions Not Attempted
Total Questions on Quiz
Question Details
Results
Date
Score
Hint
Time allowed
minutes
seconds
Time used
Answer Choice(s) Selected
Question Text
All done
Need more practice!
Keep trying!
Not bad!
Good work!
Perfect!


Filed Under: JSP

JSP Elements

December 30, 2010 By j2eereference 1 Comment

JSP Scripting is a mechanism for embedding code fragments directly into an HTML page.There are three types of scriptlets

Scriptlets, Expression and Declaration.

JSP Scriptlets

Scriptlets are used to embed any piece of java code into the page.

the syntax for a scriptlet is as follows

<%   Scriptlet  %>

Scrptlets will get executed at the the time of request.

writing a simple JSP page using Scriptlets

<html>

<head><title>Hellow world</title></head>

<body>

<%

out.println(“This is  for scritplet sample”);

%>

</body>

</html>

 

JSP Expression

Expressions are used to dynamically calculate values to be inserted direcly into the JSp page.These are the elements that are evaluated with the result being converted to Java.lang.String. After the string is converted,it is written to out object. The expression should be enclosed within <%= and %> 

while writing expression semicolon cananot be used to end the expression.

Expression format is as follows

<%= Java Expression %>

 Sample  JSP code using Expression

html>
   <head>
   <title>JSP Expression </title>
   </head>
   <body>
   <p> <%= 5+5 %><br>                                                                                                   // This will display 10
     <%= (2*3) + (3+3) %><br>                                                                                       // This will display 12
   <%= “Some text ” + (3*3) + (3+3) %><br>                                                          // This will display Some text 96
    Add a string? <%= “Some text ” + ((3*3) + (3+3)) %><br>                         // This will display Some text15

  </p></body>
</html>

JSP Declarations

JSP declarations are uesd to define methods or variables that are to be used in the java code later in the JSP file. The declaration get inserted into main body of the servlet class. It has the following form .

<%! declaration %>

example :  <%! int i=0 %>

JSP Comments

There are two types of comments that can  be embedded in a JSP page

1. HTML Commnet

This comment can be viewed fromt he page source from the web browser.

<% —    Comment     –>

A JSP comment may also contain expression.The following example uses an expression to display the surrent date on the source page

<!– Current date is <%= (new java.util.date()).toLocaleString() %> –>

This will display the the following on the screen

<!– Current date is April 19 ,2011 –>

2. Hidden comment 

If you use hidden comment , comments are not sent to the client .The syntax for writing the hidden comment is as follows

<%–   Comments    –%>

Filed Under: JSP

JSP Life Cycle

December 30, 2010 By j2eereference 1 Comment

JSP Compilation:

When a request comes for a JSP, the JSP engine first checks whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.

JSP compilation involves three steps:

1) Parsing the JSP.

2) Converting JSP to a servlet.

3) Compiling the servlet.

1)     Initialize –  jspInit()

After compiling and loading the JSP page  it invokes the jspInit() method before servicing any requests. You can override the jspInit() method if there is any specific need for initializing your JSP.

public void jspInit(){

// Your Initialization code here.

}

 2)    service – jspService()

This is the next step after initialization of JSP . The _jspService() method takes HttpServletRequest and HttpServletResponse as its parameters as follows:

void _jspService(HttpServletRequest request, HttpServletResponse response) {

// Your code for handling service

}

  3)   Complete – jspDestroy()

The jspDestroy() method is the JSP equivalent of the destroy method for servlets. You can Override jspDestroy if you need to perform any cleanup, such as releasing database connections.

public void jspDestroy(){

// Your cleanup code goes here.

} 

Filed Under: JSP

JSP Introduction

December 30, 2010 By j2eereference Leave a Comment

What is JSP (Java Server Page) ?

         JSP is a standard component of J2EE which is an extension to Servlet to generate dynamic web pages.  JSP defines some specialized tags to  to embed Java code  within HTML. JSP is the combination of  Static HTML and Dynamically Generated Content using Java technology.  The suffix ends with .jsp to indicate the web server that the file is a JSP file.

Advantages of using JSP over Servlet

1)  Effective way for generating dynamic HTML.

2)  JSPs automatically get compiled to servlets and execute on the Web Server.

3) JSP compilation happens only if there is any change in the JSP source.

4)  JSP is faster and easier for editing.

5) JSP  Separates the graphical design from the dynamic content

6)  Write Once run anywhere.

Filed Under: JSP

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.