JSP Ratan 9am

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 52

JSP

JSP Day-1

1. jsp used to write the programming at serverside, to design web applciations.

jsp we can write the programming at client side to render the proper response to browser.

2. Jsp is extension of servlets so we can use all features of servlets in addition we can use,

implicit objects, custom tags, predefined tags.

3. jsp tag based programming basics of java sufficient to understand the JSP

servlets everything java code. needs more java konwelge.

4. Servlets are best for more processing logics but jsp are best to develop dynamic web pages for more presentation logics
rather than processing logics.

5. Servlets are present in classes folder : private area : to Access the private area servlet use web.xml

jsp are present in webcontent folder along with html code : public area : to access the jsp web.xml is optional.

6. Servlets are java based: when we are doing modifications : recompilation

jsp are tag based : when we are doing modifications : just refresh will reflect the modifications.

7. servlets are directly will executed. servltes are faster

every jsp internally converted servlet that converted servlet executed we will get the response.

8. Servlet are executed by : servlet container

To execute the jsp : web container

web container : jsp Engine + servlet container

jsp Engine : will convert jsp to servlet

servlet container : will execute the converted servlet.

Servlet container name is : Catalina

Jsp engine name is : Jasper

9. servlet predefined support : servlet-api.jar


JSP predefined support : jsp-api.jar , servlet-api.jar

10. servlet life cycle methods

init() service() destory()

jsp life cycle methods

_jspInit() _jspService() _jspDestory()

11. The present version of servlets is 4.0 & present version of jsp is 2.3

12. MVC : In MVC jsp acts as a view part & servlets acts as a controller part.

13. servlets predefined support

javax.servlet

javax.servlet.http

javax.servlet.annotation

jsp predefiend support

Javax.servlet.jsp

Javax.servlet.jsp.tagext

Login.html:

<html>

<body>

<form action="LoginServlet" method="POST">

User Name: <input type="text" name="username" /><br>

Password: <input type="text" name="password" /><br>

<input type="submit" value="Sign In" />

</form>

</body>

</html>

LoginServlet.java:-

package com.dss;
import java.io.IOException;

import java.io.PrintWriter;

import java.util.Date;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/LoginServlet")

public class LoginServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public LoginServlet() { }

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String username = request.getParameter("username");

String password = request.getParameter("password");

if(username.equals("durga") && password.equals("ratan")){

//Rendering success response on browser.

out.println("<html><body>");

out.println("<h1><font color=\"green\"/>Successfully logged in at:"+ new Date()+"</h1>");

out.println("</body></html>");

else{

//Rendering failure response to browser.

out.println("<html><body>");

out.println("<h1><font color='red'/>Invalid Username or Password.</h1>");

out.println("</body></html>");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,


IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String username = request.getParameter("username");

String password = request.getParameter("password");

//Perform (or Invoke) Business Logic

if(username.equals("anu") && password.equals("ratan"))

{ //Invoke Success response page.

RequestDispatcher rd = request.getRequestDispatcher("/Success.jsp");

rd.forward(request, response);

else

{ //Invoke Failure response page.

RequestDispatcher rd = request.getRequestDispatcher("/Failure.jsp");

rd.forward(request, response);

Success.jsp:

<%@ page import="java.util.Date" %>

<html>

<body>

<h1><font color="green"/>Successfully logged in at:<%= new Date()%></h1>

</body>

</html>

Failure.jsp:

<html>

<body>
<h1><font color="red"/>Invalid Username or Password</h1>

</body>

</html>

success.html : we will get the features of only html

success.jsp : we will get the features of both html & jsp.

ex-1: create the web application with one jsp form.

//first.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<html>

<body>

This is JSP First Application..........

</body>

</html>

http://localhost:8888/JapApp1/first.jsp

HttpJspBase(c)

trans |

req ----> first.jsp ----> first_jsp.java

the converted servlet location:

E:\advjava9amonline\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\JapApp1\org\apache\j
sp

//first_jsp.java

package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;

import javax.servlet.jsp.*;

public final class first_jsp extends org.apache.jasper.runtime.HttpJspBase

implements org.apache.jasper.runtime.JspSourceDependent,

org.apache.jasper.runtime.JspSourceImports {

private static final javax.servlet.jsp.JspFactory _jspxFactory =

javax.servlet.jsp.JspFactory.getDefaultFactory();

private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

private static final java.util.Set<java.lang.String> _jspx_imports_packages;

private static final java.util.Set<java.lang.String> _jspx_imports_classes;

static {

_jspx_imports_packages = new java.util.HashSet<>();

_jspx_imports_packages.add("javax.servlet");

_jspx_imports_packages.add("javax.servlet.http");

_jspx_imports_packages.add("javax.servlet.jsp");

_jspx_imports_classes = null;

private volatile javax.el.ExpressionFactory _el_expressionfactory;

private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;

public java.util.Map<java.lang.String,java.lang.Long> getDependants() {

return _jspx_dependants;

public java.util.Set<java.lang.String> getPackageImports() {

return _jspx_imports_packages;

public java.util.Set<java.lang.String> getClassImports() {


return _jspx_imports_classes;

public javax.el.ExpressionFactory _jsp_getExpressionFactory() {

if (_el_expressionfactory == null) {

synchronized (this) {

if (_el_expressionfactory == null) {

_el_expressionfactory =
_jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();

return _el_expressionfactory;

public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {

if (_jsp_instancemanager == null) {

synchronized (this) {

if (_jsp_instancemanager == null) {

_jsp_instancemanager =
org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());

return _jsp_instancemanager;

public void _jspInit() {

public void _jspDestroy() {

public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse


response)

throws java.io.IOException, javax.servlet.ServletException {


if (!javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {

final java.lang.String _jspx_method = request.getMethod();

if ("OPTIONS".equals(_jspx_method)) {

response.setHeader("Allow","GET, HEAD, POST, OPTIONS");

return;

if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method)) {

response.setHeader("Allow","GET, HEAD, POST, OPTIONS");

response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET, POST or HEAD. Jasper


also permits OPTIONS");

return;

final javax.servlet.jsp.PageContext pageContext;

javax.servlet.http.HttpSession session = null;

final javax.servlet.ServletContext application;

final javax.servlet.ServletConfig config;

javax.servlet.jsp.JspWriter out = null;

final java.lang.Object page = this;

javax.servlet.jsp.JspWriter _jspx_out = null;

javax.servlet.jsp.PageContext _jspx_page_context = null;

try {

response.setContentType("text/html; charset=ISO-8859-1");

pageContext = _jspxFactory.getPageContext(this, request, response,

null, true, 8192, true);

_jspx_page_context = pageContext;

application = pageContext.getServletContext();

config = pageContext.getServletConfig();

session = pageContext.getSession();

out = pageContext.getOut();

_jspx_out = out;

out.write("\r\n");
out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01
Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");

out.write("<html>\r\n");

out.write("<head>\r\n");

out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\">\r\n");

out.write("<title>Insert title here</title>\r\n");

out.write("</head>\r\n");

out.write("<body>\r\n");

out.write("\tThis is JSP First Application..........\r\n");

out.write("</body>\r\n");

out.write("</html>");

} catch (java.lang.Throwable t) {

if (!(t instanceof javax.servlet.jsp.SkipPageException)){

out = _jspx_out;

if (out != null && out.getBufferSize() != 0)

try {

if (response.isCommitted()) {

out.flush();

} else {

out.clearBuffer();

} catch (java.io.IOException e) {}

if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);

else throw new ServletException(t);

} finally {

_jspxFactory.releasePageContext(_jspx_page_context);

Servlets : to add the response into response object use PrintWriter

JSP : to add the response into response object use JSPWriter

Jsp Day-2
//Predefined support :

Servlet

JSPPage(i) GenericServlet

| |

HttpJspPage(i) HttpServlet

HttpJspBase(c)

trans |

req ----> first.jsp ----> first_jsp.java

Jsppage :

_jspInit()

_jspDestory()

HttpJspPage:

_jspService()

//jsp Life Cycle:

jsp engine : will trslate jsp into servlet.

servlet container : will execute translated servlet.

//Request process

Note: The jsp translation is done only once when send the first request.

from second request onwards directly converted servlet service() executed we will get the response.

//Two models of designing JSPs

1. Jsp Model-1 Architecture

In this model jsp alone responsible to write presentation logics & businness layer & model component.

2. Jsp Model-2 Architecture: MVC

Model ---> java bean classes


=View ----> JSP pages

Cotroller ----> servlets

//Jsp components :

Directives

page

include

taglib

Scritping elements

scriptlets

declarations

expression

comments

jsp action:

standred actions

custom actions

//Implicit objects :

request ----- Javax.servlet.http.HttpServletRequest

response ----- Javax.servlet.http.HttpServletResponse

config ----- Javax.servlet.ServletConfig

application ----- Javax.servlet.ServletContext

session ----- Javax.servlet.http.HttpSession

out ----- Javax.servlet.jsp.JspWriter

page ----- Java.lang.Object

pageContext ----- Javax.servlet.jsp.PageContext

exception ----- Java.lang.Throwable

Scritping elements : To write some java code inside the JSP.

Declarations: used to declare the varaibles & methods

<%!

String uname;

String pwd;

%>
Scriptlets: used to write the block of java code

<%

for (int i=0;i<10;i++)

{ out.println("this is jsp");

%>

<%

uname = request.getParameter("uname");

pwd = request.getParameter("pwd");

%>

expression: To print the data

User name : <%=uname%>

User apssword : <%=upwd>

comments:

java based comments

jsp comments

<%-- sjldkfjskldfj --%>

xml based

<!-- sjldkfjskldfj -->

ex: login Application

//login.html

<html>

<body>

<form action=./LoginAction.jsp method="post">

User name:<input type="text" name="username" /><br>

Password:<input type="password" name="password" /><br>

<input type="submit" value="login">

</form>

</body>

</html>
//LoginAction.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<html>

<body>

<!-- This is declarations -->

<%!

String uname;

String upwd;

%>

<%--This is Block of java code --%>

<%

uname = request.getParameter("username");

upwd = request.getParameter("password");

if(uname.equals("ratan") && upwd.equals("ratan"))

{ out.println("login success");

else

{ out.println("login failure");

%>

<!-- This is printing the data -->

<br/>

user name : <%=uname %>

<br/>

user Password : <%=upwd %>

</body>

</html>

//response implicit object:

<%
uname = request.getParameter("username");

upwd = request.getParameter("password");

if(uname.equals("ratan") && upwd.equals("ratan"))

{ response.sendRedirect("http://www.facebook.com");

else

{ response.sendError(777,"login fail try with valid user name & password");

%>

when we send request to LoginAction.jsp it is translated to LoginAction_jsp.java

E:\advjava9amonline\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\work\Catalina\localhost\JspLoginPage\org\apa
che\jsp

check the converted servlet in above location

1. Declaration tag varaibles becomes instance varaibles of converted servlet.

2. the code of Scriptlets will become logics of _jspService()

3. expression tag varaibles becomes arguments of: out.print(uname);

jsp Day-3

Directives:

page

Page Directive can be used to define the present Jsp page characteristics like to define import statements,
specify particular super class to the translated servlet, to specify metadata about present Jsp pages and so on.

<%@page [attribute-list]%>

language:

This attribute can be used to specify language.

The default value of this attribute is java.

<%@page language="java"%>

contentType:

This attribute will take a particular MIME type in order to give an intimation to the client about to specify the type
of response which Jsp page has generated.

<%@page contentType="text/html"%>

The default value of this attribute is text/html.


import:

This attribute can be used to import a particular packages into the present Jsp pages.

<%@page import="java.io.*"%>

<%@page import="java.io.*",import="java.lang.*"%>

The default values of this attribute are java.lang, javax.servlet, javax.servlet.http,


javax.servlet.jsp.

info :

<%@page info="This is jsp directives....."%>

ex:

<%@ page language="java" contentType="text/html" import="java.util.*"%>

<html>

<body>

<%!Date d=null;%>

<%

d = new Date();

%>

Today Date : <%=d%>

</body>

</html>

errorPage:

This attribute can be used to specify an error page to execute when we have an exception in the present Jsp page.

this attribute used to forward the request to error pages.

<%@page errorPage="error.jsp"%>

isErrorPage:

It is a boolean attribute, it can be used to give an intimation to the container about to allow or not to allow exception
implicit object into the present Jsp page.

If we provide value as true to this attribute then container will allow exception implicit object into the present Jsp page.
If we provide value as false to this attribute then container will not allow exception implicit object into the present Jsp
page.

The default value of this attribute is false.

<%@page isErrorPage=”true”%>

//first.py : here the NullPointerException raised so it forward the request to myerror.jsp

<%@ page language="java" contentType="text/html" import="java.util.*" errorPage="myerror.jsp"%>

<html>

<body>

<%!Date d=null;%>

Today Date : <%=d.toString()%>

</body>

</html>

//myerror.jsp

<%@ page language="java" contentType="text/html" isErrorPage="true"%>

<html>

<body>

Exception info : <%=exception%>

</body>

</html>

buffer:

This attribute can be used to specify the particular size to the buffer available in JspWriter object.

Note: Jsp technology is having its own writer object to track the generated dynamic response, JspWriter will provide very
good performance when compared with PrintWriter in servlets.

<%@page buffer="52kb"%>

The default value of this attribute is 8kb.

autoFlush:

It is a boolean attribute, it can be used to give an intimation to the container about to flush or not to flush dynamic
response to client automatically when JspWriter buffer filled with the response completely.
If autoFlush attribute value is true then container will flush the complete response to the client from the buffer
when it reaches its maximum capacity.

If autoFlush attribute value is false then container will raise an exception when the buffer is filled with the
response.

root cause: java.io.IOException:Error:Jsp Buffer Overflow.

<%@ page language="java" contentType="text/html" buffer="1kb" autoFlush="false"%>

<html>

<body>

<%

for(int i=0;i<100000;i++)

{ out.println(" JSP classes");

%>

</body>

</html>

extends:

This attribute will take a particular class name, it will be available to the translated servlet as super class.

<%@page extends="com.dss.MyClass"%>

Where MyClass should be an implementation class to HttpJspPage interface and should be a subclass to
HttpServlet.

The default value of this attribute is HttpJspBase class

session:

It is a Boolean attribute, it is give intimation to the container about to allow or not to allow session implicit object into the
present Jsp page.The default value of this attribute is true.

<%@page session="true"%> : it enable to session object

<%@page session="false"%> : it desable to session object

isThreadSafe:

It is a boolean attribute, it can be used to give an intimation to the container about to allow or not to allow multiple
number of requests at a time into the present Jsp page.

If we provide true as value to this attribute then container will allow multiple number of requests at a time.

If we provide false as value to this attribute then automatically container will allow only one request at a time and it will
implement SingleThreadModel interface in the translated servlet.
The default value of this attribute is true.

<%@page isThreadSafe="true"%> : multiple threads can access the jsp

the converted servet will not implements : SingleThreadModel

<%@page isThreadSafe="false" %> : only one thred is allow to access this jsp

the converted servet will not implements : SingleThreadModel

isELIgnored:

It is a boolean attribute, it can be used to give an intimation to the container about to allow or not to allow
Expression Language syntaxes in the present Jsp page.

Note: Expression Language is a Scripting language, it can be used to eliminate java code completely from the Jsp pages.

If isELIgnored attribute value is true then container will eliminate Expression Language syntaxes from the present Jsp page.

If we provide false as value to this attribute then container will allow Expression Language syntaxes into the present Jsp
pages.

The default value of this attribute is false.

<%@page isELIgnored="true"%>

The default value in JSP1.2 version is: true.

The default value from JSP2.0 version is: false

9. <jsp:params---->

jsp Day-4

The common code across all JSP pages recommended to write once in a separate JSP page, and include this JSP across all
other JSPs using <%@ include %> directive.

The main advantage with this approach is to promote Reusability and Maintainability.

<%@include file=”--”%>

Where file attribute can be used to specify the name and location of the target resource.

logo.jsp:

<html>

<body><center>

<table width="100%" height="20%" bgcolor="red">


<tr><td colspan="2"><center><b><font size="7" color="white">

Ratan Software Solutions

</font></b></center></td></tr>

</table></center></body>

</html>

footer.jsp:

<html>

<body><center>

<table width="100%" height="15%" bgcolor="blue">

<tr><td colspan="2"><center><b><font size="6" color="white">

copyrights2010-2020@Ratansoftwaresolutions

</font></b></center></td></tr>

</table></center></body>

</html>

body.jsp:

<html>

<body bgcolor="lightyellow">

<center><b><font size="7">

<p><br>

Ratan Software Solutions is one of the Training Institute.

<br><br></p>

</font></b></center></body>

</html>

mainpage1.jsp:

<%@include file="logo.jsp"%>

<%@include file="body.jsp"%>

<%@include file="footer.jsp"%>

mainpage2.jsp:

<%@include file="logo.jsp"%>

<%@include file="body.jsp"%>

<%@include file="footer.jsp"%>
Note : in including mechanism all the dependent file content Is included in main file during translation page hence it is
static inclusion.

include action is dynamic inclusion:

at runtime the data is added.

<jsp:include page="logo.jsp"/>

<jsp:include page="body.jsp"/>

<jsp:include page="footer.jsp"/>

Note :

Include directive is static inclusion : at translation phsase the data is included.

Include action is dynamic inclusion : At runtime the data is included.

Scopes in jsp : There are four scopes in jsp

Page

Request

Session

Application

Page scope:

‘page’ scope means, the JSP object can be accessed only from within the same page where it was created.

The default scope for JSP objects created using <jsp:useBean> tag is page.

JSP implicit objects out, exception, response, pageContext, config and page have ‘page’ scope.

Request scope:

A JSP object created using the ‘request’ scope can be accessed from any pages that serves that request. More than one
page can serve a single request. The JSP object will be bound to the request object.

Implicit object request has the ‘request’ scope.

Session scope :

‘session’ scope means, the JSP object is accessible from pages that belong to the same session from where it was
created. The JSP object that is created using the session scope is bound to the session object.

Implicit object session has the ‘session’ scope.

Application scope:
A JSP object created using the ‘application’ scope can be accessed from any pages across the application. The JSP
object is bound to the application object.

Implicit object application has the ‘application’ scope.

PageContext:

pageContext is a implicit object in jsp of type PageContext object.

pageContext Object used to store the data temprarly any of the the four scopes.

The PageContext object is used to set or get or remove the the attributes form fallowing scopes,

Page

Request

Session

Application

form.html:

<html>

<body>

<form action="welcome.jsp" method="post">

Enter user name = <input type="text" name="uname"/>

<input type="submit" value="submit"/>

</form>

</body>

</html>

Welcome.jsp:-

<%@ page language="java" contentType="text/html"%>

<html>

<body>

<%

String uname = request.getParameter("uname");

pageContext.setAttribute("uname",uname, PageContext.SESSION_SCOPE);

out.println("<a href='second.jsp'>click here to get msg</a>");

%>

</body>

</html>
Second.jsp:-

<%@ page language="java" contentType="text/html"%>

<html>

<body>

<%String uname = (String)pageContext.getAttribute("uname",PageContext.SESSION_SCOPE);

out.println("Welcome="+uname);

%>

</body>

</html>

In Jsp technology, by using scripting elements we are able to provide java code inside the Jsp pages,

but the main theme of Jsp technology is not to allow java code inside Jsp pages.

To eliminate java code from jsp use standred actions.

write the java separate, we can configure the java code using standred actions.

//to configure the bean class

1. <jsp:useBean---->

2. <jsp:setProperty---->

3. <jsp:getProperty---->

//incluse & forward machanisum

4. <jsp:include---->

5. <jsp:forward---->

//to give the input

6. <jsp:param---->

7. <jsp:params---->

//to configure the applet

7. <jsp:plugin---->

8. <jsp:fallback---->

10. <jsp:declaration----> ==== <%! %>

11. <jsp:scriptlet----> ==== <% %>

12. <jsp:expression----> ==== <%= %>


custom action :

<mytag> ----- your class

JSTL: giving some more tags to configure the java code. Just like standred actions.

Jsp Day-5

config ----- Javax.servlet.ServletConfig ----- <init-param>

application ----- Javax.servlet.ServletContext ----- <context-param>

specefic to jsp : config : <init-param>

common to all jsp : application : <context-param>

To give init-param & context param we have to configure the jsp in web.xml

//configuring jsp in web.xml

<web-app>

<servlet>

<servlet-name>FirstJsp</servlet-name>

<jsp-file>/first.jsp</jsp-file>

</servlet>

<servlet-mapping>

<servlet-name>FirstJsp</servlet-name>

<url-pattern>/first</url-pattern>

</servlet-mapping>

</web-app>

//form.html

<html><body>

<a href="first">click here to get First jsp data</a><br>

<a href="second">click here to get Second jsp data</a><br>


</body></html>

//web.xml

<?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"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

id="WebApp_ID" version="3.0">

<display-name>CCJSP</display-name>

<welcome-file-list>

<welcome-file>form.html</welcome-file>

</welcome-file-list>

<context-param>

<param-name>username</param-name>

<param-value>system</param-value>

</context-param>

<context-param>

<param-name>password</param-name>

<param-value>manager</param-value>

</context-param>

<servlet>

<servlet-name>FirstJsp</servlet-name>

<jsp-file>/first.jsp</jsp-file>

<init-param>

<param-name>animal1</param-name>

<param-value>Tiger</param-value>

</init-param>

<init-param>

<param-name>animal2</param-name>

<param-value>Lion</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>FirstJsp</servlet-name>
<url-pattern>/first</url-pattern>

</servlet-mapping>

<servlet>

<servlet-name>aaa</servlet-name>

<jsp-file>/second.jsp</jsp-file>

<init-param>

<param-name>fruit1</param-name>

<param-value>Mango</param-value>

</init-param>

<init-param>

<param-name>fruit2</param-name>

<param-value>orange</param-value>

</init-param>

</servlet>

<servlet-mapping>

<servlet-name>aaa</servlet-name>

<url-pattern>/second</url-pattern>

</servlet-mapping>

</web-app>

//first.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

<%

String ip1 = config.getInitParameter("animal1");

String ip2 = config.getInitParameter("animal2");


String username = application.getInitParameter("username");

String password = application.getInitParameter("password");

%>

Init param1 value : <%=ip1%> <br>

Init param2 value : <%=ip2%> <br>

Context param1 value : <%=username %> <br>

Context param2 value : <%=password%> <br>

</body>

</html>

//second.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

<%

String ip1 = config.getInitParameter("fruit1");

String ip2 = config.getInitParameter("fruit2");

String username = application.getInitParameter("username");

String password = application.getInitParameter("password");

%>

Init param1 value : <%=ip1%> <br>

Init param2 value : <%=ip2%> <br>


Context param1 value : <%=username %> <br>

Context param2 value : <%=password%> <br>

</body>

</html>

ex-2: include & forward action

//login.html

<html>

<body>

<form action=./Login.jsp method="post">

User name:<input type="text" name="username" /><br>

Password:<input type="password" name="password" /><br>

<input type="submit" value="login">

</form>

</body>

</html>

//loginAction.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<html>

<body>

<!-- This is declarations -->

<%!

String uname;

String upwd;

%>

<%--This is Block of java code --%>

<%

uname = request.getParameter("username");
upwd = request.getParameter("password");

if(uname.equals("ratan") && upwd.equals("ratan"))

%>

<jsp:forward page="success.jsp"/>

<%

else

{ out.println("Login Fail enter valid details.....");

%>

<jsp:include page="login.html"/>

<%

%>

</body>

</html>

//success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1" import="java.util.*"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<title>Insert title here</title>

</head>

<body>

<% Date d = new Date();

%>

This is Success JSp file : Your Login Success : <%=d%>

</body>

</html>

JSP Day-6

Jsp Actions :
//to configure the bean class

1. <jsp:useBean----> to configure the bean class

2. <jsp:setProperty----> to set the data

3. <jsp:getProperty----> to get the data

//incluse & forward machanisum

4. <jsp:include---->

5. <jsp:forward---->

//to give the input

6. <jsp:param---->

7. <jsp:params---->

//to configure the applet

7. <jsp:plugin---->

8. <jsp:fallback---->

10. <jsp:declaration----> ==== <%! %>

11. <jsp:scriptlet----> ==== <% %>

12. <jsp:expression----> ==== <%= %>

//emp.html:

<html>

<h5> *******Employee Details********</h5>

<body>

<form method="post" action="main.jsp">

Employee id :<input type="text" name="eid"/><br>

Employee name : <input type="text" name="ename"/><br>

Employee salary :<input type="text" name="esal"/></br>

<input type="submit" value="submit"/>

</form>

</body>

</html>

//main.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>

<html>

<body>

<%! int eid;

String ename;

double esal;

%>

<% eid = Integer.parseInt(request.getParameter("eid"));

ename = request.getParameter("ename");

esal = Double.parseDouble(request.getParameter("esal"));

%>

<jsp:useBean id="eb" class="com.tcs.EmpBean" scope="session"/>

<jsp:setProperty property="eid" name="eb" value="<%=eid%>"/>

<jsp:setProperty property="ename" name="eb" value="<%=ename%>"/>

<jsp:setProperty property="esal" name="eb" value="<%=esal%>"/>

Emp id= <jsp:getProperty property="eid" name="eb"/><br/>

Emp name= <jsp:getProperty property="ename" name="eb"/><br/>

Emp sal= <jsp:getProperty property="esal" name="eb"/><br/>

</body>

</html>

//EmpBean.java

package com.tcs;

public class EmpBean {

private int eid;

private String ename;

private double esal;


public int getEid() {

return eid;

public void setEid(int eid) {

this.eid = eid;

public String getEname() {

return ename;

public void setEname(String ename) {

this.ename = ename;

public double getEsal() {

return esal;

public void setEsal(double esal) {

this.esal = esal;

ex: Configure the applet

//AppletDemo.java

package com.tcs;

import java.applet.Applet;

import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

public class AppletDemo extends Applet {

String msg1, msg2;

public void paint(Graphics g) {

//reading the input message store into varaibles

msg1 = getParameter("message1");

msg2 = getParameter("message2");
//set the font size & style

Font f = new Font("arial", Font.BOLD, 40);

g.setFont(f);

this.setBackground(Color.blue);

this.setForeground(Color.white);

//to print the messsage in applet

g.drawString(msg1, 150, 70);

g.drawString(msg1, 150, 70);

//form.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<body>

<jsp:plugin code="AppletDemo" codebase="AppletDemo" width="200" height="200" type="applet">

<jsp:params>

<jsp:param name="message1" value="ratan software solutions"/>

<jsp:param name="message2" value="naresh software solutions"/>

</jsp:params>

</jsp:plugin>

</body>

</html>

ex-3:

<%@page import="java.util.*"%>

<jsp:declaration>

Date d = null;

String date = null;


</jsp:declaration>

<jsp:scriptlet>

d = new Date();

date = d.toString();

</jsp:scriptlet>

<html>

<body bgcolor="lightyellow">

<center><b><font size="6" color="red"><br><br>

Today Date : <jsp:expression>date</jsp:expression>

</font></b></center></body>

</html>

ex-4: working with the database.

//registrationform.html

<html>

<body bgcolor="lightgreen">

<form action="registration.jsp">

<pre>

<u>Registration Form</u>

Name : <input type="text" name="pname"/>

Age : <input type="text" name="uage"/>

Address : <input type="text" name="uaddr"/>

<input type="submit" value="Registration"/>

</pre>

</form>

</body>

</html>

//existed.jsp:

<center><h1>User Existed</h1></center>

//success.jsp:
<center><h1>Registration Success</h1></center>

//failure.jsp:

<center><h1>Registration Failure</h1></center>

//registration.jsp:

<%@page import="java.sql.*"%>

<%!

String uname;

int uage;

String uaddr;

static Connection con;

static Statement st;

ResultSet rs;

static{

try{

Class.forName("oracle.jdbc.driver.OracleDriver");

con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "ratan");

st=con.createStatement();

catch(Exception e){

e.printStackTrace();

%>

<%

try{

uname = request.getParameter("uname");

uage = Integer.parseInt(request.getParameter("uage"));

uaddr = request.getParameter("uaddr");

rs = st.executeQuery("select * from reg_users where uname='"+uname+"'");


boolean b = rs.next();

if(b==true)

%>

<jsp:forward page="existed.jsp"/>

<%

else

int rowCount=st.executeUpdate("insert into reg_users values


('"+uname+"',"+uage+",'"+uaddr+"')");

if(rowCount == 1)

%>

<jsp:forward page="success.jsp"/>

<%

else

%>

<jsp:forward page="failure.jsp"/>

<%

catch(Exception e){

%>

<jsp:forward page="failure.jsp"/>

<%

e.printStackTrace();

%>

ex: before includeing the target file we can give inpiut to target file.

//main.jsp:

<%@ page language="java" contentType="text/html" %>


<html>

<body>

This is info about main.jsp file<br><br><br>

<jsp:include page="hello.jsp">

<jsp:param name="a" value="10"/>

</jsp:include>

</body>

</html>

hello.jsp:

<%@ page language="java" contentType="text/html" %>

<%@page import="java.util.*"%>

<html>

<head>

<body>

hi this is hello.jsp file content<br>

welcome to Sravyainfotech<br>

<%="Today date ="+new Date()%><br>

<%="param tag value="+request.getParameter("a")%>

</body>

</html>

JSP day-7

<jsp:usebean> -----> to configure the bean class

<mytag:hello> -----> hello.tld tag.class

class MyTagClass implements Tag

{ setPageContext()

setParent()

getPrarent()

doStartTag() ---- here we will write the logics

doEndTag()

release()
}

life cycle methods:

setPageContext()

doStartTag() ---- here we will write the logics

doEndTag()

release()

There are 2 possible return values from doStartTag() method.: talking about body

1. EVAL_BODY_INCLUDE : to execute the body

2. SKIP_BODY : to skip the body

There are 2 possible return values from doEndTag() method. : remaining page

1. EVAL_PAGE : to execute the remaining page

2. SKIP_PAGE : to skip the remaining page

//hello.jsp

<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>

<mytags:hello>

hi ratan how r u

</mytags:hello>

<br>

this is remaining page of jsp

//hello.tld

<taglib>

<jsp-version>2.1</jsp-version>

<tlib-version>1.0</tlib-version>

<tag>

<name>hello</name>

<tag-class>com.tcs.CustomTag</tag-class>

<body-content>jsp</body-content>

</tag>

</taglib>

//CustomTag.java
package com.tcs;

import java.io.IOException;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.JspWriter;

import javax.servlet.jsp.PageContext;

import javax.servlet.jsp.tagext.Tag;

public class CustomTag implements Tag {

PageContext context = null;

@Override

public int doEndTag() throws JspException {

return EVAL_PAGE;

@Override

public int doStartTag() throws JspException {

JspWriter writer = context.getOut();

try {

writer.println("This is Custom Tag first Application");

writer.println("<br>");

} catch (IOException e) {

e.printStackTrace();

return EVAL_BODY_INCLUDE;

@Override

public Tag getParent() {

return null;

@Override

public void release() {

}
@Override

public void setPageContext(PageContext context) {

this.context = context;

@Override

public void setParent(Tag arg0) {

JSP day-8

doAfterBody() contians two return values:

EVAL_BODY_AGAIN

SKIP_BODY

//hello.jsp

<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>

<mytags:iterate times="10"><br>

Hi Ratan how r u

</mytags:iterate>

//hello.tld

<taglib>

<jsp-version>2.1</jsp-version>

<tlib-version>1.0</tlib-version>

<tag>

<name>iterate</name>

<tag-class>com.tcs.IterateTag</tag-class>

<body-content>jsp</body-content>

<attribute>

<name>times</name>
<required>true</required>

<rtexprvalue>true</rtexprvalue>

</attribute>

</tag>

</taglib>

//IterateTag.java

package com.tcs;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.TagSupport;

public class IterateTag extends TagSupport {

private int times;

private int count=1;

public void setTimes(int times) {

this.times = times;

@Override

public int doAfterBody() throws JspException {

if(times>count)

{ count++;

return EVAL_BODY_AGAIN;

else

{ return SKIP_BODY;

@Override

public int doEndTag() throws JspException {

return EVAL_PAGE;

}
@Override

public int doStartTag() throws JspException {

return EVAL_BODY_INCLUDE;

ex2:

//hello.jsp

<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>

<mytags:loop start="1" end="20"><br>

Hi Ratan how r u

</mytags:loop>

remaining page of the JSP

//hello.tld

<taglib>

<jsp-version>2.1</jsp-version>

<tlib-version>1.0</tlib-version>

<tag>

<name>loop</name>

<tag-class>com.tcs.Iteration</tag-class>

<body-content>jsp</body-content>

<attribute>

<name>start</name>

<required>true</required>

</attribute>

<attribute>

<name>end</name>

<required>true</required>

</attribute>

</tag>

</taglib>

//Iteration.java:

package com.tcs;
import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.TagSupport;

public class Iteration extends TagSupport{

private int start;

private int end;

public void setStart(int start) {

this.start = start; }

public void setEnd(int end) {

this.end = end; }

@Override

publicint doAfterBody() throws JspException {

if(end>start)

{ start++;

returnEVAL_BODY_AGAIN; }

else

{ returnEVAL_PAGE; }

@Override

public int doStartTag() throws JspException {

return EVAL_BODY_INCLUDE;

ex-3:

//hello.jsp

<%@taglib uri="/WEB-INF/hello.tld" prefix="mytags"%>

<mytags:if condition='<%=10<20%>'>

<mytags:true>condition is true</mytags:true><br>

<mytags:false>condition is false</mytags:false><br>

</mytags:if>

rest of the JSP code

//If.java

package com.tcs;
import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.TagSupport;

public class If extends TagSupport {

private boolean condition;

public void setCondition(boolean condition) {

this.condition = condition;

public boolean getCondition()

{ return condition;

@Override

public int doStartTag() throws JspException {

return EVAL_BODY_INCLUDE;

//True.java

package com.tcs;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.TagSupport;

public class True extends TagSupport {

@Override

public int doStartTag() throws JspException {

If f = (If)getParent();

boolean b = f.getCondition();

if(b==true)

{ return EVAL_BODY_INCLUDE;

else {

return SKIP_BODY;

}
//False.java

package com.tcs;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.TagSupport;

public class False extends TagSupport {

@Override

public int doStartTag() throws JspException {

If f = (If)getParent();

boolean b = f.getCondition();

if(b==true)

{ return SKIP_BODY;

else

{ return EVAL_BODY_INCLUDE;

//hello.tld:

<taglib>

<jsp-version>2.1</jsp-version>

<tlib-version>1.0</tlib-version>

<tag>

<name>if</name>

<tag-class>com.tcs.If</tag-class>

<body-content>jsp</body-content>

<attribute>

<name>condition</name>

<required>true</required>

<rtexprvalue>true</rtexprvalue>

</attribute>

</tag>

<tag>

<name>true</name>

<tag-class>com.tcs.True</tag-class>
<body-content>jsp</body-content>

</tag>

<tag>

<name>false</name>

<tag-class>com.tcs.False</tag-class>

<body-content>jsp</body-content>

</tag>

</taglib>

JSp Day-9 : JSTL

C:\Program Files\Apache Software Foundation\Tomcat 9.0\webapps\examples\WEB-INF\lib

ex1:

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

<%@page isELIgnored="true"%>

<html>

<body>

<center><b><font size="7">

<c:set var="a" value="AAA" scope="request"/>

<br>

<c:out value="core tag library"/>

<br><br>

<c:out value="${a}"/>

</font></b></center>

<body>

<html>

ex-2:

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

<%@page isELIgnored="true"%>

<html>

<body>

<center><b><font size="7">

<c:set var="a" value="AAA" scope="request"/>

<br>
a-----><c:out value="${a}"/>

<br><br>

<c:remove var="a" scope="request"/>

a-----><c:out value="${a}"/>

</font></b></center>

<body>

<html>

ex-3:

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

<%@page isELIgnored="true"%>

<html>

<body>

<center><b><font size="7">

<c:catch var="e">

<jsp:scriptlet>

java.util.Date d=null;

out.println(d.toString());

</jsp:scriptlet>

</c:catch>

<c:out value="${e}"/>

</font></b></center>

<body>

<html>

ex-4:

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

<%@page isELIgnored="true"%>

<html>

<body>

<center><b><font size="7">

<c:set var="a" value="10"/>

<c:set var="b" value="20"/>

<c:if test="${a<b}">

condition is true

</c:if>
<br>

out of if

</font></b></center>

<body>

<html>

ex-5:

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

<%@page isELIgnored="true"%>

<html>

<body>

<center><b><font size="7">

<c:set var="a" value="10"/>

<c:choose>

<c:when test="${a==10}">

TEN

</c:when>

<c:when test="${a==15}">

FIFTEEN

</c:when>

<c:when test="${a==20}">

TWENTY

</c:when>

<c:otherwise>

Number is not in 10,15 and 20

</c:otherwise>

</c:choose>

</font></b></center>

<body>

<html>

ex-6:

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

<%@page isELIgnored="true"%>

<html>

<body>
<center><b><font size="7">

<c:forEach var="a" begin="0" end="10" step="2">

<c:out value="${a}"/><br>

</c:forEach>

<%

String[] s={"A","B","C"};

request.setAttribute("s",s);

%>

<br>

<c:forEach var="x" items="${s}">

<c:out value="${x}"/><br>

</c:forEach>

</font></b></center>

<body>

<html>

ex-7:

second.jsp:

<center><h1>This is second.jsp</h1></center>

core7.jsp:

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

<%@page isELIgnored="true"%>

<html>

<body>

<center><b><font size="7">

Start

<br>

<c:import url="second.jsp"/>

<br>

End

</font></b></center>

<body>

<html>
ex-8:

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

<%@page isELIgnored="true"%>

<html>

<body>

<center><b><font size="7">

<c:redirect url="http://facebook.com"/>

</font></b></center>

<body>

<html>

SQL data :

ex-1:

<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>

<%@taglib uri="http://java.sun.com/jstl/sql_rt" prefix="sql"%>

<%@page isELIgnored="true"%>

<html>

<body>

<center><b><font size="7">

<sql:setDataSource driver="oracle.jdbc.driver.OracleDriver"

url="jdbc:oracle:thin:@localhost:1521:xe"

user="system" password="ratan"/>

<sql:update var="result" sql="create table anish(id number,name varchar2(10),sal number)"/>

Table created success fully.....

</font></b></center>

</body>

</html>

ex 2:

<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>

<%@taglib uri="http://java.sun.com/jstl/sql_rt" prefix="sql"%>

<%@page isELIgnored="true"%>

<html>

<body>
<center><b><font size="7">

<sql:setDataSource driver="oracle.jdbc.driver.OracleDriver"

url="jdbc:oracle:thin:@localhost:1521:xe"

user="system" password="ratan"/>

<sql:update var="result" sql="insert into anish values(111,'aaa',5000)"/>

<sql:update var="result" sql="insert into anish values(222,'bbb',6000)"/>

<sql:update var="result" sql="insert into anish values(333,'ccc',7000)"/>

Data inserted successfully...........

</font></b></center>

</body>

</html>

ex 3:

<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>

<%@taglib uri="http://java.sun.com/jstl/sql_rt" prefix="sql"%>

<%@page isELIgnored="true"%>

<html>

<body>

<center><b><font size="7">

<sql:setDataSource driver="oracle.jdbc.driver.OracleDriver"

url="jdbc:oracle:thin:@localhost:1521:xe"

user="system" password="ratan"/>

<sql:update var="result" sql="insert into anish values(?,?,?)">

<sql:param value="444"/>

<sql:param>anu</sql:param>

<sql:param value="40000"/>

</sql:update>

Data inserted successfully......

</font></b></center>

</body>

</html>

ex 4:

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

<%@taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%>


<%@page isELIgnored="true"%>

<html>

<body>

<center><b><font size="7">

<sql:setDataSource driver="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:xe" user="system" password="ratan"/>

<sql:update var="result">

update anish set esal=esal+? where esal>?

<sql:param>500</sql:param>

<sql:param>5000</sql:param>

</sql:update>

Row Count ...... <c:out value="${result}"/>

</font></b></center></body>

</html>

ex-5:

<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>

<%@taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%>

<%@page isELIgnored="true"%>

<html>

<body>

<center><b><font size="7">

<sql:setDataSource driver="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:xe" user="system" password="ratan"/>

<sql:query var="result" sql="select * from emp"/>

<table border="1" bgcolor="lightyellow">

<tr>

<c:forEach var="columnName" items="${result.columnNames}">

<td><center><b><font size="6" color="red">

<c:out value="${columnName}"/>

</font></b></center></td>

</c:forEach>

</tr>

<c:forEach var="row" items="${result.rowsByIndex}">

<tr>
<c:forEach var="column" items="${row}">

<td><b><font size="5">

<c:out value="${column}"/>

</font></b></td>

</c:forEach>

</tr>

</c:forEach>

</table>

</font></b></center>

</body>

</html>

ex:

You might also like