JSP Scriptlet Tag Explained
JSP Scriptlet Tag Explained
Scripting elements
The scripting elements provides the ability to insert java code inside the jsp. There are three types of scripting elements:
[Link]
<html> <body> <form action="[Link]"> <input type="text" name="uname">
SHARAN K P
Page 1
JSP DOCUMENTS
<input type="submit" value="go"><br/> </form> </body> </html>
[Link]
<html> <body> <% String name=[Link]("uname"); [Link]("welcome "+name); %> </form> </body> </html> next>>
Note: Do not end your statement with semicolon in case of expression tag.
SHARAN K P
Page 2
JSP DOCUMENTS
instance of Calendar class by the getInstance() method.
[Link]
<html> <body> Current Time: <%= [Link]().getTime() %> </body> </html>
[Link]
<html> <body> <form action="[Link]"> <input type="text" name="uname"><br/> <input type="submit" value="go"> </form> </body> </html>
[Link]
<html> <body> <%= "Welcome "+[Link]("uname") %> </form> </body> </html>
SHARAN K P
Page 3
JSP DOCUMENTS
get memory at each request.
What is the difference between the jsp scriptlet tag and jsp declaration tag ?
The jsp scriptlet tag can only declare variables not methods whereas jsp declaration tag can declare variables as well as methods. The declaration of scriptlet tag is placed inside the _jspService() method whereas the declaration of jsp declaration tag is placed outside the _jspService() method.
[Link]
<html> <body> <%! int data=50; %> <%= "Value of the variable is:"+data %> </body> </html>
[Link]
<html> <body> <%!
SHARAN K P
Page 4
JSP DOCUMENTS
int cube(int n){ return n*n*n*; } %> <%= "Cube of 3 is:"+cube(3) %> </body> </html>
Object
out request response config application session pageContext page exception JspWriter
Type
JSP DOCUMENTS
In this example we are simply displaying date and time.
[Link]
<html> <body> <% [Link]("Today is:"+[Link]().getTime()); %> </body> </html>
[Link]
<html> <body> <% String name=[Link]("uname"); [Link]("welcome "+name); %> </body> </html> next>>
SHARAN K P
Page 6
JSP DOCUMENTS
<form action="[Link]"> <input type="text" name="uname"> <input type="submit" value="go"><br/> </form> </body> </html> [Link] <html> <body> <% [Link]("[Link] %> </body> </html> next>>
SHARAN K P
Page 7
JSP DOCUMENTS
</servlet-mapping> </web-app> [Link] <html> <body> <% [Link]("Welcome "+[Link]("uname")); String driver=[Link]("dname"); [Link]("driver name is="+driver); %> </body> </html> next>>
SHARAN K P
Page 8
JSP DOCUMENTS
</web-app> [Link] <html> <body> <% [Link]("Welcome "+[Link]("uname")); String driver=[Link]("dname"); [Link]("driver name is="+driver); %> </body> </html> next>>
[Link]
<html> <body> <% String name=[Link]("uname"); [Link]("Welcome "+name); [Link]("user",name); <a href="[Link]">second jsp page</a> %> </body> </html>
SHARAN K P
Page 9
JSP DOCUMENTS
[Link]
<html> <body> <% String name=(String)[Link]("user"); [Link]("Hello "+name); %> </body> </html>
[Link]
<html> <body> <% String name=[Link]("uname"); [Link]("Welcome "+name); [Link]("user",name,PageContext.SESSION_SCOPE);
SHARAN K P
Page 10
JSP DOCUMENTS
<a href="[Link]">second jsp page</a> %> </body> </html>
[Link]
<html> <body> <% String name=(String)[Link]("user",PageContext.SESSION_SCOPE); [Link]("Hello "+name); %> </body> </html> next>>
SHARAN K P
Page 11
JSP DOCUMENTS
</html> To get the full example, click here full example of exception handling in jsp. But, it will be better to learn it after the JSP Directives next>>
JSP directives
1. JSP directives 1. page directive 2. Attributes of page directive 1. import 2. contentType 3. extends 4. info 5. buffer 6. language 7. isELIgnored 8. isThreadSafe 9. errorPage 10. isErrorPage The directives are messages that tells the web container how to translate a JSP page into corresponding [Link] are three types of directives:
JSP DOCUMENTS
import contentType extends info buffer language isELIgnored isThreadSafe autoFlush session pageEncoding errorPage isErrorPage
1)import
The import attribute is used to import class,interface or all the members of a [Link] is similar to import keyword in java class or interface.
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP [Link] default value is "text/html;charset=ISO-8859-1".
SHARAN K P
Page 13
JSP DOCUMENTS
</html>
3)extends
The extends attribute defines the parent class that will be inherited by the generated [Link] 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.
5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP [Link] default size of the buffer is 8Kb.
SHARAN K P
Page 14
JSP DOCUMENTS
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. <%@ page isELIgnored="true" %>//Now EL will be ignored
8)isThreadSafe
Servlet and JSP both are [Link] you want to control this behaviour of JSP page, you can use isThreadSafe attribute of page [Link] value of isThreadSafe value is [Link] you make it false, the web container will serialize the multiple requests, i.e. it will wait until the JSP finishes responding to a request before passing another request to [Link] you make the value of isThreadSafe attribute like: <%@ page isThreadSafe="false" %> The web container in such a case, will generate the servlet as: public class SimplePage_jsp extends HttpJspBase implements SingleThreadModel{ ....... }
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.
SHARAN K P
Page 15
JSP DOCUMENTS
</body> </html>
10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.
Note: The exception object can only be used in the error page.
Include directive
1. Include directive 2. Advantage of Include directive 3. Example of 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).
JSP DOCUMENTS
In this example, we are including the content of the [Link] file. To run this example you must create an [Link] file. 1. <html> <body> <%@ include file="[Link]" %> Today is: <%= [Link]().getTime() %> </body> </html>
Note: The include directive includes the original content, so the actual page size grows at runtime.
SHARAN K P
Page 17
JSP DOCUMENTS
SHARAN K P
Page 18
JSP DOCUMENTS
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 [Link] page. The pages where may occur exception, define the errorPage attribute of page directive, as in the [Link] page. There are 3 files:
[Link] for input values [Link] for dividing the two numbers and displaying the result [Link] for handling the exception
[Link]
<form action="[Link]"> No1:<input type="text" name="n1" /><br/><br/> No1:<input type="text" name="n2" /><br/><br/> <input type="submit" value="divide"/> </form>
[Link]
<%@ page errorPage="[Link]" %> <% String num1=[Link]("n1"); String num2=[Link]("n2"); int a=[Link](num1); int b=[Link](num2); int c=a/b; [Link]("division of numbers is: "+c); %>
[Link]
<%@ page isErrorPage="true" %> <h3>Sorry an exception occured!</h3> Exception is: <%= exception %>
SHARAN K P
Page 19
JSP DOCUMENTS
SHARAN K P
Page 20
JSP DOCUMENTS
Example of exception handling in jsp by specifying the error-page element in [Link] file
This approach is better because you don't need to specify the errorPage attribute in each jsp
SHARAN K P
Page 21
JSP DOCUMENTS
page. Specifying the single entry in the [Link] file will handle the exception. In this case, either specify exception-type or error-code with the location element. If you want to handle all the exception, you will have to specify the [Link] in the exception-type element. Let's see the simple example: There are 4 files:
[Link] file for specifying the error-page element [Link] for input values [Link] for dividing the two numbers and displaying the result [Link] for displaying the exception
1) [Link] file if you want to handle the exception for a specific error code
<web-app> <error-page> <error-code>500</error-code> <location>/[Link]</location> </error-page> </web-app>
SHARAN K P
Page 22
JSP DOCUMENTS
4) [Link] file is same as in the above example
The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean development. So we will see these tags in bean developement.
[Link]
SHARAN K P
Page 23
JSP DOCUMENTS
<html> <body> <h2>this is index page</h2> <jsp:forward page="[Link]" /> </body> </html>
[Link]
<html> <body> <% [Link]("Today is:"+[Link]().getTime()); %> </body> </html>
[Link]
<html> <body> <h2>this is index page</h2> <jsp:forward page="[Link]" > <jsp:param name="name" value="[Link]" /> </jsp:forward> </body> </html>
[Link]
<html> <body> <% [Link]("Today is:"+[Link]().getTime()); %> <%= [Link]("name") %> </body> </html> next>>
SHARAN K P
Page 24
JSP DOCUMENTS
3. Example of jsp:include action tag without parameter The jsp:forward action tag is used to include the content of another resource it may be jsp, html or servlet. The jsp include action tag includes the resource at request time so it is better for dynamic pages because there might be changes in future.
[Link]
<html> <body> <h2>this is index page</h2> <jsp:include page="[Link]" /> <h2>end section of index page</h2> </body> </html>
[Link]
<html> <body> <% [Link]("Today is:"+[Link]().getTime()); %> </body> </html> next>>
Java Bean
SHARAN K P Page 25
JSP DOCUMENTS
A Java Bean is a java class that should follow following conventions:
It should have a no-arg constructor. It should be Serializable. It should provide methods to set and get the values of the properties, known as getter and setter methods.
Note: There are two ways to provide values to the object, one way is by constructor and second is by setter method.
SHARAN K P
Page 26
JSP DOCUMENTS
SHARAN K P
Page 27
JSP DOCUMENTS
[Link] (a simple Bean class)
package [Link]; public class Calculator{ public int cube(int n){return n*n*n;} }
[Link] file
<jsp:useBean id="obj" class="[Link]"/> <% int m=[Link](5); [Link]("cube of 5 is "+m); %>
SHARAN K P
Page 28
JSP DOCUMENTS
component that represents data. The jsp:setProperty action tag sets a property value or values in a bean using the setter method.
Example of jsp:setProperty action tag if you have to set all the values of incoming request in the bean
<jsp:setProperty name="bean" property="*" />
Example of jsp:setProperty action tag if you have to set value of the incoming specific property
<jsp:setProperty name="bean" property="username" />
Example of jsp:setProperty action tag if you have to set a specific value in the property
<jsp:setProperty name="bean" property="username" value="Kumar" />
JSP DOCUMENTS
In this example there are 3 pages:
[Link] for input of values [Link] file that sets the incoming values to the bean object and prints the one value [Link] bean class that have setter and getter methods
[Link]
<form action="[Link]"/> Enter Name:<input type="text" name="name"/> </form>
[Link]
<jsp:useBean id="obj" class="[Link]" /> <jsp:setProperty name="obj" property="*" /> Welcome, <jsp:getProperty name="obj" property="name" />
[Link]
package [Link]; public class User{ private String name; public void setName(String name){ [Link]=name; } public String getName(){ return name; } }
SHARAN K P
Page 30
JSP DOCUMENTS
[Link]
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Mouse Drag</title> </head> <body bgcolor="khaki"> <h1>Mouse Drag Example</h1>
SHARAN K P
Page 31
JSP DOCUMENTS
<jsp:plugin align="middle" height="500" width="500" type="applet" code="[Link]" name="clock" codebase="."/> </body> </html>
Implicit Objects
pageScope
Usage
it maps the given attribute name with the value set in the page scope it maps the given attribute name with the value set in the request scope
requestScope
sessionScope
it maps the given attribute name with the value set in the session scope
SHARAN K P
Page 32
JSP DOCUMENTS
applicationScope it maps the given attribute name with the value set in the application scope it maps the request parameter to the single value it maps the request parameter to an array of values it maps the request header name to the single value it maps the request header name to an array of values it maps the given cookie name to the cookie value it maps the initialization parameter 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 [Link] and [Link]. The [Link] file gets input from the user and sends the request to the [Link] which in turn prints the name of the user using EL.
[Link]
<form action="[Link]"> Enter Name:<input type="text" name="name" /><br/><br/> <input type="submit" value="go"/> </form>
[Link]
Welcome, ${ [Link] }
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.
[Link]
SHARAN K P Page 33
JSP DOCUMENTS
<h3>welcome to index page</h3> <% [Link]("user","sonoo"); %> <a href="[Link]">visit</a>
[Link]
Value is ${ [Link] }
Precedence of Operators in EL
There are many operators that have been provided in the Expression Language. Their precedence are as follows: [] .
()
* / div % mod
+ - (binary)
== != eq ne
&& and
|| or
?:
Reserve words in EL
There are many reserve words in the Expression Language. They are as follows:
SHARAN K P
Page 34
JSP DOCUMENTS
lt eq and le ne or gt true not ge false instanceof
div
mod
empty
null
MVC in JSP
1. MVC in JSP 2. Example of following MVC in JSP MVC stands for Model View and Controller. It is a design pattern that separates the business logic, presentation logic and data. Controller acts as an interface between View and Model. Controller intercepts all the requests. Modelrepresents the state of the application i.e. data. Viewrepresents the presentaion.
[Link] a servlet that acts as a controller. [Link] and [Link] files acts as view components. [Link] file for mapping the servlet.
[Link] In this servlet, we are simply checking the input values, if run this application first time, it will for the request to the login page without error message. If you type any other password than sonoo, it will redirect again to the login page with error message. But if you type the password sonoo, it will redirect to the welcome page. import [Link]; import [Link]; import [Link]; import [Link]; import [Link];
SHARAN K P
Page 35
JSP DOCUMENTS
import [Link]; import [Link]; public class MServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { [Link]("text/html"); PrintWriter out = [Link](); String n=[Link]("name"); String p=[Link]("pass"); if(n==null){ RequestDispatcher rd=[Link]("[Link]"); [Link](request, response); } else if([Link]("sonoo")){ RequestDispatcher rd=[Link]("[Link]"); [Link](request, response); } else{ [Link]("error","true"); RequestDispatcher rd=[Link]("[Link]"); [Link](request, response); } [Link](); } } [Link] <% if([Link]("error")!=null){ [Link]("Not valid user! Try again<hr>"); } %> <form action="servletM"> Name:<input type="text" name="name"/><br/> Password:<input type="password" name="pass"/><br/> <input type="submit" value="login"/> </form> [Link] Welcome User! [Link] <web-app>
SHARAN K P
Page 36
JSP DOCUMENTS
<servlet> <servlet-name>MServlet</servlet-name> <servlet-class>MServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MServlet</servlet-name> <url-pattern>/servletM</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>servletM</welcome-file> </welcome-file-list> </web-app>
next>>
[Link] for getting the values from the user [Link], a bean class that have properties and setter and getter methods. [Link], a jsp file that processes the request and calls the methods [Link], an interface that contains many constants like DRIVER_CLASS, CONNECTION_URL, USERNAME and PASSWORD [Link], a class that returns an object of Connection. It uses the Singleton and factory method design pattern. [Link], a DAO class that is responsible to get access to the database
SHARAN K P
Page 37
JSP DOCUMENTS
[Link]
We are having only three fields here, to make the concept clear and simplify the flow of the application. You can have other fields also like country, hobby etc. according to your requirement. <form action="[Link]"> <input type="text" name="uname" value="Name..." onclick="[Link]=''"/><br/> <input type="text" name="uemail" value="Email ID..." onclick="[Link]=''"/><br/> <input type="password" name="upass" value="Password..." onclick="[Link]=''"/><br/> <input type="submit" value="register"/> </form>
[Link]
This jsp file contains all the incoming values to an object of bean class which is passed as an argument in the register method of the RegisterDao class. <%@page import="[Link]"%> <jsp:useBean id="obj" class="[Link]"/> <jsp:setProperty property="*" name="obj"/> <% int status=[Link](obj); if(status>0) [Link]("You are successfully registered"); %>
[Link]
It is the bean class that have 3 properties uname, uemail and upass with its setter and getter methods. package bean; public class User { private String uname,upass,uemail; public String getUname() { return uname; } public void setUname(String uname) { [Link] = uname; } public String getUpass() { return upass; } public void setUpass(String upass) { [Link] = upass; } public String getUemail() {
SHARAN K P
Page 38
JSP DOCUMENTS
return uemail; } public void setUemail(String uemail) { [Link] = uemail; } }
[Link]
This interface contains four constants that can vary from database to database. package bean; public interface Provider { String DRIVER="[Link]"; String CONNECTION_URL="jdbc:oracle:thin:@localhost:1521:xe"; String USERNAME="system"; String PASSWORD="oracle"; }
[Link]
This class is responsible to return the object of Connection. Here, driver class is loaded only once and connection object gets memory only once. package bean; import [Link].*; import static [Link].*; public class ConnectionProvider { private static Connection con=null; static{ try{ [Link](DRIVER); con=[Link](CONNECTION_URL,USERNAME,PASSWORD); }catch(Exception e){} } public static Connection getCon(){ return con; } }
[Link]
This class inserts the values of the bean component into the database. package bean; import [Link].*; public class RegisterDao {
SHARAN K P
Page 39
JSP DOCUMENTS
public static int register(User u){ int status=0; try{ Connection con=[Link](); PreparedStatement ps=[Link]("insert into user432 values(?,?,?)"); [Link](1,[Link]()); [Link](2,[Link]()); [Link](3,[Link]()); status=[Link](); }catch(Exception e){} return status; } }
[Link] it provides three links for login, logout and profile [Link] for getting the values from the user [Link], a jsp file that processes the request and calls the methods. [Link], a bean class that have properties and setter and getter methods. [Link], an interface that contains many constants like DRIVER_CLASS, CONNECTION_URL, USERNAME and PASSWORD [Link], a class that is responsible to return the object of Connection. It uses the Singleton and factory method design pattern. [Link], a DAO class that verifies the emailId and password from the database. [Link] it invalidates the session. [Link] it provides simple message if user is logged in, otherwise forwards the request to the [Link] page.
In this example, we are using the Oracle10g database to match the emailId and password with the database. The table name is user432 which have many fields like name, email, pass etc. You may use this query to create the table: CREATE TABLE "USER432" ( "NAME" VARCHAR2(4000), "EMAIL" VARCHAR2(4000),
SHARAN K P
Page 40
JSP DOCUMENTS
"PASS" VARCHAR2(4000) ) / We assume that there are many records in this table.
[Link]
It simply provides three links for login, logout and profile. <a name="jsploginex"></a><a href="[Link]">login</a>| <a href="[Link]">logout</a>| <a href="[Link]">profile</a>
[Link]
This file creates a login form for two input fields name and password. It is the simple login form, you can change it for better look and feel. We are focusing on the concept only. <%@ include file="[Link]" %> <hr> <h3>Login Form</h3> <% String profile_msg=(String)[Link]("profile_msg"); if(profile_msg!=null){ [Link](profile_msg); } String login_msg=(String)[Link]("login_msg"); if(login_msg!=null){ [Link](login_msg); } %> <br> <form action="[Link]" method="post"> Name:<input type="text" name="name"><br><br> Password:<input type="password" name="password"><br><br> <input type="submit" value="login">" </form>
[Link]
This jsp file contains all the incoming values to an object of bean class which is passed as an argument in the validate method of the LoginDao class. If emailid and password is correct, it displays a message you are successfully logged in! and maintains the session so that we may recognize the user. <%@page import="[Link]"%> <jsp:useBean id="obj" class="[Link]"/> <jsp:setProperty property="*" name="obj"/> <% boolean status=[Link](obj); if(status){ [Link]("You r successfully logged in");
SHARAN K P
Page 41
JSP DOCUMENTS
[Link]("session","TRUE"); } else { [Link]("Sorry, email or password error"); %> <jsp:include page="[Link]"></jsp:include> <% } %>
[Link]
It is the bean class that have 2 properties email and pass with its setter and getter methods. package bean; public class LoginBean { private String email,pass; public String getEmail() { return email; } public void setEmail(String email) { [Link] = email; } public String getPass() { return pass; } public void setPass(String pass) { [Link] = pass; } }
[Link]
This interface contains four constants that may differ from database to database. package bean; public interface Provider { String DRIVER="[Link]"; String CONNECTION_URL="jdbc:oracle:thin:@localhost:1521:xe"; String USERNAME="system"; String PASSWORD="oracle"; }
[Link]
This class provides a factory method that returns the object of Connection. Here, driver class is loaded only once and connection object gets memory only once because it is static.
SHARAN K P
Page 42
JSP DOCUMENTS
package bean; import [Link].*; import static [Link].*; public class ConnectionProvider { private static Connection con=null; static{ try{ [Link](DRIVER); con=[Link](CONNECTION_URL,USERNAME,PASSWORD); }catch(Exception e){} } public static Connection getCon(){ return con; } }
[Link]
This class varifies the emailid and password. package bean; import [Link].*; public class LoginDao { public static boolean validate(LoginBean bean){ boolean status=false; try{ Connection con=[Link](); PreparedStatement ps=[Link]( "select * from user432 where email=? and pass=?"); [Link](1,[Link]()); [Link](2, [Link]()); ResultSet rs=[Link](); status=[Link](); }catch(Exception e){} return status; } }
SHARAN K P
Page 43
JSP DOCUMENTS
2. MultipartRequest class 3. Constructors of MultipartRequest class 4. Example of File Upload in JSP There are many ways to upload the file to the server. One of the way is by the MultipartRequest class. For using this class you need to have the [Link] file. In this example, we are providing the [Link] file alongwith the code.
MultipartRequest class
It is a utility class to handle the multipart/form-data request. There are many constructors defined in the MultipartRequest class.
[Link]
To upload the file to the server, there are two requirements: 1. You must use the post request. 2. encodeType should be multipart/form-data that gives information to the server that you are going to upload the file. <form action="[Link]" method="post" enctype="multipart/form-data"> Select File:<input type="file" name="fname"/><br/> <input type="image" src="[Link]"/> </form>
[Link]
We are uploading the incoming file to the location d:/new, you can specify your location here. <%@ page import="[Link]" %> <% MultipartRequest m = new MultipartRequest(request, "d:/new");
SHARAN K P
Page 44
JSP DOCUMENTS
[Link]("successfully uploaded"); %> If size of the file is greater than 1MB, you should specify the post size.
[Link]
This file provides a link to download the jsp file. <a href="[Link]">download the jsp file</a>
[Link]
In this example, we are downloading the file [Link] which is located in the e: drive. You may change this location accordingly. <% String filename = "[Link]"; String filepath = "e:\\"; [Link]("APPLICATION/OCTET-STREAM"); [Link]("Content-Disposition","attachment; filename=\"" + filename + "\""); [Link] fileInputStream=new [Link](filepath + filename); int i; while ((i=[Link]()) != -1) { [Link](i); } [Link](); %>
SHARAN K P
Page 45