Download - jsp Basics

Transcript
Page 1: jsp Basics

JSP Jsp is a web technology function which is used to develop server side web components. Jsp will be used in presentation layer. Complete jsp life cycle will be taken care by web container. Jsp page is combination of HTML elements and JSP elements.

Following is the list of JSP elements: ----------

1. Scripting elements Scriplets Expressions Declarations

2. Directives Page directives Include directives taglib directives

3. Standard Action <jsp:include> <jsp:forward> <jsp:param> <jsp:useBean> <jsp:setProperty> <jsp:getProperty>

4. Custom elements(Tags)

Syntax: ----------<% ---- ---- ---- ---- ---- %>

Scriplets is used to write any valid java statement. All the elements inside the Scriplets must be terminated by semicolon.

Example: --------<% int a=10;out println(a); // Implicit object%>

All the statements inside the Scriplets will be placed inside the service() method of translated servlet.

Scripting Elements

Information About JSP by JLC

[email protected]

Page 2: jsp Basics

Syntax: ------------------<%=exp %>Exp:-----<%=”sri”%><%=a%><%=obj.m1();%> X(invalid)

Expression is a short-cut form of out.println. All the expression inside the JSP’s will be placed inside the service() method of translated

servlet .

Syntax:---------- <% ! ------ ----- ----- ----- ---- %> It is used to write variable declaration and method definition. Java statement are not allowed inside the declaration all the declaration inside the JSP will be placed directly inside the translated servlet class

and outside the service() method.Exp: ----------

<% ! Void m1(){System.out.println(“Hello”);}int a ;

%> Hello.jsp Hello-jsp.java

<html><body><h1>I am the Scriplets<% int a=10;out.println (“Hello ------“);out.println (a);

Package org.apache.jsp;Import javax.servlet.*;Import javax.servlet.http.*;Import javax.servlet.jsp.*;Public final class Hello-Jsp extends HttpJspBase{Int x=99;Void m1()

Expression

Declaration

Hello.jsp

Page 3: jsp Basics

out.println(x);m1();%><h1> I am the expression<%=”hai--------”%><h1> I am the declaration<%! Int x=99;Void m1(){System.out.println(x);System.out.println(“m1”);}%>

{System.out.println(x);System.out.println(“m1”);}Public void -JSPService(HttpServletRequest req,HttpServletResponse res)throws java.io.IO Exception ,ServletException{

1) Page context page context=null;2) HttpSession session=null;3) Servlet context application= null;4) Servlet config config=null;5) JspWriter out=null;6) Object page=this;

Response.setContentType(“text/html”);PageContext= ----- ------Application=pageContext.getSession();Out=pageContext.getOut();out.write(“<html>\r\n<body>\r\n <h1> I am the Scriplets\r\n”);Int a=10;out.println(“Hello-----------------!”);out.println(a);out.println(x);m1();out.writer(“\r\n<h1> I am expression\r\n”);out.print(“hai----------“);out.write(“\r\n<h1> I am the declaration \r\n”);out.write(“\n”);}}

<% @ page language=”java”extends=”some class”import=”pack1,pack2”Session=”true/false”IsThreadSafe=”true/false”errorPage=”some Jsp”IsErrorPage = “true/false”IsELIgnore = “true/flase” %>

This attribute is used to specify the language whose statements are allow inside the Scriplets.

Directives

Page directive

Language

JSPBy Mukesh

Page 4: jsp Basics

Currently only valid value for this attribute is “java “. if you give other value for this you can get the error called “invalid language attribute”.

When you developing servlets we are taking HttpServlet as super class asClass HelloServlet extend HttpServlet {---------- ------------ ---------- }

When container is generating the servlet container take HttpJSPBase as supper classClass test-Jsp extends HttpJSPBase {-------- ------- ------ }

If you want to change the supper class what container is taking by default when it is generating the servlet you can use extends attributes

when you are changing the supper class from HttpJSPBase to HttpServlet then you need to override any one of the methods available in HttpServlet.

Import attribute is used to specify the package which you want to import for the translated servlet class.

Extends

If I want to implement something inside the init and destroy method of the servlet. what I have to do?

In Jsp you have to implement JspInit() and JspDestroy() method in the declaration sectionExample :----------

<%! Public void JSPInit(){System.out.println(“JSPInit()”);}Public void JSPDestroy(){System.out.println(“JSPDestroy()”);}%>

Can I override _JSPService() method inside declaration section?No, because when you override _JSPService method there will two _JspService() methods inside the translated servlet. One from you and another from container.Having two methods inside the class with the same name and same method signature is invalid.

What is the Jsp life cycle method? JspInit() _JspService() JspDestroy()

Why there is _ for the JspService method?It show that override method is not possible .

Import

JSPInit()&

JSPDestroy()

Page 5: jsp Basics

you can specify the multiple package with the comma “,”separation.<%@ page import=”java.util.*,java.sql.*,javax.sql.*”%>

Possible values for this attributes are true/false default value is true.If you specify the session value as false then session implicit object will be disabled. Example: -------

<%@ page Session=”false”%> Because of the above statement you are unable to use session implicit object inside the

JSP.

Container follows two models for the servlet: ----------- Multi Thread model Single Thread Model

In multi Thread Model only one instance will be created for the servlet and multiple thread will be created to serve multiple request.

In single thread model multiple instances will be created for the one servlet to provide the service to multiple request multi thread model is better than single thread model.

The default model what container is following is multithread model.When you writing the servlet by extending HttpServlet as supper class to follow the single thread model to servlet class must implement single thread model marker interface which is available in javax.servlet package.

Class HelloServlet extends HttpServlet implements single Thread Model{

-------------- ----------- --------------}

In the case of Jsp . if you want to follow single thread model you have to specify the page directive as follows:---

<%@page isThreadSafe=”false”%>

Session attribute

IsThreadSafe

errorPage or IsErrorPage<%@page errorPage=”error.jsp”%>

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

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

<%@page isErrorPage=”true”%>

Page 6: jsp Basics

When you are writing the java code inside the Jsp’s. you may get exception inside that to handle the exception you need to write try, catch blocks many times in all the Jsp’s .to avoid the try ,catch block and to centralize the exception handling use errorPage or IsErrorPage attribute inside the JSP’s where you want to handle all the exceptions. Enable the exception implicit objects by writing the following: ------------

<%@ page isErrorPage=”true”%>Test.jsp

<% @ page errorPage=”errors.jsp”%><h1>hello guys<%int x=10/0;String s=session.getAttribute(“A”).toString();out.println(s); %>

errors.jsp<% @ page isErrorPage=”true”%><h1>I am handling exceptions<br><% out.println(“exception”); %>

It is used to include one Jsp or Html to another JSP.Syntax: ------

<% @ include file=”some jsp(or) some Html”%><% @ include file=”/header.jsp”%><% @ include file=”/login.jsp”%><% @ include file=”/book.html”%>

it is used to use the custom tags developed by you in JSP & also used to use JSTL tags inside the JSP.

<%@taglib uri=”some uri” prefix=”some prefix”%>JSP standard Actions

<jsp:include> <jsp:forward> <jsp:param> <jsp:useBean> <jsp:setProperty> <jsp:getProperty>

<jsp:include>Include tag is used to include one jsp or html inside other jsp.

Syntax:----<jsp:include page=”some jsp or html”/>

Example <jsp:include page=”header.jsp” />

Include directive

Taglib directive

Page 7: jsp Basics

Include tag functionality is similar to include() method of request Dispatcher.<JSP:forward>

Forward tags used to forward the request from one jsp to another jsp or html. In this same request, response from one JSP is given as request, response to other JSP.

<jsp:forward page=”some jsp or html”/><jsp:forward page=”home.jsp”/>

Forward tag functionality is similar to forward() method of requestDispatcher.Param tag

Param tag is used to pass the parameters when you are forwarding the request from one jsp to another JSP or when you including one JSP to another JSP.

Param tag must be used always along with forward and include.Exp:--------------

<jsp:param name=”sid” value=”99”/>For include

For forward

Use Bean tag is used the java beans in JSP. setProperty is used to assign the value to the property of the java bean. getPropery is used to get the value of the property from the java Bean.

Student.javapackage com.jlc;public class Student{private String sid;private String sname;private String email;private String phone;public void setSid(String sid){

<%@ page import="com.jlc.*"%><h1>this jsp is adding Student object to session<br>open y.jsp and check the data.....

x.jsp<jsp:include page=”header.jsp”><jsp:param name=”cname” value=”JLC”/></jsp:include>

Header.jsp <%cn=r.getParameter(“cname”);Out.println(cn)%>

x.Jsp <jsp:forward page=”y.jsp”>

<jsp:param name=”sname value=”sn”/><jsp:param=”sid” value=”99”/>

</jsp:forward>

y.jsp<% sid=request.getParameter(“sid”);sname=request.getParameter(“sname”); %>

header.Jsp <jsp:useBean><jsp:setProperty>,<jsp:getProperty><jsp:useBean id=”some obj”Scope=”some scope”/><jsp:setProperty name=”some obj” property=”some property value=”some vbalue”/><jsp:getProperty name=”some obj” property=”some property”/>

x.jspStudent.java

Page 8: jsp Basics

this.sid=sid;}public void setSname(String sname){this.sname=sname;}public void setEmail(String email){this.email=email;}public void setPhone(String phone){this.phone=phone;}public String getSid(){return sid;}public String getSname(){return sname;}public String getEmail(){return email;}public String getPhone(){return phone;} }

<%Student stu=new Student();stu.setSid("99");stu.setSname("sri");stu.setEmail("[email protected]");stu.setPhone("9999");session.setAttribute("STU",stu);%>

<%@ page import="com.jlc.*"%><%Object o=session.getAttribute("STU");Student stu=null;if(o!=null){stu=(Student)o;}%><h1>Sid:<%=stu.getSid()%><br>Sname<%=stu.getSname()%><br>Email:<%=stu.getEmail()%><br>Phone:<%=stu.getPhone()%>

X1.Jsp y1.Jsp <%@ page import="com.jlc.*"%><h1>this jsp is adding Student object to session<br>open y1.jsp and check the data..<jsp:useBean id="stu1" class="com.jlc.Student"scope="session"/><jsp:setProperty name="stu1" property="sid" value="88"/><jsp:setProperty name="stu1" property="sname" value="srinivas"/><jsp:setProperty name="stu1" property="email" value="srinivas"/>

<%@ page import= "com.jlc.*"%><h1>Sid:<jsp:getProperty name="stu1" property="sid"/><br>Sname:<jsp:getProperty name="stu1" property="sname"/><br>Email:<jsp:getProperty name="stu1" property="email"/><br>Phone:<jsp:getProperty name="stu1" property="phone"/>

y.jsp

This is 1st

JSPprogram

JLC

RAMANSHYAM

01-jun-2008

Custom tag development

Page 9: jsp Basics

Steps to develop custom tags:---------- Write one TLD file (with extension *.tld)(tag library descriptor) – contains description

about your tag Write one tag handler java class Write the <taglib> tag inside the web.xml. After developing the tag use that tag in any jsp by writing one taglib directive inside the

Jsp.

x.Jsp <%@ taglib uri="/WEB-INF/jlc.tld" prefix="sd"%><sd:hello name="vas"/><sd:hello/> // wrong according to our requirement

Here sd //prefix Hello // tag name

Name // attribute name Sri // attribute value

o/p of x.jsphello,sri welcome to JLCyour email is [email protected],vas welcome to jlcyour email is not specified

web.xml<taglib><tlib-uri>WEB-INF/jlc.tld<tlib-uri><tlib-location>WEB-INF/jlc.tld</tlib-location></taglib>

Jlc.tld <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"><taglib><tlibversion>1.0</tlibversion><jspversion>1.1</jspversion><uri>/WEB-INF/jlc.tld</uri><tag><name>hello</name><tagclass>com.jlc.HelloTagHandler</tagclass><bodycontent>empty</bodycontent><attribute><name>name</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute>

Page 10: jsp Basics

<attribute><name>email</name><required>false</required></attribute></tag></taglib>

HelloTagHandler.javapackage com.jlc;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;public class HelloTagHandler extends TagSupport{String name;String email;

public void setName(String name){this.name=name;System.out.println(name);}public void setEmail(String email){this.email=email;System.out.println(email);}

public int doEndTag() throws JspException{try{String msg="Hello"+" "+name+" "+"welcome to jlc";if(email!=null||email.length()!=0){msg=msg+" "+"email is "+email;}else{msg=msg+" "+"email is not specified";}JspWriter out=pageContext.getOut();out.write("<h1>"+msg+"</h1>");}catch(Exception e){System.out.println(e);}return EVAL_PAGE;} }

Tracing First it will take the prefix(minatory ) and compare this prefix with prefix written in

<taglib> If it ok then through this prefix it takes the uri from <taglib> Then it compare this uri and uri given in web.xml If they are same then it takes the name of the tld file (location) and checks whether

this type of file is present or not. If yes then it load the tld file and create instances of this class.

Then it checks the tag name which should be same as x.jsp file and also attribute name should be same as x.jsp file if we wouldn’t (as in x.jsp) that attribute name=”name is mandatory in our custom tag then in jlc.tld write like

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

If any attribute name is not mandatory like email in x.jsp then write as <name>email</name>

HelloTagHandler.java

Page 11: jsp Basics

<required>false</required>

After that it checks whether given tag handler class are present or not If it is there then it load the given taghandler class as given above in example Create the instances(same as x.jsp) At last it calls the doEndtag() method and returns EVAL-PAGE

Try to implement the following: -------------

Files required: --------- Search.jsp Results.jsp Jlc.tld showStudenttag.java web.xml

search.jsp results.jsp <html><body><h1>search</h1><form action="/results.jsp"><h2>enter sid<br><input type="text" name="sid"/><br><input type="submit" value="show"/><br></form></body><html>

<%@ taglib uri="/WEB-INF/jlc.tld" prefix="sd"%><html><body><h1> searchresult</h1><%String sid=request.getParameter("sid");%><sd:showStudent sid="<%=sid%>"/></body></html>

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"><taglib><tlibversion>1.0</tlibversion><jspversion>1.1</jspversion><uri>/WEB-INF/jlc.tld</uri><tag><name>showStudent</name><tagclass>com.jlc.ShowStudentTag</tagclass><bodycontent>empty</bodycontent><attribute>

package com.jlc;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;public class ShowStudentTag extends TagSupport{private String sid=null;public void setSid(String sid){this.sid=sid;}public String getSid(){return sid;

Enter sid ----- Searching

<taglib><tlib-uri>WEB-INF/jlc.tld<tlib-uri><tlib-location>WEB-INF/jlc.tld</tlib-location></taglib>

Web.xml

ShowStudentTag.java

Jlc.tld

Page 12: jsp Basics

<name>sid</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute></tag></taglib>

}public int doEndTag() throws JspException{try{//call modelString sname="srinivas";String email="[email protected]";String phone="9999";JspWriter out=pageContext.getOut();if(sid.equals("99")){out.write("<table border=2 bgcolor=cyan>");out.write("<tr>");out.write("<td>Sid</td>");out.write("<td>"+sid+"</td>");out.write("</tr>");out.write("<tr>");out.write("<td>Sname</td>");out.write("<td>"+sname+"</td>");out.write("</tr>");out.write("<tr>");out.write("<td>Email</td>");out.write("<td>"+email+"</td>");out.write("</tr>");

continue

To simplify the developer task SUN has implemented some custom tags for the commonly used that scenario .As a jsp developer we can use the JSTL tag directly in the JSP.

In the JSTL we have following four types of tags JSTL core tags JSTL formatting tag JSTL xml/xsl tag JSTL sql tags(not use directly in JSP)

JSTL core tags:----------------- To use JSTL tag in JSP you need to write the following taglib directive in the JSP.

<%@ taglib uri=http://java.sun.com/jsp/jstl/core prefix=”sd”%> //prefix=”some thing”

You should copy the following two jar file in your web application lib folder. JSTL.jar Standard.jar

out.write("<tr>");out.write("<td>Phone</td>");out.write("<td>"+phone+"</td>");out.write("</tr>");out.write("</table>");}else{out.write("<h1>Student not found");}}catch(Exception e){System.out.println(e);}return EVAL_PAGE;}}

JSTL JSP Standard Tag Library

Page 13: jsp Basics

After copy the other side to lib restart the server

Following are the list of JSTL core tags <sd:set> <sd:remove> <sd:out> <sd:if> <sd:choose> <sd:when>

<sd:otherwise> <sd:forEach> <sd:import> <sd:catch> <sd:param>

Example: ---------<%@ page isELIgnored="false"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="sd"%><sd:set var="email" scope="session" value="[email protected]"/><h1>Email:${email}<br><sd:remove var="email" scope="session"/>Email:${email}<br><sd:set var="sname" scope="request" value="sri"/>Sname:<sd:out var="sname"/>Sname:${sname}<sd:if test="${sname eq 'sri'}">this student name is srinivas...</sd:if><sd:if test="${sname ne 'sri'}">this student name is not srinivas...</sd:if>

Set tag is used to declare a variable to the given name and initialized the variable with the given value and stores the variable in specified scope.

Remove tag is used to remove the specified variable from specified scope. Out tag is used to display the value of specified variable. If tag is used to perform simple conditional checks.

Example :-----<%@ page isELIgnored="false"%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="sd"%><sd:set var="sid" scope="session" value="99"/><font color="red">Sid:${sid}<br></font><sd:choose><sd:when test="${sid eq '99'}"><h1>student id is 99</h1></sd:when><sd:when test="${sid eq '88'}"><h1>student id is 88</h1>

Page 14: jsp Basics

</sd:when><sd:when test="${sid eq '77'}"><h1>student id is 77</h1></sd:when><sd:otherwise><h1> student id is unknown</h1></sd:otherwise></sd:choose>

Syntax for EL: --------${object name: object name}

Any valid EL implicit object Any parameter or header or cookie or attribute name

Following are the list of EL implicit objects :------------------------------ Param ParamValues RequestScope PageScope SessionScope ApplicationScope *.pageContext

In a JSP by default scripting elements will be unable and EL statement/expression will be disabled.

To enable the EL expression in JSP you need to use following page directives<%@ page isELIgnored=”false”%>

Implement the following core tag with the given attributesOut nameSet more value scopeRemove name scopeIf check(some condition)

y.jsp with EL

Files required :---------------- jlc.tld JspUtil.java OutTag.java

EL (Expression Language )

Name is ${param.sn}Email is ${param.em}Phone is ${param.ph}

Question

Page 15: jsp Basics

RemoveTag.java SetTag.java test.jsp web.xml

jlc.tld

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> x.jsp <taglib><tlibversion>1.0</tlibversion><jspversion>1.1</jspversion><uri>/WEB-INF/jlc.tld</uri><tag><name>set</name><tagclass>com.jlc.SetTag</tagclass><bodycontent>empty</bodycontent><attribute><name>name</name><required>true</required><rtexprvalue>true</rtexprvalue> y.jsp with scriptlet</attribute><attribute><name>value</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>scope</name></attribute></tag>

Continue <tag><name>remove</name><tagclass>com.jlc.RemoveTag</tagclass><bodycontent>empty</bodycontent><attribute><name>name</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>scope</name></attribute></tag> continue

<tag><name>out</name><tagclass>com.jlc.OutTag</tagclass><bodycontent>empty</bodycontent><attribute><name>name</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute><attribute><name>scope</name></attribute></tag></taglib>

SN

Email

Phone

Submit

<%String sn=request.getParameter(“SN”)String em= request.getParameter(“em”)String ph= request.getParameter(“ph”)out.println(Name is”+SN);out.println(Email is”+em);out.println(Phone is”+ph);

%>

Page 16: jsp Basics

OutTag.java

package com.jlc;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;public class OutTag extends TagSupport{String name=null;String scope=null;public void setName(String name){this.name=name;}public String getScope(){return scope;}public void setScope(String scope){this.scope=scope;}public int doEndTag() throws JspException{String val="";try{if(!JspUtil.isEmpty(scope)){if(scope.equals("page")){val=pageContext.getAttribute(name,pageContext.PAGE_SCOPE).toString();}else if(scope.equals("request")){val=pageContext.getAttribute(name,pageContext.REQUEST_SCOPE).toString();}elseif(scope.equals("session")){val=pageContext.getAttribute(name,pageContext.SESSION_SCOPE).toString();}else

Files required :-------------

jlc.tld JspUtil.java OutTag.java RemoveTag.java SetTag.java test.jsp web.xml

Page 17: jsp Basics

{val=pageContext.getAttribute(name,pageContext.APPLICATION_SCOPE).toString();}}else{val=pageContext.getAttribute(name,pageContext.PAGE_SCOPE).toString();}JspWriter out=pageContext.getOut();out.write(val);}catch(Exception e){System.out.println(e);}return EVAL_PAGE;}}

RemoveTag.java

package com.jlc;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;public class RemoveTag extends TagSupport{String name=null;String scope=null;public String getName(){return name;}public void setName(String name){this.name=name;}public String getScope(){return scope;}public void setScope(String scope){this.scope=scope;

Files required :-------------

jlc.tld JspUtil.java OutTag.java RemoveTag.java SetTag.java test.jsp web.xml

Information About JSP by JLC

[email protected]

Information About JSP by JLC

[email protected]

Page 18: jsp Basics

}public int doEndTag() throws JspException{

try{if(!JspUtil.isEmpty(scope)){if(scope.equals("page")){pageContext.removeAttribute(name,pageContext.PAGE_SCOPE);}else if(scope.equals("request")){pageContext.removeAttribute(name,pageContext.REQUEST_SCOPE);}elseif(scope.equals("session")){pageContext.removeAttribute(name,pageContext.SESSION_SCOPE);}else{pageContext.removeAttribute(name,pageContext.APPLICATION_SCOPE);}}else{pageContext.removeAttribute(name,pageContext.PAGE_SCOPE);}}catch(Exception e){System.out.println(e);}return EVAL_PAGE;}}

SetTag.javapackage com.jlc;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;public class SetTag extends TagSupport{String name=null;

Files required :-------------

jlc.tld JspUtil.java OutTag.java RemoveTag.java SetTag.java test.jsp web.xml

Page 19: jsp Basics

String value=null;String scope=null;public String getName(){return name;}public void setName(String name){this.name=name;}public String getValue(){return value;}public void setValue(String value){this.value=value;}public String getScope(){return scope;}public void setScope(String scope){this.scope=scope;}public int doEndTag() throws JspException{try{if(JspUtil.isEmpty(scope)){pageContext.setAttribute(name,value,pageContext.PAGE_SCOPE);}else{if(scope.equals("page")){pageContext.setAttribute(name,value,pageContext.PAGE_SCOPE);}else if(scope.equals("request")){pageContext.setAttribute(name,value,pageContext.REQUEST_SCOPE);}elseif(scope.equals("session"))

Information About JSP by JLC

[email protected]

Information About JSP, ANT &Log4J by

[email protected]

Page 20: jsp Basics

{pageContext.setAttribute(name,value,pageContext.SESSION_SCOPE);} else {pageContext.setAttribute(name,value,pageContext.APPLICATION_SCOPE);} }}catch(Exception e){ System.out.println(e); }return EVAL_PAGE;}}

test.jsp JspUtil.java<%@ taglib uri="/WEB-INF/jlc.tld" prefix="sd"%><sd:set name="sid" value="99" scope="session"/><sd:set name="sname" value="sri"/><br>Sid:<sd:out name="sid" scope="session"/><br>Sname:<sd:out name="sname" scope="request"/><sd:remove name="sname"/><sd:remove name="sid"/><br>Sid:<sd:out name="sid" scope="session"/><br>Sname:<sd:out name="sname"/>

package com.jlc;public class JspUtil{public static boolean isEmpty(String str){if(str==null||str.length()==0){return true;}return false;}}

There are ten EL implement object: ------------- PageContext ParentValue Header

Implement the following custom tagsSet tag: -------

Attribute:-- name, value, scopeNote :---- name ,value, attribute are mandatory and scope is optional. if scope is not specify, then the default scope is page.Remove tag: ----------

Attribute:-- name, scope.Note :------- name is mandatory and scope is optional. When scope is not specified, it has to verify in all the scopes Out tag:--------

Attributes:-- name , scopeNote :------- name is mandatory and scope is optional, when scope is verify in all the scope starting from page and display the 1st occurrence only.

Method of JSP

Page 21: jsp Basics

HeaderValue Param Cookie pageScope requestScope sessionScope applicationScope

Catch tag:---------Catch tag is used to finding the exception inside the jsp without writing try & catch block inside the Scriplets.Example:----

<% @ taglib<h1>I am before catch<br><sd:catch><%

Int x=10/0;%>I am inside catch</sd:catch>I am after catch<br>

Import tag :-------------It allows to implement the files from other server also but include always from the same server.

Import tag is used to include the contents of JSP or HTML within other JSP’s.<sd:import url=”/hello.jsp”/> // within the application (abc.com.hello)<sd:import url=http://www.hello.html/> (with different application)

Similarly task you can do with include directive and include actions but these two will allow to include the resource(html/jsp) from the same application only.JSTL’s import tag allows to include the jsp from the same application and also from different application.

Interface iteration Tag extends Tag{Int EVAL-BODY_AGAIN;

Can I include one JSP in another JSP using include directive. How can I pass parameter?No way.

Can I include one JSP in another JSP using include action. How can I pass parameters using jsp:param tag ?<jsp:include page=”y.jsp”><jsp param name=”a” value=”10”/></jsp.include>

Can I include one JSP in another JSP using JSTL import tag. how can I pass the parameter.Using JSTL param tag.<sd import url=”hello.jsp”/>Sd param name=”x” value =”10”/></sd:import> Question -------------Answer

Page 22: jsp Basics

Public abstract int doAfterBody();}

i

i

i

c

c c

int doStartTag() int doEndTag() int doAfterBody() void doInitBody() set BodyContent(BodyContent)

list of integer constants which can be returned by custom tag Life Cycle methods:-------

public static final int SKIP_BODY;int EVAL_BODY_INCLUDE;int SKIP_PAGEint EVAL-PAGEint EVAL-BODY-TAGint EVAL-BODY –BUFFERED

When the tag is encountered in JSP first prefix of the tag will be taken and container verifies to check any taglib directive is specified.

If no taglib director found then tag will be ignored.

Tag

Iteraton TagBody tag

TagSupport

TagSupportTagSupport

TagHandler class life cycle method or custom tag life cycle methods

Flow of custom tag execution

Page 23: jsp Basics

If any matching taglib directive is found then URI of the taglib directive will be taken. Container verifies web.xml to check whether it contains any taglib tag with the same URI

with the URI found in the JSP if taglib tag is not found inside the web.xml then container search for tld file in the WEB-INF folder and four sub-levels under WEB-INF.

If the taglib tag is found in the web.xml then the location of the tld file will betaken. If the tld file is not found in the location specified by you in the web.xml or sub-folder of

WEB-INF then you get an exception with the message “file not found” If the tld file is not found somewhere then URI found in the JSP will be compared with

URI specified in tld file. If not matching will be found then exception will be thrown.

If matching found then following things will happened: ------------------

a) Tag name of the JSP will be taken and will be verified in the “tld file”.b) If the tag is not found in the tld file then following error message will be display.

“No tag set1” defined in the tag library method imported with the prefix “sd”.c) If the tag is found in the tld file then all the attributes will be verified according to tld.

d) If All the attributes used in the tag or according to TLD then TagHandler class will taken and will be verified in the given package.

e) If the class is not available then class not found exception will be thrown.f) If the class is found then it (container) load the class and create the instances of the class.g) After instantiating the classHandler class, following is the life cycle diagram

Implement the custom tag with body<sd:for var=”5”>------- -------- I am srinivas---------- </sd for>

fortest.jsp

<%@ taglib uri="/WEB-INF/for.tld"

for.tld<taglib><jspversion>1.1</jspversion><tlibversion>1.0</tlibversion>

Note1 :------- when mandatory attribute are not used in the tag then following error message will be displayed Message1:------according to the TLD attribute value is mandatory for tag set.Note 2:-------- when you are using unspecified attributes in the tag then following error message will be display Message2:-------attribute scope 1 invalid for tag are according to the TLD.

photo

Page 24: jsp Basics

prefix="sd"%><h1> <sd:for var="5"> i am jlc student </sd:for> <sd:for var="3"> i don't know any thing in java </sd:for>

<uri>/WEB-INF/for.tld</uri><tag><name>for</name><tagclass>com.jlc.ForTag</tagclass><bodycontent>jsp</bodycontent><attribute><name>var</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute</tag></taglib>

package com.jlc;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;import javax.servlet.jsp.tagext.*;public class ForTag extends TagSupport{String var;int count;int n;public void setVar(String var){this.var=var;System.out.println("1");}public int doStartTag(){count=1;n=Integer.parseInt(var);System.out.println("doStartTag()");return EVAL_BODY_INCLUDE;}

public int doAfterBody(){System.out.println("doAfterBody()");if(count<n){count++;System.out.println("2");return EVAL_BODY_AGAIN;}else{return SKIP_BODY;}}public int doEndTag(){System.out.println("doEndTag()");return EVAL_PAGE;}}

<%@ page isELIgnored="false"%><%@ taglib uri="/WEB-INF/tlds/sdsoft.tld" prefix="sd"%><h1> student info</h1><sd:student>

<%@ page import="com.javasree.*" %><%Student stu=new Student();stu.setSname("vas");stu.setEmail("[email protected]");stu.setPhone("8888");

forTag.java

forTag.java

fortest.jsp

for.tld

NESTED TAG DEVLOPMENT

Page 25: jsp Basics

<sd:sname value ="sri"/><sd:email value ="[email protected]"/><sd:phone value ="999"/></sd:student><sd:student><sd:sname value ="${STU.sname}"/><sd:email value ="${STU.email}"/><sd:phone value ="${STU.phone}"/></sd:student>

session.setAttribute("STU",stu);%><h1> ok done

<taglib><tlibversion>1.0</tlibversion><jspversion>1.1</jspversion><uri>/WEB-INF/tlds/sdsoft.tld</uri><tag><name>student</name><tagclass>com.javasree.StudentTagHandler</tagclass><bodycontent>jsp</bodycontent></tag><tag><name>sname</name><tagclass>com.javasree.SnameTagHandler</tagclass><bodycontent>empty</bodycontent><attribute><name>value</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute></tag><tag>

<name>email</name><tagclass>com.javasree.EmailTagHandler</tagclass><bodycontent>empty</bodycontent><attribute><name>value</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute></tag><tag><name>phone</name><tagclass>com.javasree.PhoneTagHandler</tagclass><bodycontent>empty</bodycontent><attribute><name>value</name><required>true</required><rtexprvalue>true</rtexprvalue></attribute></tag></taglib>

package com.javasree;import javax.servlet.jsp.tagext.*;import javax.servlet.jsp.*;public class EmailTagHandler extends TagSupport{private String value=null;public void setValue(String value){ this.value=value; }public int doEndTag() throws JspException{try{

StudentTagHandler sth=(StudentTagHandler)getParent();sth.addValue(value);}catch(Exception e){System.out.println(e);}return EVAL_PAGE;}}

show.jsptest.jsp

sdsoft.tldsdsoft.tld

EmailTagHandler.java

Page 26: jsp Basics

package com.javasree;import javax.servlet.jsp.tagext.*;import javax.servlet.jsp.*;public class PhoneTagHandler extends TagSupport{private String value=null;public void setValue(String value){this.value=value;}public int doEndTag() throws JspException{try{

StudentTagHandler sth=(StudentTagHandler)getParent();sth.addValue(value);}catch(Exception e){System.out.println(e);}return EVAL_PAGE;}}

package com.javasree;import javax.servlet.jsp.tagext.*;import javax.servlet.jsp.*;public class SnameTagHandler extends TagSupport{private String value=null;public void setValue(String value){this.value=value;}public int doEndTag() throws JspException{try{

StudentTagHandler sth=(StudentTagHandler)getParent();sth.addValue(value);}catch(Exception e){System.out.println(e);}return EVAL_PAGE;}}

package com.javasree;import javax.servlet.jsp.tagext.*;import javax.servlet.jsp.*;import java.util.*;public class StudentTagHandler extends TagSupport{ArrayList al=null;public void addValue(String value){al.add(value);

public int doEndTag()throws JspException{try{JspWriter out=pageContext.getOut();String msg[]={"Student Name","Email","Phone"};out.println("<table bgcolor=cyan>");for(int i=0;i<al.size();i++){out.println("<tr>");out.println("<td>"+msg[i]+"</td>");

PhoneTagHandler.java

SnameTagHandler.java

StudentTagHandler.java

PhoneTagHandler.java

Page 27: jsp Basics

}public int doStartTag()throws JspException{try{al=new ArrayList();}catch(Exception e){System.out.println(e);}return EVAL_BODY_INCLUDE;}

out.println("<td>"+al.get(i)+"</td>");out.println("</tr>");}out.println("</table>");}catch(Exception e){System.out.println(e);}return EVAL_PAGE;}}

package com.javasree;public class Student{private String phone;private String sname;private String email;public void setPhone(String phone){this.phone=phone;}public void setSname(String sname){this.sname=sname;}

public void setEmail(String email){this.email=email;}public String getPhone(){return phone;}public String getSname(){return sname;}public String getEmail(){return email;}}

Jsp writer and print writer

We can find three types of scope in servlet: ------- Request scope Session scope Context scope

Context is the biggest scope Context object will be accessed by all the users in all the request. Session scope is the 2nd highest. Session unique for one user

Servlet scope

StudentTagHandler.java

Student.java

Student.java

PHOTO

Page 28: jsp Basics

Context unique for one application. Data inside the session scope can be accessed by a particular user in all the request. Data inside the request object can be accessed by a single user within the request

before sending the response.

In the jsp you can find four scopes Page scope Request scope Session scope Application scope

Include directive V/S include action

Include directive Attribute for the include directive is file When include the page using include

directive contents of that page will be included at translation time (the time at which JSP is converted into servlet).

Because of including contents it is not good in performance.

When you are using include directive you can’t pass any data to included page.

Include action Attribute for the Include action is a page. When include the page using Include

action response of the page will be included at run time.

This is good in performance because they included page will be evaluated only once and its response will be included several times.

NOTE :----- Include action is similar to include method in request dispatcher interface

When you including a page using include action you can send the data to included page as a parameter using Jsp:param action

Hello.jsp<h1>I am hello.jspx.jsp<%@ include file=”hello.jsp”%><jsp: include page=”hello.jsp”/>X_jsp.java file containg the following code for the above two different includes Out.write(<h1> I am hello.jsp”);JSPRuntimeLibrary.include(req,res , “hello.jsp”,out,false);

JSP scope

Page 29: jsp Basics

Object pageContext application session * request response out page config exception *

API javax.Servlet.jsp.pageContent javax.Servlet.servletContent javax.Servlet.http.httpSession javax.Servlet.http.HttpServletRequest javax.Servlet.http.HttpServletResponse javax.Servlet.jsp.jspWriter java.lang.Object javax.Servlet.servletConfig java.lang.Trowable

List of the implicit object with API

* We can enable or disable it.

Page 30: jsp Basics

<%@ page isELIgnored="false" import=java.util.*,com.jlc.*" %><%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="sd"%><%Student s1=new Student();

s1.setSid("99");s1.setSname("sri");s1.setEmail("[email protected]");s1.setPhone("9999");

Student s2=new Student();s2.setSid("88");s2.setSname("vas");s2.setEmail("[email protected]");s2.setPhone("8888");

ArrayList al=new ArrayList();al.add(s1);al.add(s2);

session.setAttribute("AL",al);HashMap hm1=new HashMap();

hm1.put("a","aaaa");hm1.put("b","bbbb");hm1.put("c","cccc");

HashMap hm2=new HashMap();hm2.put("x","xxxx");hm2.put("y","yyyy");hm2.put("z","zzzz");

ArrayList al1=new ArrayList();al1.add(hm1);al1.add(hm2);

session.setAttribute("AL1",al1);%><h1>Student info<br><sd:forEach var="stu" items="${AL}">

Student ID:{stu.sid}<br>Sname:${stu.sname}<br>Email:${stu.email}<br>Phone:${stu.phone}<br>

</sd:forEach><h1>from list of maps<br>

<sd:forEach var="map" items="${AL1}"><sd:forEach var="x" items="${map}">

${x}<br>${map["${x}"]}</sd:forEach></sd:forEach>

JSP BY JLCwww.jlcindia.com

logon please

sadeshkumar.yadav@g

mail.com


Top Related