Вы находитесь на странице: 1из 30

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)

Information About JSP by JLC www.jlcindia.com


mrajmit81@gmail.com

Scripting Elements
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.

Expression

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


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

servlet .

Declaration
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 Package org.apache.jsp; Import javax.servlet.*; Import javax.servlet.http.*; <html> Import javax.servlet.jsp.*; Hello.jsp <body> Public final class Hello-Jsp extends <h1>I am the Scriplets HttpJspBase <% int a=10; { out.println (Hello ------); Int x=99;

out.println (a); 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); } %>

JSP By Mukesh

Void 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); } }

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

Language

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

Scriplets. 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.

Extends
When you developing servlets we are taking HttpServlet as super class as

Class HelloServlet extend HttpServlet { --------------------- ---------} When container is generating the servlet container take HttpJSPBase as supper class Class 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.
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 section Example :---------<%! Public void JSPInit() { System.out.println(JSPInit()); } Public void JSPDestroy() { Can I override _JSPService() method inside declaration section? System.out.println(JSPDestroy()); 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 .

JSPInit() & JSPDestroy()

Import

Import attribute is used to specify the package which you want to import for the translated servlet class. you can specify the multiple package with the comma ,separation. <%@ page import=java.util.*,java.sql.*,javax.sql.*%>

Session attribute
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.

IsThreadSafe
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%>

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

or

IsErrorPage
<%@page errorPage=err or.jsp%>

<%@page errorPage=err or.jsp%> <%@page isErrorPage=true %>

When you are writing the java code inside the Jsps. you may get exception inside that to handle the exception you need to write try, catch blocks many times in all the Jsps .to avoid the try ,catch block and to centralize the exception handling use errorPage or IsErrorPage attribute inside the JSPs 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); %>

Include directive
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%>

Taglib directive
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 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 x.jsp
<jsp:include page=header.jsp> <jsp:param name=cname value=JLC/> </jsp:include> Header.jsp

For forward x.Jsp

<%cn=r.getParameter(cname); Out.println(cn)%> <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 Use Bean tag is used the java beans in JSP. value=some to the property of the java bean. setProperty is used to assign the value vbalue/> <jsp:getProperty property from property=some getPropery is used to get the value of the name=some objthe java Bean. property/>

Student.java package com.jlc; public class Student { private String sid; private String sname; private String email;

x.jsp
Student.java
<%@ page import="com.jlc.*"%>

private String phone; public void setSid(String sid) { 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() This is 1st { JSP return sid; program } public String getSname() JLC { return sname; RAMANSHYAM } public String getEmail() 01-jun-2008 { return email; } public String getPhone() { return phone; } } X1.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"/>

<h1>this jsp is adding Student object to session<br> open y.jsp and check the data..... <% Student stu=new Student(); stu.setSid("99"); stu.setSname("sri"); stu.setEmail("sri@sd.com"); stu.setPhone("9999"); session.setAttribute("STU",stu); %>

y.jsp
<%@ 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()%>

y1.Jsp <%@ 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"/>

<jsp:setProperty name="stu1" property="email" value="srinivas"/> 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 Hello Name Sri o/p of x.jsp hello,sri welcome to JLC your email is sri@sd.com hello,vas welcome to jlc your 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> //prefix // tag name // attribute name // attribute value

Custom tag development

<required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>email</name> <required>false</required> </attribute></tag></taglib> HelloTagHandler.java package com.jlc; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class HelloTagHandler extends TagSupport { HelloTagHandler.java 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); } Tracing
First it will take the prefix(minatory ) and compare this prefix with prefix written in

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; } }

<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. name should be same as x.jsp file if we wouldnt (as in x.jsp) that attribute name=name is mandatory in our custom tag then in jlc.tld write like <name>name</name>

Then it checks the tag name which should be same as x.jsp file and also attribute

<required>true</required> If any attribute name is not mandatory like email in x.jsp then write as <name>email</name> <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: -------------

Enter sid ----Files required: -------- Search.jsp Results.jsp Jlc.tld Web.xml showStudenttag.java web.xml search.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>

Searching

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

results.jsp <%@ taglib uri="/WEB-INF/jlc.tld" prefix="sd"%> <html> <body> <h1> searchresult</h1> <% String sid=request.getParameter("sid"); %> <sd:showStudent sid="<%=sid%>"/> </body></html> 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) { ShowStudentTag.java this.sid=sid;

<?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/webjsptaglibrary_1_1.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> Jlc.tld <uri>/WEB-INF/jlc.tld</uri> <tag>

<name>showStudent</name> <tagclass>com.jlc.ShowStudentTag</tagclass> <bodycontent>empty</bodycontent> <attribute> <name>sid</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute></tag></taglib>


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; } }

} public String getSid() { return sid; } public int doEndTag() throws JspException { try{ //call model String sname="srinivas"; String email="sri@sd.com"; 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

JSTL

JSP Standard Tag Library

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 After copy the other side to lib restart the server <sd:otherwise> <sd:forEach> <sd:import> <sd:catch> <sd:param>

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

<%@ page isELIgnored="false"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="sd"%> <sd:set var="email" scope="session" value="sri@sd.com"/> <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> </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>

EL
Syntax for EL: --------

(Expression Language )

${object name: object name} Any valid EL implicit object name Any parameter or header or cookie or attribute

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 attributes Out name Set more value scope Remove name scope If check(some condition) y.jsp with EL
Name is ${param.sn} Email is ${param.em} Phone is ${param.ph}

Question

Files required :--------------- jlc.tld JspUtil.java OutTag.java 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> SN <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <uri>/WEB-INF/jlc.tld</uri> Email <tag> <name>set</name> Phone <tagclass>com.jlc.SetTag</tagclass> <bodycontent>empty</bodycontent> Submit <attribute> <name>name</name> <required>true</required> <rtexprvalue>true</rtexprvalue> y.jsp with scriptlet </attribute> <% <attribute> String sn=request.getParameter(SN) <name>value</name> String em= request.getParameter(em) <required>true</required> String ph= request.getParameter(ph) <rtexprvalue>true</rtexprvalue> out.println(Name is+SN); out.println(Email is+em); </attribute> out.println(Phone is+ph); <attribute> %> <name>scope</name> </attribute> </tag> Continue <tag> <tag> <name>remove</name> <name>out</name> <tagclass>com.jlc.RemoveTag</tagclass> <tagclass>com.jlc.OutTag</tagclass> <bodycontent>empty</bodycontent> <bodycontent>empty</bodycontent> <attribute> <attribute> <name>name</name> <name>name</name> <required>true</required> <required>true</required> <rtexprvalue>true</rtexprvalue> <rtexprvalue>true</rtexprvalue> </attribute> </attribute>

<attribute> <name>scope</name> </attribute> </tag> continue

<attribute> <name>scope</name> </attribute> </tag></taglib>

OutTag.java package com.jlc; Files required :------------import javax.servlet.*; jlc.tld import javax.servlet.http.*; JspUtil.java import javax.servlet.jsp.*; OutTag.java import javax.servlet.jsp.tagext.*; RemoveTag.java public class OutTag extends TagSupport SetTag.java { test.jsp String name=null; web.xml 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(); } else

if(scope.equals("session")) { val=pageContext.getAttribute(name,pageContext.SESSION_SCOPE).toString(); } else { val=pageContext.getAttribute(name,pageContext.APPLICATION_SCOPE).toString(); } } else { val=pageContext.getAttribute(name,pageContext.PAGE_SCOPE).toString(); Information About } JSP by JLC JspWriter out=pageContext.getOut(); out.write(val); www.jlcindia.com }catch(Exception e) sadeshkumr.yadav@gmail.com { 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() {

Files required :------------ jlc.tld JspUtil.java OutTag.java RemoveTag.java SetTag.java test.jsp web.xml

Information About JSP by JLC www.jlcindia.com


sadeshkumar.yadav@gmail.com

return scope; } public void setScope(String scope) { this.scope=scope; } 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); } else if(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.java package com.jlc; import javax.servlet.*; import javax.servlet.http.*;

import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; Files required :------------public class SetTag extends TagSupport { jlc.tld String name=null; JspUtil.java String value=null; OutTag.java String scope=null; RemoveTag.java public String getName() SetTag.java test.jsp { web.xml 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; } sadeshkumar.yadav@gmail.com public int doEndTag() throws JspException { try{ if(JspUtil.isEmpty(scope)) { pageContext.setAttribute(name,value,pageContext.PAGE_SCOPE); Information About } else JSP, ANT &Log4J by { JLC if(scope.equals("page")) { www.jlcindia.com pageContext.setAttribute(name,value,pageContext.PAGE_SCOPE); rajivsh101@gmail.com } else if(scope.equals("request"))

Information About JSP by JLC www.jlcindia.com

{ pageContext.setAttribute(name,value,pageContext.REQUEST_SCOPE); } else if(scope.equals("session")) { 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"%> package com.jlc; <sd:set name="sid" value="99" scope="session"/> public class JspUtil <sd:set name="sname" value="sri"/> { <br>Sid:<sd:out name="sid" scope="session"/> public static boolean isEmpty(String <br>Sname:<sd:out name="sname" scope="request"/> str) <sd:remove name="sname"/> { <sd:remove name="sid"/> if(str==null||str.length()==0) <br>Sid:<sd:out name="sid" scope="session"/> { <br>Sname:<sd:out name="sname"/> return true; } return false; } }

Method of JSP
Implement the following custom tags Set tag: ------Attribute:-- name, value, scope Note :---- 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 , scope Note :------- name is mandatory and scope is optional, when scope is verify in all the scope starting from page and display the 1st occurrence only.

There are ten EL implement object: ------------ PageContext ParentValue Header 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 JSPs. <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. JSTLs import tag allows to include the jsp from the same application and also from different application.
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

Interface iteration Tag extends Tag { Int EVAL-BODY_AGAIN; Public abstract int doAfterBody();} i

Tag
i

Iteraton Tag Body tag


c

TagSupport
c

TagSupport

TagSupport

TagHandler class life cycle method or custom tag life cycle methods
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_PAGE int EVAL-PAGE int EVAL-BODY-TAG int EVAL-BODY BUFFERED

Flow of custom tag execution

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. 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.
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.

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

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

fortest.jsp <%@ taglib uri="/WEB-INF/for.tld" 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>

for.tld <taglib> <jspversion>1.1</jspversion> <tlibversion>1.0</tlibversion> <uri>/WEB-INF/for.tld</uri> <tag> <name>for</name> <tagclass>com.jlc.ForTag</tagclass> <bodycontent>jsp</bodycontent> <attribute> for.tld <name>var</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute</tag></taglib> public int doAfterBody() { System.out.println("doAfterBody()"); if(count<n) { count++; System.out.println("2"); return EVAL_BODY_AGAIN; } else forTag.java { return SKIP_BODY; } } public int doEndTag() { System.out.println("doEndTag()"); return EVAL_PAGE; } }

fortest.jsp
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) { forTag.java this.var=var; System.out.println("1"); } public int doStartTag() { count=1; n=Integer.parseInt(var); System.out.println("doStartTag()"); return EVAL_BODY_INCLUDE; }

NESTED

TAG

DEVLOPMENT

<%@ page isELIgnored="false"%> <%@ taglib uri="/WEB-INF/tlds/sdsoft.tld" prefix="sd"%> <h1> student info</h1> <sd:student> <sd:sname value ="sri"/> <sd:email value ="sri@sd.com"/> show.jsp <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>

<%@ page import="com.javasree.*" %> <% Student stu=new Student(); stu.setSname("vas"); stu.setEmail("vas@sd.com"); stu.setPhone("8888"); session.setAttribute("STU",stu); %> <h1> ok done

test.jsp

<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> sdsoft.tld <tag> package com.javasree; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; public class EmailTagHandler extends TagSupport { private String value=null;

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

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

public void setValue(String value) { this.value=value; } public int doEndTag() throws JspException { try{

return EVAL_PAGE; } } EmailTagHandler.java

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 { PhoneTagHandler.java try{ 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{ package com.javasree; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; import java.util.*;

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

PhoneTagHandler.java

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

SnameTagHandler.java

public int doEndTag()throws JspException { try{ JspWriter out=pageContext.getOut();

public class StudentTagHandler extends TagSupport { ArrayList al=null; public void addValue(String value) { StudentTagHandler.java al.add(value); } public int doStartTag()throws JspException { try{ al=new ArrayList(); }catch(Exception e) { System.out.println(e); } return EVAL_BODY_INCLUDE; }

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>"); out.println("<td>"+al.get(i)+"</td>"); out.println("</tr>"); } out.println("</table>"); }catch(Exception e) { System.out.println(e); } return EVAL_PAGE; } StudentTagHandler.java }

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; }

Student.java

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

Jsp writer and print writer

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

PHOTO

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 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.

JSP scope
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. 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

When you are using include directive

you cant pass any data to included page.

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.jsp x.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);

List of the implicit object with API

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

We can enable or disable it.

JSP BY JLC www.jlcindia.com <%@ page isELIgnored="false" import=java.util.*,com.jlc.*" %> logon please

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="sd"%> <% sadeshkumar.yadav@gmail.com Student s1=new Student(); s1.setSid("99"); s1.setSname("sri"); s1.setEmail("s@s.com"); s1.setPhone("9999"); Student s2=new Student(); s2.setSid("88"); s2.setSname("vas"); s2.setEmail("v@s.com"); 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>

Вам также может понравиться