Bca It Chap3
Bca It Chap3
-side programming technology that enables the
creation of dynamic, platform-independent method for building
Web-based applications.
JDBC API to access enterprise databases.
Webpages that supports dynamic content.
ages by
making use of special JSP tags, most of which start with <% and
end with %>.
designed to fulfill the role of a user interface for a Java web
application.
as text files that combine HTML or
XHTML code, XML elements, and embedded JSP actions and
commands.
forms, present records from a database or another source, and
create Webpages dynamically.
information from a database or registering user preferences,
accessing JavaBeans components, passing control between pages,
and sharing information between requests, pages etc.
1
J2EE
SERVLET JSP
Writing code for servlet is harder than JSP JSP is easy to code as it is java in html.
as it is html in java.
Servlet plays a controller role in MVC JSP is the view in MVC approach for
Servlet is faster than JSP. JSP is slower than Servlet because the
then compile.
Servlet can accept all protocol requests. JSP only accept http requests.
In Servlet, we can override the service() In JSP, we cannot override its service()
method. method.
like business logic and presentation logic in presentation logic by using javaBeans.
2
J2EE
task because it includes reloading, click the refresh button.
JSP Processing
3
J2EE
web server.
servlet content.
4
J2EE
5
J2EE
Syntax of JSP Directive
<%@ directive attribute="value" %>
1. JSP page directive
The page directive defines attributes that apply to an entire JSP page.
Syntax of JSP page directive
<%@ page attribute="value" %>
Attributes of JSP page directive
import
contentType
extends
info
buffer
language
isELIgnored
isThreadSafe
autoFlush
session
pageEncoding
errorPage
isErrorPage
1)import
6
J2EE
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail
Extension) type of the HTTP response.The default value is
"text/html;charset=ISO-8859-1".
Example of contentType attribute
<html>
<body>
<%@ page contentType=application/msword %>
Today is: <%= new java.util.Date() %>
</body>
</html>
3)extends
The extends attribute defines the parent class that will be inherited by
the generated servlet.It is rarely used.
4)info
This attribute simply sets the information of the JSP page which is
retrieved later by using getServletInfo() method of Servlet interface.
Example of info attribute
7
J2EE
<html>
<body>
<%@ page info="created by computer student " %>
Today is: <%= new java.util.Date() %>
</body>
</html>
5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output
generated by the JSP page.The default size of the buffer is 8Kb.
6)language
The language attribute specifies the scripting language used in the JSP
page. The default value is "java".
7)isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored
attribute. By default its value is false i.e. Expression Language is
enabled by default. We see Expression Language later.
8)isThreadSafe
8
J2EE
Servlet and JSP both are multithreaded.If you want to control this
behaviour of JSP page, you can use isThreadSafe attribute of page
directive.The value of isThreadSafe value is true.If you make it false, the
web container will serialize the multiple requests,
9)errorPage
The errorPage attribute is used to define the error page, if exception
occurs in the current page, it will be redirected to the error page.
Example of errorPage attribute
//index.jsp
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
</body>
</html>
10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the
error page.
2.include directive
The include directive is used to include the contents of any
resource it may be jsp file, html file or text file.
The include directive includes the original content of the included
resource at page translation time (the jsp page is translated only
once so it will be better to include static resource).
Advantage of Include directive
Code Reusability
9
J2EE
Syntax of include directive
<%@ include file="resourceName" %>
The scripting elements provides the ability to insert java code inside the jsp.
There are three types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag
1.scriptlet tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as
follows:
<% java source code %>
Example of JSP scriptlet tag
In this example, we are displaying a welcome message.
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
11
J2EE
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form> </body> </html>
File2: welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form> </body> </html>
2.expression tag
The code placed within JSP expression tag is written to the output
stream of the response. So you need not write out.print() to write data. It
is mainly used to print the values of variable or method.
Syntax of JSP expression tag
<%= statement %>
File1: index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form> </body> </html>
12
J2EE
File2: welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body> </html>
2.declaration tag
The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the
service() method of auto generated servlet.
So it doesn't get memory at each request.
Syntax of JSP declaration tag
<%! field or method declaration %>
The jsp scriptlet tag can only declare The jsp declaration tag can declare variables
13
J2EE
variables not methods. as well as methods.
The declaration of scriptlet tag is placed The declaration of jsp declaration tag is
inside the _jspService() method. placed outside the _jspService() method.
There are many JSP action tags or elements. Each JSP action tag is
used to perform some specific tasks.
The action tags are used to control the flow between pages and to
use Java Bean. The Jsp action tags are given below.
A JSP action directive provides an easy method to encapsulate the
common tasks.
These typically create or act on objects, usually JavaBeans.
JavaBeans are components that are created once, and can be reused
over and over again.
1.JSP:Include:
JSP page.
Servlet.
we are including.
ollowing Example We Used 2 JSP Files, one.jsp file is sample file
which is included in second.jsp file.
Example:
First.JSP:
<html>
<head>
<title>JSP Include Example</title>
</head>
14
J2EE
<body>
<h1>This is the first.jsp File.</h1>
<jsp:include page="second..jsp" />
</body> </html>
Second.JSP:
<html>
<head>
<title>Second JSP File</title>
</head>
<body>
<h1>This is the second.jsp File. This File Included Using JSP Include
Action Tag.</h1>
</body> </html>
2.JSP:Forward:
15
J2EE
<html>
<head>
<title>Display Page</title>
</head>
<body>
Hello this is a display.jsp Page
</body>
</html>
3.Jsp:Param
The <c:param> tag allows proper URL request parameter to be specified with
URL and also does the necessary URL encoding required.
Within a <c:param> tag, the name attribute indicates the parameter name, and the
value attribute indicates the parameter value −
Attribute
The <c:param> tag has the following attributes −
name Name of the request parameter to set in the URL Yes None
Example
If you need to pass parameters to a <c:import> tag, use the <c:url> tag to create
the URL first as shown below −
<c:url value = "/index.jsp" var = "myURL">
<c:param name = "trackingId" value = "1234"/>
<c:param name = "reportType" value = "summary"/>
</c:url>
<c:import url = "${myURL}"/>
16
J2EE
The above request will pass the URL as below - Try it yourself.
"/index.jsp?trackingId=1234;reportType=summary"
4.Jsp:Plugin
The jsp:plugin action tag is used to embed applet in the jsp file. The
jsp:plugin action tag downloads plugin at client side to execute an applet
or bean.
Syntax of jsp:plugin action tag
<jsp:plugin type= "applet | bean" code= "nameOfClassFile"
codebase= "directoryNameOfClassFile" >
</jsp:plugin>
1. Request :
This is an object of HTTPServletRequest.
This allows the developer to access the request parameters using
getParameter(), the request type (GET, POST HEAD etc).
And the incoming HTTP header.
However, if HTTP is not used, than request is usually an object of
javax.servlet.ServletRequest.
2.Response :
This is an HttServletResponse object associated with the response
of the client.
17
J2EE
This allows the developer to set the content type, which is to be
sent to the client's browser using the setContentType() method.
3.Out :
This is an object of type javax.servlet,.jsp.Jsp writer.
It is used for writing data to the output buffer.
The buffer size can be adjusted or may even be turned off.
You may recall that this can be done using the buffer attribute of
the page directive.
The out object is used almost exclusively in scriptlets, as JSP
expressions get automatically placed in the output stream.
4.Session :
This is HttpSession object associated with the request.
The sessions are created automatically, so this variable is bound to
the page even if there is no incoming session reference.
However, there is one exception.
The session attribute for a particular page may be sent to false.
In this case, any attempt made to reference the session variable will
produce error.
5. Application :
This a javax.servlet.ServletContext object.
It is used to share information among all users of a currently active
application.
6. Confg :
This object stores servlet configuration data, but rarely used.
This is the javax.servlet.ServletConfig object.
18
J2EE
How Cookie works
Types of Cookie
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user
closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user
closes the browser. It is removed only if user logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using
cookies. It provides a lot of useful methods for cookies.
19
J2EE
Constructor of Cookie class
Constructor Description
There are given some commonly used methods of the Cookie class.
Method Description
public String getName() Returns the name of the cookie. The name
cannot be changed after creation.
Let's see the simple code to delete cookie. It is mainly used to logout or
signout the user.
1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name
and value of cookie
4. }
21
J2EE
Q.8 Explain session on JSP
In such case, container creates a session id for each user.The container
uses this id to identify the particular user.An object of HttpSession can
be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the
session identifier, creation time, and last accessed time.
index.html
22
J2EE
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
welcome.jsp
1. <html>
2. <body>
3. <%
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
8. session.setAttribute("user",name);
10. <a href="second.jsp">second jsp page</a>
12. %>
13. </body>
14. </html>
second.jsp
1. <html>
2. <body>
3. <%
5. String name=(String)session.getAttribute("user");
6. out.print("Hello "+name);
8. %>
9. </body>
10. </html>
23
J2EE
The exception is normally an object that is thrown at runtime. Exception
Handling is the process to handle
the runtime errors. There may occur exception any time in your web
application. So handling exceptions is as afer side for the web developer.
In JSP, there are two ways to perform exception handling:
1. By errorPage and isErrorPage attributes of page directive
2. By <error-page> element in web.xml file
Example of exception handling in jsp by the elements of page
directive
In this case, you must define and create a page to handle the exceptions,
as in the error.jsp page. The pages
where may occur exception, define the errorPage attribute of page
directive, as in the process.jsp page.
There are 3 files:
· index.jsp for input values
· process.jsp for dividing the two numbers and displaying the result
· error.jsp for handling the exception
index.jsp
1. <form action="process.jsp">
2. No1:<input type="text" name="n1" /><br/><br/>
3. No1:<input type="text" name="n2" /><br/><br/>
4. <input type="submit" value="divide"/>
5. </form>
process.jsp
1. <%@page errorPage="error.jsp" %>
2. <%
3.
4. String num1=request.getParameter("n1");
5. String num2=request.getParameter("n2");
6.
7. int a=Integer.parseInt(num1);
8. int b=Integer.parseInt(num2);
9. int c=a/b;
10. out.print("division of numbers is: "+c);
11.
24
J2EE
12. %>
error.jsp
1. <%@page isErrorPage="true" %>
2.
3. <h3>Sorry an exception occured!</h3>
4.
5. Exception is: <%= exception %>
Q.10 javabean
A JavaBean is a Java class that should follow the following conventions:
1. getPropertyName ()
25
J2EE
For example, if the property name is firstName, the method name would
be getFirstName() to read that property. This method is called the
accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would
be setFirstName() to write that property. This method is called the
mutator.
Advantages of JavaBean
o The JavaBean properties and methods can be exposed to another
application.
o It provides an easiness to reuse the software components.
Disadvantages of JavaBean
o JavaBeans are mutable. So, it can't take advantages of immutable
objects.
o Creating the setter and getter method for each property separately
may lead to the boilerplate code.
o package mypack;
o public class Test{
o public static void main(String args[]){
o Employee e=new Employee();//object is created
o e.setName("Arjun");//setting value to the object
o System.out.println(e.getName());
o }}
26
J2EE
<jsp:useBean id = "name" class = "package.class" />
Once a bean class is loaded, you can
use jsp:setProperty and jsp:getProperty actions to modify and retrieve
the bean properties.
Q.12 Define Expression Language (EL) in JSP
27
J2EE
11. pageContext: it provides access to many objects request,
session etc.
28