Java Server Page
Java Server Page
JSP Basics
□ JSP technology is used to create dynamic web
applications.
□ JSP pages are easier to maintain then a Servlet.
□ JSP pages are opposite of Servlets.
□ Servlet adds HTML code inside Java code.
□ JSP adds Java code inside HTML using JSP tags.
□ Everything a Servlet can do, a JSP page can also do it.
JSP Basics
□ JSP enables us to write HTML pages containing tags,
inside which we can include powerful Java programs.
□ Using JSP, can easily separate Presentation and
Business logic.
□ Web designer can design and update JSP pages
creating the presentation layer and java developer can
write server side complex computational code without
concerning the web design.
□ And both the layers can easily interact over HTTP
requests.
Advantage of JSP over Servlet
□ 1) Extension to Servlet
□ JSP technology is the extension to servlet
technology. We can use all the features of servlet in
JSP. In addition to, we can use implicit objects,
predefined tags, expression language and Custom
tags in JSP, that makes JSP development easy.
□ 2) Easy to maintain
□ JSP can be easily managed because we can easily
separate our business logic with presentation logic.
In servlet technology, we mix our business logic
with the presentation logic.
Advantage of JSP over Servlet
□ 3) Fast Development: No need to recompile and
redeploy
□ If JSP page is modified, we don't need to recompile
and redeploy the project. The servlet code needs to be
updated and recompiled if we have to change the look
and feel of the application.
□ 4) Less code than Servlet
□ In JSP, we can use a lot of tags such as action tags,
jstl, custom tags etc. that reduces the code. Moreover,
we can use implicit objects etc.
Java Server Pages (JSP) Architecture
Receive HTTP Server
Request
□
JSP Container
JSPs run in two phases Page Compiler Servlet
JSP
■ Translation Phase Servlet No
Parse JSP
Curren
■ Execution Phase t?
JSP
Yes
Servlet Generate JSP
□ In translation phase Loade
d?
Servlet Source
Yes No
JSP page is compiled Compile JSP
Load Servlet
Servlet
into a servlet
■ called JSP Page JSP Page Servlet
Implementation class Generate
Response
<body>
Page Count is:
<% out.println(++count); %>
</body>
</html>
JSP page(hello.jsp) becomes this Servlet
public class hello_jsp extends HttpServlet
{
public void _jspService(HttpServletRequest request,
HttpServletResponse response) throws
IOException,ServletException
{
PrintWriter out = response.getWriter();
response.setContenType("text/html");
out.write("<html><body>");
int count=0;
out.write("Page count is:");
out.print(++count);
out.write("</body></html>");
}}
Components of JSP
Four different elements are used in
constructing JSPs
1. Scripting Elements
2. Implicit Objects
3. Directives
4. Actions
1. Scripting Elements
<body>
<%= "welcome to jsp" %>
</body>
</html>
Example of JSP expression tag
To display current time:
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
JSP Declaration Tag
□ The JSP declaration tag is used to declare
fields and methods.
<html>
<html>
<body>
<body>
<%!
<%! int data=50; %>
int cube(int n)
<%= "Value of the variable is:"+data
{
%>
return n*n*n*;
}
</body>
%>
</html>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
Difference between JSP Scriptlet tag and
Declaration tag
□ HTML comments
■ An HTML comment.
■ Ignored by the browser.
■ It is visible in client machine (Browser source code) as a
comment.
<!-- This comment is HTML --> 23
More Details
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
JSP Implicit Objects
welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
The Response object
□ It used to add or manipulate response such as
redirect response to another resource, send error etc.
□ Methods of response Implicit Object
□ void setContentType(String type)
void sendRedirect(String address)
void addHeader(String name, String value)
void setHeader(String name, String value)
boolean containsHeader(String name)
void addCookie(Cookie value)
void sendError(int status_code, String message)
void setStatus(int statuscode)
The Response object
□ response.setContentType("text/html");
□ response.sendRedirect("http://google.com");
□ response.addCookie(Cookie Author);
<servlet>
<servlet-name>Servlet1</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name> Servlet1 </servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
</web-app>
JSP application object
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>
JSP application object
JSP application object
JSP config object
□ In JSP, config is an implicit object of type
ServletConfig.
□ This object can be used to get initialization
parameter for a particular JSP page.
□ The config object is created by the web
container for each jsp page.
□ Generally, it is used to get initialization
parameter from the web.xml file.
JSP config object
□ index.html
□ <form action="welcome">
□ <input type="text" name="uname">
□ <input type="submit" value="go"><br/>
□ </form>
□
JSP config object
web.xml file <servlet-mapping>
<web-app> <servlet-name>servlet1</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>servlet1</servlet-name> </web-app>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
JSP config object
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
%>
JSP pageContext object
□ In JSP, pageContext is an implicit object of type
PageContext class.
□ The pageContext object can be used to set,get or
remove attribute from one of the following scopes:
1. page
2. request
3. session
4. application
In JSP, page scope is the default scope.
JSP pageContext object
□ JSP Page – Scope: PAGE_CONTEXT
□ The page object is really a direct synonym for the this object.
□ <%=this.getClass().getName() %>
JSP exception object
□ It’s an instance of java.lang.Throwable.
□ It is used for exception handling in JSP.
□ This object is only available for error pages,
which means a JSP page should have
isErrorPage to true in order to use exception
implicit object.
□ JSP exception object Example
JAVA Beans
A Java Bean is a java class that should follow
following conventions:
1. It should have a no-arg constructor.
2. It should be Serializable.
class= "packageName.className"
type= "packageName.className"
beanName="packageName.className >
</jsp:useBean>
JSP Actions :useBean
Attributes of jsp:useBean action tag
□ id: is used to identify the bean(beans’s name).
□ scope: The default scope is page.
■ page: bean is used within the JSP page.
■ request: bean is used from any JSP page that processes the
same request. It has wider scope than page.
■ session: bean is used from any JSP page in the same session
whether processes the same request or not. It has wider scope
than request.
■ application: bean is used from any JSP page in the same
application. It has wider scope than session.
JSP Actions :useBean
Attributes of jsp:useBean action tag
□ class: instantiates the specified bean class (i.e.
creates an object of the bean class) but it must have
no-arg or no constructor and must not be abstract.
□ type: provides the bean a data type if the bean
already exists in the scope. It is mainly used with
class or beanName attribute. If you use it without
class or beanName, no bean is instantiated.
□ beanName: instantiates the bean using the
java.beans.Beans.instantiate() method.
JSP Actions:setProperty
<html>
<head>
<h1>Java bean example in jsp</h1>
<hr></hr>
</head>
<body>
<jsp:useBean id="mybean" class="my.MyBean" scope="session" >
<jsp:setProperty name="mybean" property="name" value=" Hello world " />
</jsp:useBean>
StudentBean.java
package javabeansample;
public class StuBean
{
public StuBean() { }
private String name;
private int rollno;
public void setName(String name)
{ this.name=name; }
public String getName()
{ return name; }
public void setRollno(int rollno)
{ this.rollno=rollno; }
public int getRollno()
{ return rollno; }
}
JSP Actions :useBean Example2
EmployeeBeanTest.jsp
<html>
<head>
<title>JSP Page to show use of useBean action
</title>
</head> <body>
<jsp:useBean id="student" class="javabeansample.StuBean"/>
□ index.jsp
□ process.jsp
□ User.java
JSP Actions :useBean Example3
□ index.jsp
<form action="process.jsp" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
Email:<input type="text" name="email"><br>
<input type="submit" value="register">
</form>
JSP Actions :useBean Example3
□ process.jsp
<jsp:useBean id="userbean"
class="Mybean.User"></jsp:useBean>
<jsp:setProperty name="userbean" property="*" />
Record:<br>
<jsp:getProperty name="userbean" property="name" /><br>
<jsp:getProperty name="userbean" property="password" /><br>
<jsp:getProperty name="userbean" property="email" /><br>
JSP Actions :useBean Example3
□ codebase= "directoryNameOfClassFile"
□ </jsp:plugin>
JSP Actions: plugIn
Constructor Description
Cookie() constructs a cookie.
Method Description
public void setMaxAge Sets the maximum age of the cookie
(int expiry) in seconds.
public String getName() Returns the name of the cookie. The
name cannot be changed after
creation.
public String getValue() Returns the value of the cookie.
public void setName changes the name of the cookie.
(String name)
public void setValue changes the value of the cookie.
(String value)
Other methods required for using Cookies