Professional Documents
Culture Documents
• If we develop any web application with servlets, then it is mandatory for the web
application developer to configure web.xml file.
Imp points about JSP
• A JSP is a text file with any name but with extension .jsp
• A JSP on its own cannot process a client request.It will be translated in to a servlet
by JSP engine.That container-generated servlet serves the client request.
• Developing a JSP is nothing but another style of developing a servlet.Instead of we
writing a servlet,we instruct the container to write servlet for us
NOTE:
6. Request processing:
jspService(): The _jspService() method is called for each and every request by the JSP container in
the jsp life cycle.
7. Destroy:
6.At last, the webserver forwards the HTML file as a response to the client’s browser.
Explain about Anatomy of JSP PAGE
• JSP page is a simple web page that contains the JSP Elements and Template text
• The template text can be scripting code such as HTML, XML or simple plain text
• The template text is always passed directly to the browser
• The JSP elements can be action tags , custom tags, JSTL library elements
• The JSP elements are responsible for generating dynamic web pages
• When the JSP request gets processed template text and JSP Elements are merged
together and sent to the browser as a response.
MVC in JSP
What is MVC?
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.
•It receives the requests from the view layer and processes the requests and does the
necessary validation for the request.
•This requests is further sent to model layer for data processing, and once the request is
processed, it sends back to the controller with required information and displayed
accordingly by the view.
Ex: Servlet
Model represents the state of the application i.e. data. It can also have business logic.
The model connects with the database as well and stores the data into a database which
is connected to it.
Ex:Java Bean
View represents the presentaion i.e. UI(User Interface).
Ex: html,jsp
Advantages of MVC Architecture
The advantages of MVC are:
•Easy to maintain
•Easy to extend
•Easy to test
•Navigation control is centralized
Expression Language
Expression Language (EL) in JSP
Expression language (EL) has been introduced in JSP 2.0.
The Expression Language (EL) simplifies the process of accessing data
from bean properties and from implicit objects to produce scriptless JSP Pages.
EL includes arithmetic, relational and logical operators too.
There are many implicit objects, operators, and reserve words in EL.
The syntax for Expression Language (EL)
${ expression }
whatever is present inside braces gets evaluated at runtime and being sent to the output
stream.
JSP EL Implicit Objects
The JSP directives are messages that tell the web container how to translate a JSP page
into the corresponding servlet.
• The directive elements are used to do page-related operations during page translation
time.
• Using directive elements we can import some packages and used them to specify
attributes of the page.
• 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 is used to provide the name of the file that can be included in the
JSP.
Syntax
include.jsp
<html>
<body>
</body> </html>
hai.html
<html>
<body> hai h r u</body> output:Include JSP
hai h r u output:
</html>
3. taglib directive:
• The JSP taglib directive is used to define a tag library that defines many tags. We use
the TLD (Tag Library Descriptor) file to define the tags.
• The directive taglib is used to specify the custom tags.
Syntax:
• The code placed within the 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 variables or methods.
Syntax:
<%= statement %>
Ex To illustrate Expression tag: Welcome.jsp
<html>
<body>
<%= "welcome to jsp" %> output: welcome to jsp
</body>
</html>
Action Elements or Action tags:
• 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.
Using JSP actions
•a file can be inserted into another page dynamically,
•a bean component can be reused,
•a user can be forwarded from one page to another page.
syntax:
• <jsp:action_name attribute = "attribute_value" />
JSP Action Tags or Action Elements
• jsp:forward: is used for forwarding the request and response to other resources.
• jsp:include: is used for including another resource.
• jsp:param: is used for setting the parameter for (forward or include) value.
• jsp:useBean: is used for creating or locating bean objects.
• jsp:setProperty: is used for setting the value of property in the bean object.
• jsp:getProperty: is used for printing the value of the property of the bean.
• jsp:element: is used for defining XML elements dynamically.
• jsp:plugin: is used for embedding other components (applets).
• jsp: fallback can be used to print the message if the plugin is working.
1. jsp: forward action tag
The jsp: forward action tag is used to forward the request to another resource it may be
JSP, HTML, or another resource.
Syntax forward action tag without the parameter
<jsp:forward page=“Relative URL " />
• The jsp: include action tag is used to include the content of another resource it
may be JSP, HTML, or servlet.
• The jsp: include tag can be used to include static as well as dynamic pages.
Syntax of jsp: include action tag without the parameter
<jsp:include page=“relative URL" />
Syntax of JSP: include action tag with a parameter
<jsp:include page=“relative URL
<jsp:param name="parameter name value="parameter value
</jsp: include>
Advantage
Code reusability: We can use a page many times such as including header and footer
pages in all pages. So it saves a lot of time.
Ex : To illustrate include action without parameter
index.jsp
<h2>this is index page</h2>
<jsp:include page="printdate.jsp" />
<h2>end section of index page</h2>
Printdate.jsp
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
3 param action
<jsp: param> tag is used to represent parameter value during jsp forward or include
action this should be the subtag of <jsp: forward> or <jsp: include>.
Syntax
<jsp:param name=“param_name " value=“param_value "/>
Ex : To illustrate param action
index.jsp
<html>
<body>
<h2>this is index page</h2>
<jsp:forward page="printdate.jsp" >
<jsp:param name="name" value=“amazon.com" />
</jsp: forward>
</body>
</html>
printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
<%= request.getParameter("name") %>
</body>
</html>
Output:
Today is:Fri Oct 28 21:05:10 IST 2022 amazon.com
Using Beans in JSP Pages
What is java bean?
• A Java Bean is a specialized Java class that is defined according to Java Beans API
Specifications.
• A Java Bean is a plat form independent reusable software component used in
Presentation layer.
Advantages of JavaBean
•It provides an easiness to reuse the software components.
•Java Bean used at client side like development of button, password field screen etc.
•it provides easy maintenance.
A Java Bean is a java class that should follow following conventions or Rules:
Or
1.out
2.request
3.response
4.config
5.application
6.session
7.pagecontext
8.page
9.exception
1. JSP out implicit object
JSP provides an implicit object named out. It is the object of JspWriter.
out is one the implicit object to write the data to the buffer and send output to the client
in response.
Page implicit variable hold the currently executes Servlet object for the corresponding
JSP.
Acts as this object for current jsp page
EX:
<%=page.getClass ().getName () %>
<%=page.getServlestInfo ()%>
9.exception implicit object
In JSP, exception is an implicit object of type java.lang.Throwable class.
This object can be used to print the exception. But it can only be used in error pages.
error.jsp
<%@ page isErrorPage="true" %>
<html>
<body>
Sorry following exception occured:<%= exception %>
</body>
</html>
Session tracking
Using cookies and session
Session Handling or Session Management or Session tracing in JSP
Session Handling becomes mandatory when a requested data need to be sustained for
further use. Since http protocol considers every request as a new one, session handling
becomes important.
1.Cookies
2.Session
3.URL Rewriting
Cookies
Hidden Form Field
URL Rewriting
HttpSession
1.JSP Cookies
• Cookies are the text files stored on the client computer/machine for tracking purposes
like login details, file transfer, etc.
• Cookies are mainly used to recognize a user on the web server.
• A cookie can be used to remember the username and password for any site.
• 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.
• A cookie's value can uniquely identify a client, so cookies are commonly used for
session management.
• Size of cookies is 4 kb.
• In JSP cookie is the object of the class javax.servlet.http.Cookie. This class is used to
creates a cookie.
• A JSP can access to the cookies through the request method request.getCookies()
which returns an array of Cookie objects.
Types of Cookies in JSP
There are basically two types of cookies:
1. Persistent cookies: These cookies are also known as permanent cookies. They remain
on the hard drive and persist until the user deletes them or they expire themselves.
2. Session cookies: These cookies are also known as temporary cookies. They get deleted
themselves as soon as the session ends or the browser closes.
Cookie methods:
setDomain(String domain)
•This JSP set cookie is used to set the domain to which the cookie applies
getDomain()
•This JSP get cookie is used to get the domain to which the cookie applies
setMaxAge(int expiry)
•It sets the maximum expiration time to the cookie expires.
intgetMaxAge()
•It returns the maximum age of the cookie in JSP
getName()
•It returns the name of the cookie
setValue(String value)
•Sets the value associated with the cookie
getValue()
•Get the value associated with the cookie
Creating the cookie in JSP
Creating a Cookie object:
You call the Cookie constructor with a cookie name and a cookie value
EX: Cookie cookie = new Cookie("key","value");
Setting the maximum age:
You can use setMaxAge to specify how long (in seconds) the cookie should be valid
Ex: cookie.setMaxAge(60*60*24);
You can use response.addCookie() to add cookies in the HTTP response header as
follows:
EX: response.addCookie(cookie);
Reading Cookies with JSP
Cookie.html
<html>
<body>
<form method = "post" action="cookie1.jsp">
<font>Username<input type = "text" name = "name"></font>
</font><br>
<input type = "submit" name = "submit" value = "submit" >
</form>
</body>
</html>
cookie1.jsp
Output:
Hello cherry
2. JSP Session
• In JSP, a session is an implicit object of type HttpSession.The Java developer can use
this object to set, get or remove attributes or to get session information.
• JSP makes use of sessions to identify a user across more than one-page of request or
visit to a Web site and to store information about that user.
• The session is available until the session time out until the client log out. The default
session time is 30 minutes and can configure explicit session time in the web.xml file.
Example of session implicit object
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
Methods used HttpSession object
1.setAttribute(String, object):To set a attribute name and attribute value pair in the session object
we use
Ex: session.setAttribute(“uid”,”kiran”);
2.getAttribute(String name):We can get attribute value associated with attribute name by using
the following method
Session.getAttribute(“uid”));
3.invalidate():We can delete the session or end a session by using Invalidate();
Ex: session.invalidate ();
5.isNew(): This method is used to check either the session is new or not. Boolean value (true or
false) is returned by it.
6. removeAttribute(String name): The objects that are stored in the session can be removed
from the session.
Ex to create session in jsp
index.html
<html>
<body>
<h1> Session Demo</h>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
welcome.jsp
<%@ page language="java" contentType="text/html;"%>
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
%>
<a href="second.jsp">Display the value</a>
</body>
</html>
second.jsp
<%@ page language="java" contentType="text/html;"%>
<html>
<body>
<h1>Display the session value on this page</h1>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
OUTPUT:
Display the session value on this page
Hello cherry
3.URL REWRITING:
• URL rewriting: In URL rewriting we append some extra information on the end of each
URL that identifies the session.
• If your browser does not support cookies, URL rewriting provides you with another
session tracking alternative. URL rewriting is a method in which the requested URL is
modified to include a session ID.
• URL rewriting works only for Hyperlinks.
• In URL rewriting client state and identity information is stored in every request and
response.
An invisible text box of the form page is called a hidden box. When a form page is
submitted, the hidden box value goes to web resource program along with the request
parameter value.
• HTML form hidden input elements are called Hidden Form Fields.
• In hidden form fields the html entry will be like this :
• <input type ="hidden" name = "uid" value="kiran">.
• This means that when you submit the form, the specified name and value will be get
included in get or post method.
• In this session ID information would be embedded within the form as a hidden field and
submitted with the Http POST command.
connecting to database in JSP
Accessing DataBase from JSP page( connecting jsp page to Data Base Mysql)
Step1:
Create a data base named students in Mysql using the following command
Mysql> create Database students;
Mysql>use students;
Then create table named students with field’s sname, saddress.
Mysql> create table students (sname char (10), saddress char (10));
Mysql>Table successfuly created.
Mysql>insert into students values(‘cherry’,’Hyd’);
Mysql> inserted values successfully.
same sddress
Cherry Hyd
Step2:For establishing the connectivity between Jsp and Mysql you have to download
Step3:Create the Directory Structure for the JSP web application in a web-app folder in
tomcat 7.And place all the jsp and html files outside the WEB-INF folder inside the
web-app folder
Step4: create the html program to insert username and address
user.html
<html>
<body>
<form name = "login" method="post" action="proc.jsp">
User Name:
<input type="text" name="sname" ></td>
Address:
<input type="test" name="saddress" ></td>
<input type="submit" name="ok" value="Submit"></td>
</form>
</body>
</html>
Step5: create a jsp page to connect to the database and values should be updated in
database
proc.jsp
<%@ page language="java" import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%
Connection conn=null;
ResultSet rs=null;
Statement stmt=null;
Class.forName ("com.mysql.jdbc.Driver").newInstance();
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/kiran","root","root");
out.write("connected to the mysql");
stmt=conn.createStatement();
String sname=request.getParameter("sname");
String saddress=request.getParameter("saddress");
stmt.executeUpdate("insert into students(sname,saddress)values ('" + sname +"','"+saddress+"')");
conn.close();
out.write("connection success");
%>
Step6:
start the tomcat server and type the URL in some Browser
http:localhost:8085/user.html
Step7:
Output:
Connected to mysql
Connection success