Create First JSP Page:
In this Topic you will learn how to create your first page and then run on the
Tomcat Server. Tomcat server is one of the most popular Servlet Container for
deploying and running the Java based application. In this topic you will learn
how to make your web application and run on Tomcat Server.
Java Server Pages is simple text file with .jsp extension and it contains HTML
code along with embedded Java Code. JSP file is compiled into Servlet and then
run on the Tomcat. Tomcat server automatically compiles the JSP file into
Servlet.
Adding Java code into JSP Page:
Three types of tags can be used to add the code into JSP page. These are:
JSP Scriptlet
JSP expression
JSP declaration
In the topic we will use the JSP expression for adding the Java code.
Here is the first JSP code:
<html> <head> <title>my First JSP page.</title> </head> <body> <p align="center"><font color="#FF00ff" size="6"><%="hello java"%></font></p> <p align="center"><font color="#800ff" size="6"><%="Hello JSP"%> </font></p> </body> </html> |
Create the above file and save as "index.jsp" file.
Next step is to create the web application and then deploy on the Tomcat Server.
Above example code display the "hello java" and "Hello JSP" on the browser. You
can click on the following URL to run the example online on our server.
Execute the example.
To deploy and run the JSP application we need the Tomcat server.
To deploy the web application on Tomcat Server you can use any one of the
following techniques:
Create war file and deploy on Tomcat manually
Use the Eclipse for creating web application and then automatically running on
Tomcat
Create war file from Eclipse and then deploy on Tomcat
Let me explain you how to create war file manually and deploy on Tomcat
Go to any directory of your hard disk and then create a directory "myjsp", in my
computer we are using the "D:\examples\javanote\webapp\myjsp" directory.
Now create the following directory Structure:
Directory Structure of Web Application
/myjsp/
index.jsp
WEB-INF
web.xml
classes
lib
You should save the "index.jsp" file into the root of the web application
as shown above.
You should add the following code in the web.xml file:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>my First JSP</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> |
Now to build the war file you should use the following
command:
Go to the directory "D:\examples\javanote\webapp\myjsp" and then use the
following command to create the war file:
jar -cvf ../myjsp.war *
Here is the output of the above command:
D:\examples\javanote\webapp\myjsp>jar -cvf ../myjsp.war *
added manifest:
adding: index.jsp(in = 253) (out= 156)(deflated 38%)
adding: WEB-INF/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/classes/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/lib/(in = 0) (out= 0)(stored 0%)
adding: WEB-INF/web.xml(in = 487) (out= 247)(deflated 49%)
D:\examples\javanote\webapp\myjsp>
Now to deploy the application copy the myjsp.war into the webapps directory of
the Tomcat and then start the Tomcat. now you see the output of your system.
Set a cookie and delete a cookie from within a JSP page:
A cookie, mycookie, can be deleted using the following scriptlet:
<%
//creating a cookie
Cookie mycookie = new Cookie("Name","aValue");
response.addCookie(mycookie);
//delete a cookie
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);
%>
Dose JSP handle run-time exceptions:
You can use the errorPage attribute of the page directive to have uncaught
run-time exceptions automatically forwarded to an error processing page.
For example:
<%@ page errorPage=\"error.jsp\" %> redirects the browser to the JSP page
error.jsp if an uncaught exception is encountered during request processing.
Within error.jsp, if you indicate that it is an error-processing page, via the
directive: <%@ page isErrorPage=\"true\" %> Throwable object describing
the exception may be accessed within the error page via the exception implicit
object. Note: You must always use a relative URL as the value for the errorPage
attribute.
Implement a thread-safe JSP page, What are the advantages and Disadvantages
of using it:
You can make your JSPs thread-safe by having them implement the
SingleThreadModel interface. This is done by adding the directive <%@ page
isThreadSafe="false" %> within your JSP page. With this, instead of a single
instance of the servlet generated for your JSP page loaded in memory, you will
have N instances of the servlet loaded and initialized, with the service method
of each instance effectively synchronized. You can typically control the number
of instances (N) that are instantiated for all servlets implementing
SingleThreadModel through the admin screen for your JSP engine. More
importantly, avoid using the tag for variables. If you do use this tag, then you
should set isThreadSafe to true, as mentioned above. Otherwise, all requests to
that page will access those variables, causing a nasty race condition.
SingleThreadModel is not recommended for normal use. There are many pitfalls,
including the example above of not being able to use <%! %>. You should try
really hard to make them thread-safe the old fashioned way: by making them
thread-safe
Difference between variable declared inside a
declaration part and variable declared in scriplet part:
Variable declared inside declaration part is treated as a global variable.that
means after convertion jsp file into servlet that variable will be in outside of
service method or it will be declared as instance variable.And the scope is
available to complete jsp and to complete in the converted servlet class.where
as if u declare a variable inside a scriplet that variable will be declared
inside a service method and the scope is with in the service method.
Implicit objects & List them:
Certain objects that are available for the use in JSP documents without being
declared first. These objects are parsed by the JSP engine and inserted into the
generated servlet. The implicit objects are listed below:
a)request
b)response
c)pageContext
d)session
e)application
f)out
g)config
h)page
i)exception
Difference between custom JSP tags and JavaBeans:
In the context of a JSP page, both accomplish similar goals but the differences
are:
custom tags | javabeans |
Can manipulate JSP content | Can't manipulate JSP content |
Custom tags can simplify the complex operations much better than the bean can. But require a bit more work to set up | . Easier to set up |
Used only in JSPs in a relatively self-contained manner. Can be used in both Servlets and JSPs. | You can define a bean in one Servlet and use them in another Servlet or a JSP page. |
JavaBeans declaration and usage example:
<jsp:useBean id="identifier" class="packageName.className"/> <jsp:setProperty name="identifier" property="classField" value="someValue" /> <jsp:getProperty name="identifier" property="classField" /> <%=identifier.getclassField() %> |
Use comments within a JSP page:
You can use “JSP-style” comments to selectively block out code while debugging
or simply to comment your scriptlets. JSP comments are not visible at the
client.
For example:
<%-- the scriptlet is now commented out
<%
out.println("Hello java");
%>
--%>
You can also use HTML-style comments anywhere within your JSP page. These
comments are visible at the client. For example:
<!-- (c) 2004 -->
Of course, you can also use comments supported by your JSP scripting language
within your scriptlets. For example, assuming Java is the scripting language,
you can have:
<%
//some comment
/**
yet another comment
**/
%>
Can my JSP page communicate with an EJB Session Bean:
The following is a code snippet that demonstrates how a JSP page can interact
with an EJB session bean:
<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>
<%!
//declare a "global" reference to an instance of the home interface of the session bean
AccountHome accHome=null;
public void jspInit() {
//obtain an instance of the home interface
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
} %>
<%
//instantiate the session bean
Account acct = accHome.create();
//invoke the remote methods
acct.doWhatever(...);
// etc etc...
%>
JSP lifecycle methods can I override:
You cannot override the jspService() method
within a JSP page. You can however, override the jspInit() and
jspDestroy() methods within a JSP page. jspInit() can be useful for
allocating resources like database connections, network connections, and so
forth for the JSP page. It is good programming practice to free any allocated
resources within jspDestroy().
How can we avoid direct access of JSP pages from client browser?
We know that anything inside WEB-INF directory can’t be accessed directly in web
application, so we can place our JSP pages in WEB-INF directory to avoid direct
access to JSP page from client browser. But in this case, we will have to
configure it in deployment descriptor just like Servlets.
Sample configuration is given below code snippet of web.xml file.
<servlet>
<servlet-name>jspTest</servlet-name>
<jsp-file>/WEB-INF/test.jsp</jsp-file>
<init-param>
<param-name>jsptest</param-name>
<param-value>jspTest Value</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>jspTest</servlet-name>
<url-pattern>/jspTest.do</url-pattern>
</servlet-mapping>
Differentiate between GET and POST:
When you use GET, the entire form submission gets encapsulated in one
URL. The query length is limited to 260 characters, not secure, faster,
quick
and easy.
When you use POST your name/value pairs inside the body of the HTTP
request, which makes a cleaner URL. It imposes no size limitations on the
form's output. It is used to send a large amount of data to the server to be
processed. It is comparatively more versatile and secure.
Autoflush:
This command is used to autoflush the contents. If a value of true is used it
indicates to flush the buffer whenever it is full. In case of false it indicates
that an exception should be thrown whenever the buffer is full. If you are
trying to access the page at the time of conversion of a JSP into servlet will
result in error.
Different scopes available for JSPs:
There are four types of scopes are allowed in the JSP listed below.
1. page - with in the same page
2. request - after forward or include also you will get the request scope
data.
3. session - after senRedirect also you will get the session scope data.
All data stored in session is available to end user till session closed or
browser closed.
4. application - Data will be available throughout the application. One
user can store data in application scope and other can get the data from
application scope.
In JSPs how many ways are possible to perform inclusion?
We can perform inclusion In JSP, in the following ways.
By include directive:
<%@ include file=”header.jsp” %>
The content of the header.jsp will be included in the current jsp at translation
time. Hence this inclusion is also known as static include.
By include action:
<jsp:include page=”header.jsp” />
The response of the jsp will be included in the current page response at request
processing time(run time) hence it is also known as dynamic include.
by using pageContext implicit object
<%
pageContext.include(“/header.jsp”);
%>
This inclusion also happened at request processing time(run time).
by using RequestDispatcher object
<%
RequestDispatcher rd = request.getRequestDispatcher(“/header.jsp”);
Rd.incliude(request,response);
%>
EL :
EL stands for expression language. An expression language makes it possible to
easily access application data.In the below expression amountofwine variable
value will be rendered.
There are ${amount} litres of milk in the bottle.
EL search for an attribute:
EL parser searches the attribute in following order:
Page
Request
Session (if it exists)
Application
If no match is found for then it displays empty string.
Types of JSTL tags:
Based on the JSTL functions, they are categorized into five types.
1)Core Tags – Core tags provide support for iteration, conditional logic,
catch exception, url, forward or redirect response etc.
2)Formatting and Localization Tags – These tags are provided for
formatting of Numbers, Dates and i18n support through locales and resource
bundles.
3)SQL Tags – JSTL SQL Tags provide support for interaction with
relational databases such as Oracle, MySql etc.
4)XML Tags – XML tags are used to work with XML documents such as parsing
XML, transforming XML data and XPath expressions evaluation.
5)JSTL Functions Tags – JSTL tags provide a number of functions that we
can use to perform common operation, most of them are for String manipulation
such as String Concatenation, Split String etc.