SlideShare ist ein Scribd-Unternehmen logo
1 von 27
Tomcat 7

Servlet 3.0
-------------
      servelet anno

        Synch and Aych processing*


JEE 5 or JEE 6
------------

both are same tech...

MVC

View:jsp

Controller: servlet/ filter


JSP
-----


if both servelt and jsp are same the why two?
-------------------------------------------

CGI and Perl

Servlet


ASP


JSP= Java Server Pages
--------
      to simplify the web app development




ASP.net
------


Struts
-------

Velocity
--------




jsp is same as servlet
--------------------------

jsp should be convered in servlet.
------------------------------------

Servlet container
JSP container




JSP is slow then servlet first time only
----------------------------------------
      depends on container u are using*

after ward speed of jsp and servlet are same.



What ever we can do in servlet we can do in jsp
----------------------------------------------


Servlet and jsp
==============




how to learn jsp in 1 hr
-------------------------




JSP
===========

Nuts and bolts of JSP
--------------------

diective
-----------
      decide behaviour of whole page

     <%@ ............ %>


scriptlet
------------

     <%          %>
     pure java code
no html    and jsp code

expresssion
------------

      <%= i    %>


      out.prinln(i);


      expression is an replacement (Shortcut of out.println() )




decleration
------------

      <%!           %>




<%! int i=0;%>
<% i++;%>
<%=i%>




to compare jsp with sevlet
----------------------------------

hit counter programs
--------------------

<%!
      int i=0;

      String fun()
      {
ruturn "hi";
       }
%>



<%


       out.println("i:"+i);
       out.print(fun());
%>




<%=i++%>

is equivalent to

<%

       out.print(i++);
%>




JSP key topics
=======================
Java bean in jsp

EL

JSTL

JSP std tag liberary

Custome tag



Should be used in place of scriptlet
                     ---------




class MyServlet extends HttpServlet
{
      int i=0;

       public void fun()
       {
out.print("HI");
     }

     public void doGet(...... req,......res)thr............
     {
           PrintWriter out=res.get........();


              out.println("i:"+i);

              out.print("<h1>india is shining?</h1>");
              out.print("hi");

              fun();
     }
}




JSP directive
=============

<%@ .... %>

     •page
              defines page-specific properties such as character encoding,
              the content type for this pages response and whether this

              page should have the implicit session object.


              <%@ page import="foo.*" session="false" %>

            <%@ page language=•java• import=•java.util.Date(),
java.util.Dateformate()•
      iserrorpage=•false•%>


              A page directive can use up to thirteen different attributes
                                --------------------


     •include
            Defines text and code that gets added
           into the current page at translation time


              <%@ include file="hi.html" %>

     •taglib
           Defines tag libraries available to the JSP
<%@ taglib tagdir="/WEB-INF/tags/cool" prefix="cool" %>




what is the syn of include directive
--------------------------------

a.jsp
--------------------

<h1>file 1</h2>
<%@ include file="b.jsp" %>


b.jsp
-----------

<h1>file 2</h2>
<h1>india is shining!</h1>
<%=new Date()%>


in theory
---------
      we should not use include directive if content of b.jsp

     is changing with time.




Scriptlet
=========
                   <%   %>




     pure java code
     Nothing else only pure java
<% out.println(Counter.getCount()); %>




Expression
=========
                     <%=   %>

                     <%= Counter.getCount() %>

Instance Declaration
====================
                  <%! %>




JSP Comments
===========

       HTML Comment        <!-- HTML Comment -->

       JSP Comment         <%-- JSP Comment --%>




Understnading
================

       <html>
       <body>
             <%! int count=0; %>

             The page count is now:

              <= ++count %>
       </body>
       </html>




page
       for only that page

request    doGet(..........request, ........res)


session===>HttpSession s=req.getSession()

application==>getServletContext()
Implicit Object
====================

JspWriter        out

HttpServletRequest       request



                 request.setAttribute("key","foo");
                 String temp=request.getAttribute("key");


HttpServletResponse      response

HttpSession      session

                 session.setAttribute("key","foo");
                 String temp=session.getAttribute("key");


ServletContext           application



                 application.setAttribute("key","foo");
                 String temp=application.getAttribute("key");


ServletConfig            config

Throwable        exception

PageContext      pageContext (not in servlet)


                 is an handly way to access any type of scoped variable?

Object                   page   (not in servlet)




Standard Actions
----------------------
Tags that affect runtime behavior of JSP and response send back to client




     Std action types:
     -----------------
     <jsp:useBean>
     <jsp:setProperty>
     <jsp:getProperty>
RequestDispacher rd=request.getRequestDispacher("show.jsp");
                 rd.forward(req,res);

     <jsp:include>
     <jsp:forward>

     <jsp:plugin>
     <jsp:param>

           applet




API for the Generated Servlet
==============================


     jspInit()
     --------
                 This method is called from the
                  init() method and it can be overridden

     jspDestroy()
     ----------
                 This method is called from the servlets destroy()
                 method and it too can be overridden


     _jspService()

                 This method is called from the servlets service()
                 method which means its runs
                 in a separate thread for each request,
                  the container passes the request and response
                 object to this method.

                 You cannot override this method.




Initializing your JSP
-------------------------


put this in web.xml
---------------------

<web-app ...>

  <servlet>
     <servlet-name>foo</servlet-name>
     <jsp-file>/index.jsp</jsp-file>

     <init-param>
     <param-name>email</param-name>
     <param-value>rgupta.mtech@gmail.com</param-value>
   </init-param>

 </servlet>
<servlet-mapping>
        <servlet-name>foo</servlet-name>
        <url-pattern>/index.jsp</url-pattern>
    </servlet-mapping>

</web-app>



now getting them in init method
===============================

<%!
  public void jspInit()
  {

        ServletConfig sConfig = getServletConfig();
        String emailAddr = sConfig.getInitParameter("email");
        ServletContext ctx = getServletContext();
        ctx.setAttribute("mail", emailAddr);
    }

%>




class Fun
{
      Fun(){}

}




now get attributes in service method
===============================

<%= "Mail Attribute is: " + application.getAttribute("mail") %>
<%= "Mail Attribute is: " + pageContext.findAttribute("mail") %>



<%
     ServletConfig sConfig = getServletConfig();
     String emailAddr = sConfig.getInitParameter("email");
     out.println("<br><br>Another way to get web.xml attributes: " + emailAddr );
%>




<%
   out.println("<br><br>Yet another way to get web.xml attributes: " +
getServletConfig().getInitParameter("email") );
%>




Setting scoped attributes in JSP
================================

Application
-----------

       in servlet
       ----------
             getServletContext().setAttribute("foo",barObj);

       in jsp
       --------
             application.setAttribute("foo",barObj);



Request
--------

       in servlet
       ----------
             request.setAttribute("foo",barObj);

       in jsp
       --------
             request.setAttribute("foo",barObj);



Session
--------

       in servlet
       ----------
             request.getSession().setAttribute("foo",barObj);

       in jsp
       --------
             session.setAttribute("foo",barObj);
Page
-------

     in servlet
     ----------
           do not apply

     in jsp
     --------
           pageContext.setAttribute("foo",barObj);



Note
============


     Using the pageContext to get a session-scoped attribute
     ------------------------------------------------------------

     <%= pageContext.getAttribute("foo", PageContext.SESSION_SCOPE ) %>

     Using the pageContext to get an application-scoped attribute
     ----------------------------------------------------------------
     <%= pageContext.getAttribute("mail", PageContext.APPLICATION_SCOPE) %>


     Using the pageContext to find an attribute
      when you don't know the scope
     -----------------------------
     <%= pageContext.findAttribute("mail") %>




ExceptionHandling in JSP
---------------------------


Exceptionhandling.jsp
--------------------------

<%@ page errorPage="errorpage.jsp" isErrorPage="false"%>
<%

Dog d=null;
String s=null;

....
....
d.toString();

%>


errorpage.jsp
----------------------

<%@ page isErrorPage="true" %>

This is the Error page.The following error occurs:- <br>
<%= exception.toString() %>
Reuqst dispaching vs redirect
------------------------------------




login.html
==========

<form action   ="myLogin.jsp".
      <input   type="text" name="name"/>
      <input   type="password" name="pass"/>
      <input   type="submit"/>
</form>


login app
-------------




passing parameter with dispaching
-----------------------------
    <jsp:include page="/requestParams2.jsp" >
            <jsp:param name="sessionID" value="<%= session.getId() %>" />
    </jsp:include>


getting in another servlet and jsp
---------------------------------------

<%@ page import="java.util.*" %>
<%
Enumeration parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements())
      {
            String name = (String)parameterNames.nextElement();
            out.println(name);
            out.println(request.getParameter(name) );
      }
%>
Sepration of concern
-------------------
no business logic should be done in jsp at any cost




     <jsp:useBean>

     <jsp:setProperty>

     <jsp:getProperty>




Basic of jsp model
-------------------

script file converted into eq servlet.

no diff between servlet and jsp

nut and bolts of jsp
-----------------

     Directive
     ---------
           include

           taglib*
page
                  13 attributes not all imp


     Scriptlet
     -------
     pure java code
     must be avoided diff to avoide



     expression
     ---------
     aka of short cut for out.print()


     decleation
     ----------
     <%!

     %>

           whatever u want to put in insta/static




     comments
     -------
           jsp comm
           html comm:show in view source


     include directive and include action
     ----------------------------------------
     if content is changing dynamicall always go for action



     scope
     ======
           page
           request
           session
           application

           pageContext



     Std action
     ---------
     <jsp:useBean........./>

     <jsp:setProperty ............/>
     <jsp:getProperty ............../>




How java bean internally use reflection and serl...?
------------------------------------------------
      what is reflection *
============================================================================
Day-2
============================================================================


EL:Expression Language


More on java beans
-------------------

<form action ="LoginServlet" method="get">
      ID:<input type="text" name="id"/></br>
      Name:<input type="text" name="name"/></br>
      Pass:<input type="password" name="pass"/></br>
      <input type="submit"/>
</form>



automatic type conversion

processing of bean

Expression Language Introduction ( E L )
-----------------------------------


     Putting java code in jsp is bad habbit


     then what to do?
     ---------------

     Use EL
           JSP 2.0 spec. EL offers a simpler way to
           invoke Java code but he code itself belongs somewhere else



     Although EL looks like Java it behaves differently,
     so do not try and map the same Java with EL.


     EL are always within curly braces and prefixed with the dollar sign.


      The first named variable in the expression is either an implicit object or
an attribute


     how EL make my life easy....
     -------------------------------

     EL example
     ------------
     old way don't do now
     --------------------
Please contact: <%= application.getAttribute("mail") %>


EL way
------

please contact: ${applicationScope.mail}




stop JSP from using scripting elements
--------------------------------------

     <web-app ...>
     ...
       <jsp-config>

           <jsp-property-group>

           <url-pattern>*.jsp</url-pattern>

           <scripting-invalid>true</scripting-invalid>

           </jsp-property-group>

       </jsp-config>
     ...
     </web-app>




stop using EL
-------------
<%@ page isELIgnored="true" %>

Note: this takes priority over the DD tag above




Scriptless JSP
=============

EL provide better way to accept DTO send from controller to view

Some Ex:
======

Consiser Servlet (controller) code
-----------------------------------

     Person p = new Person();

     p.setName("Paul");

     request.setAttribute("person", p);

      RequestDispatcher view = request.getRequestDispatcher
("result.jsp");
view.forward(request, response);



JSP (view) code
-----------------
      Person is: <%= request.getAttribute("person") %>


     Does it work?




Correct way?
--------------
<% Person p = (Person) request.getAttribute("person");

Person is: <%= p.getName() %>




or

Person is: <%= ((Person) request.getAttribute("person")).getName() %>




Correct Way
----------

<jsp:useBean id="person" class="foo.Person" scope="request" />

Person is: <jsp:getProperty name="person" property="name" />


class Person
{
private String name;
           ....
           ...
           ...
     }




     public class Dog
     {
           private String dogName;
           .....
           .....
     }




     public class Person
     {
           private String personName;
           private Dog dog;

           .....
           .....
     }

Person has A dog
      ----




           Dog dog=new Dog();

           dog.setDogName("myDog");

           Person p=new Person();

           p.setPersonName("foo");

           p.setDog(dog);

           request.setAttribute("person", p);



--------------------------------------------------------------------------------
------

     Expression Language
     ====================

     More examples
     --------------



     consider controller code
     ----------------------
adding persons dog in request attributes in an servlet
     -----------------------------------------------------------

     foo.Person p = new foo.Person();

     p.setName("Paul");

     foo.Dog dog = new foo.Dog();

     dog.setName("Spike");

     p.setDog(dog);

     request.setAttribute("person", p);



     getting same in jsp
     ------------------------

     using tags

<%= ((Person) request.getAttribute("person")).getDog ().getName() %>




     using EL

                  Dog's name is: ${person.dog.name}




     Some more examples
     --------------------


     in servlet
     ---------

     String[] footballTeams = { "Liverpool", "Manchester Utd", "Arsenal",
     "Chelsea" }

     request.setAttribute("footballList", footballTeams);



     in jsp
     ---------
Favorite Team: ${footballList[0]}

Worst Team: ${footballList["1"]}


            Note ["one"] would not work but ["10"] would


<%-- using the arraylist toString()
---------------------------------

All the teams: ${footballList}




Another Example
--------------

servlet code
----------------


java.util.Map foodMap = new java.util.HashMap();

foodMap.put("Fruit", "Banana");
foodMap.put("TakeAway", "Indian");
foodMap.put("Drink", "Larger");
foodMap.put("Dessert", "IceCream");
foodMap.put("HotDrink", "Coffee");

String[] foodTypes = {"Fruit", "TakeAway", "Drink", "Dessert", "HotDrink"}

request.setAttribute("foodMap", foodMap);



JSP code
---------

Favorite Hot Drink is: ${foodMap.HotDrink}
Favorite Take-Away is: ${foodMap["TakeAway"]}

Favorite Dessert is: ${foodMap[foodTypes[3]]}




EL

JSTL

JSP std tag library
---------------------

       core

       formatting

       sql

       xml

       String functions


Custom tags
-----------
      user defind tags.

in case JSTL dont have tag to solve ur problem.

then go for custom tags

(Dont cook food urself if get cooked food)




Ex:
There may be cases when you want multiple values for one given
parameter name, which is when you use paramValues
============================================================

HTML Form
-----------

<html><body>

<form action="TestBean.jsp">
        name: <input type="text" name="name">
ID: <input type="text" name="empID">

     First food: <input type="text" name="food">
     Second food: <input type="text" name="food">

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

</body></html>



JSP Code
-----------

Request param name is: ${param.name} <br>

Request param empID is: ${param.empID} <br>

<%-- you will only get the first value -->

Request param food is: ${param.food} <br>

First food is: ${paramValues.food[0]} <br>

Second food is: ${paramValues.food[1]} <br>




Here are some other parameters you can obtain,
-----------------------------------------------------

host header
--------

Host is: <%= request.getHeader("host•) %>

Host is: ${header["host"]}
Host is: $header.host}


whether Request is post or get ?
---------------------------------
Method is: ${pageContext.request.method}
Cookie information
     -----------------
     Username is: ${cookie.userName.value}


     Context init parameter (need to configure in dd)
     -----------------------


     email is: <%= application.getInitParameter("mainEmail") %>

     email is: {$initParam.mainEmail}




     What has been covered till now
     --------------------------------

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

     declaration
     ---------
                 <%! int y = 3; %>
     EL Expression
     -------------
                 email: ${applicationScope.mail}

     scriptlet
     ---------
                   <% Float one = new Float(42.5); %>

     expression
     ---------
                   <%= pageContext.getAttribute(foo") %>

     action
     ---------
                   <jsp:include page="foo.html" />




JSTL
=======

The JSTL is hugh, version 1.2 has five libraries,
four with custom tags and one with a bunch of functions for String manipulation


        •JSTL Core - core

        •JSTL fmt - formatting

        •JSTL XML - xml

        •JSTL sql - sql

        •JSTL function - string manipulation



Hello world jstl
======================

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html><body>
  ...
  <c:forEach var="i" begin="1" end="10" >
    <c:out value="${i}" />
  </c:forEach>
  ...
</body></html>




Custom tags
====================




A Custom tag is a user defined JSP language element.


When a JSP page containing custom tag is translated into a Servlet,

the tag is converted to operations on an object called tag handler.
                                   --------------------




The Web container then invokes those operations when the JSP page•s servlet is
executed.



Note:

        1. Custom tags can access all the objects available in JSP pages.

        2. Custom tags can modify the response generated by the calling page.

        3.Custom tags can be nested.
Custom tag library consists of one or more Java classes

called Tag Handlers and an XML tag library descriptor file (tag library).
      ----------------        --------------------------



javax.servlet.jsp.tagext.
-----------------------------

A class which has to be a tag handler
needs to implement <<Tag>> or<<IterationTag >> or <<BodyTag>>

or

it can also extend TagSupport or BodyTagSupport class.




Let us create a custom tag which will does substring operation on given input.




If SKIP_BODY
-----------
       is returned by doStartTag() then if body is present then it is not
evaluated.


If EVAL_BODY_INCLUDE
-----------------
      is returned, the body is evaluated and "passed through" to the current
output.
Jsp Notes

Weitere ähnliche Inhalte

Was ist angesagt?

Servlet and jsp interview questions
Servlet and jsp interview questionsServlet and jsp interview questions
Servlet and jsp interview questionsSujata Regoti
 
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010Arun Gupta
 
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…D
 
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...D
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrideugenio pombi
 
Implicit objects advance Java
Implicit objects advance JavaImplicit objects advance Java
Implicit objects advance JavaDarshit Metaliya
 
Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Lar21
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server PageVipin Yadav
 
Spring Web Views
Spring Web ViewsSpring Web Views
Spring Web ViewsEmprovise
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXIMC Institute
 
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0Arun Gupta
 
Jsp elements
Jsp elementsJsp elements
Jsp elementsNuha Noor
 
Using the Features API
Using the Features APIUsing the Features API
Using the Features APIcgmonroe
 
RESTful API 제대로 만들기
RESTful API 제대로 만들기RESTful API 제대로 만들기
RESTful API 제대로 만들기Juwon Kim
 

Was ist angesagt? (20)

Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Jsp
JspJsp
Jsp
 
Implicit object.pptx
Implicit object.pptxImplicit object.pptx
Implicit object.pptx
 
Servlet and jsp interview questions
Servlet and jsp interview questionsServlet and jsp interview questions
Servlet and jsp interview questions
 
Django
DjangoDjango
Django
 
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
Hyperproductive JSF 2.0 @ JavaOne Brazil 2010
 
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…
Things Your Mother Didnt Tell You About Bundle Configurations - Symfony Live…
 
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
Things Your Mother Didn't Tell You About Bundle Configurations - Symfony Live...
 
Datagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and BackgridDatagrids with Symfony 2, Backbone and Backgrid
Datagrids with Symfony 2, Backbone and Backgrid
 
Implicit objects advance Java
Implicit objects advance JavaImplicit objects advance Java
Implicit objects advance Java
 
Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18
 
JavaServer Pages
JavaServer PagesJavaServer Pages
JavaServer Pages
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
 
Spring Web Views
Spring Web ViewsSpring Web Views
Spring Web Views
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
Spark IT 2011 - Simplified Web Development using Java Server Faces 2.0
 
Jsp elements
Jsp elementsJsp elements
Jsp elements
 
Jsp
JspJsp
Jsp
 
Using the Features API
Using the Features APIUsing the Features API
Using the Features API
 
RESTful API 제대로 만들기
RESTful API 제대로 만들기RESTful API 제대로 만들기
RESTful API 제대로 만들기
 

Andere mochten auch

Install linux suse(sless11)
Install linux suse(sless11)Install linux suse(sless11)
Install linux suse(sless11)Tola LENG
 
Configure Proxy and Firewall (Iptables)
Configure Proxy and Firewall (Iptables)Configure Proxy and Firewall (Iptables)
Configure Proxy and Firewall (Iptables)Tola LENG
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notesRajiv Gupta
 
DNS windows server(2008R2) & linux(SLES 11)
DNS windows server(2008R2) & linux(SLES 11)DNS windows server(2008R2) & linux(SLES 11)
DNS windows server(2008R2) & linux(SLES 11)Tola LENG
 
Configure proxy firewall on SuSE Linux Enterprise Server 11
Configure proxy firewall on SuSE Linux Enterprise Server 11Configure proxy firewall on SuSE Linux Enterprise Server 11
Configure proxy firewall on SuSE Linux Enterprise Server 11Tola LENG
 
Configure active directory &amp; trust domain
Configure active directory &amp; trust domainConfigure active directory &amp; trust domain
Configure active directory &amp; trust domainTola LENG
 
Configure Webserver & SSL secure & redirect in SuSE Linux Enterprise
Configure Webserver & SSL secure & redirect in SuSE Linux EnterpriseConfigure Webserver & SSL secure & redirect in SuSE Linux Enterprise
Configure Webserver & SSL secure & redirect in SuSE Linux EnterpriseTola LENG
 
Tola.leng sa nagios
Tola.leng sa nagiosTola.leng sa nagios
Tola.leng sa nagiosTola LENG
 
How to be a good presentor by tola
How to be a good presentor by tolaHow to be a good presentor by tola
How to be a good presentor by tolaTola LENG
 
Java Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jJava Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jRajiv Gupta
 
Basic security &amp; info
Basic security &amp; infoBasic security &amp; info
Basic security &amp; infoTola LENG
 
Ansible automation tool with modules
Ansible automation tool with modulesAnsible automation tool with modules
Ansible automation tool with modulesmohamedmoharam
 
File Share Server, FTP server on Linux SuSE and Windows
File Share Server, FTP server on Linux SuSE and WindowsFile Share Server, FTP server on Linux SuSE and Windows
File Share Server, FTP server on Linux SuSE and WindowsTola LENG
 
How to configure IPA-Server & Client-Centos 7
How to configure IPA-Server & Client-Centos 7How to configure IPA-Server & Client-Centos 7
How to configure IPA-Server & Client-Centos 7Tola LENG
 
Configure DHCP Server and DHCP-Relay
Configure DHCP Server and DHCP-RelayConfigure DHCP Server and DHCP-Relay
Configure DHCP Server and DHCP-RelayTola LENG
 
Lab work servlets and jsp
Lab work servlets and jspLab work servlets and jsp
Lab work servlets and jspRajiv Gupta
 

Andere mochten auch (20)

Install linux suse(sless11)
Install linux suse(sless11)Install linux suse(sless11)
Install linux suse(sless11)
 
Map.ppt
Map.pptMap.ppt
Map.ppt
 
Configure Proxy and Firewall (Iptables)
Configure Proxy and Firewall (Iptables)Configure Proxy and Firewall (Iptables)
Configure Proxy and Firewall (Iptables)
 
Advance C++notes
Advance C++notesAdvance C++notes
Advance C++notes
 
DNS windows server(2008R2) & linux(SLES 11)
DNS windows server(2008R2) & linux(SLES 11)DNS windows server(2008R2) & linux(SLES 11)
DNS windows server(2008R2) & linux(SLES 11)
 
Configure proxy firewall on SuSE Linux Enterprise Server 11
Configure proxy firewall on SuSE Linux Enterprise Server 11Configure proxy firewall on SuSE Linux Enterprise Server 11
Configure proxy firewall on SuSE Linux Enterprise Server 11
 
Network Diagram
Network DiagramNetwork Diagram
Network Diagram
 
Configure active directory &amp; trust domain
Configure active directory &amp; trust domainConfigure active directory &amp; trust domain
Configure active directory &amp; trust domain
 
Configure Webserver & SSL secure & redirect in SuSE Linux Enterprise
Configure Webserver & SSL secure & redirect in SuSE Linux EnterpriseConfigure Webserver & SSL secure & redirect in SuSE Linux Enterprise
Configure Webserver & SSL secure & redirect in SuSE Linux Enterprise
 
Tola.leng sa nagios
Tola.leng sa nagiosTola.leng sa nagios
Tola.leng sa nagios
 
How to be a good presentor by tola
How to be a good presentor by tolaHow to be a good presentor by tola
How to be a good presentor by tola
 
jsf2 Notes
jsf2 Notesjsf2 Notes
jsf2 Notes
 
Java Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4jJava Logging discussion Log4j,Slf4j
Java Logging discussion Log4j,Slf4j
 
Basic security &amp; info
Basic security &amp; infoBasic security &amp; info
Basic security &amp; info
 
Ansible automation tool with modules
Ansible automation tool with modulesAnsible automation tool with modules
Ansible automation tool with modules
 
Struts2 notes
Struts2 notesStruts2 notes
Struts2 notes
 
File Share Server, FTP server on Linux SuSE and Windows
File Share Server, FTP server on Linux SuSE and WindowsFile Share Server, FTP server on Linux SuSE and Windows
File Share Server, FTP server on Linux SuSE and Windows
 
How to configure IPA-Server & Client-Centos 7
How to configure IPA-Server & Client-Centos 7How to configure IPA-Server & Client-Centos 7
How to configure IPA-Server & Client-Centos 7
 
Configure DHCP Server and DHCP-Relay
Configure DHCP Server and DHCP-RelayConfigure DHCP Server and DHCP-Relay
Configure DHCP Server and DHCP-Relay
 
Lab work servlets and jsp
Lab work servlets and jspLab work servlets and jsp
Lab work servlets and jsp
 

Ähnlich wie Jsp Notes

Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSPGeethu Mohan
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauSpiffy
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortalJennifer Bourey
 
AnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkara JUG
 
Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Joao Lucas Santana
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESYoga Raja
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCpootsbook
 
KMUTNB - Internet Programming 5/7
KMUTNB - Internet Programming 5/7KMUTNB - Internet Programming 5/7
KMUTNB - Internet Programming 5/7phuphax
 
KMUTNB - Internet Programming 5/7
KMUTNB - Internet Programming 5/7KMUTNB - Internet Programming 5/7
KMUTNB - Internet Programming 5/7phuphax
 

Ähnlich wie Jsp Notes (20)

JSP
JSPJSP
JSP
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
ASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin LauASP.NET Overview - Alvin Lau
ASP.NET Overview - Alvin Lau
 
Jsp sasidhar
Jsp sasidharJsp sasidhar
Jsp sasidhar
 
Presentation
PresentationPresentation
Presentation
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortal
 
J2EE jsp_01
J2EE jsp_01J2EE jsp_01
J2EE jsp_01
 
Jsp1
Jsp1Jsp1
Jsp1
 
AnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFacesAnkaraJUG Kasım 2012 - PrimeFaces
AnkaraJUG Kasım 2012 - PrimeFaces
 
Jsp element
Jsp elementJsp element
Jsp element
 
Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)Desenvolvimento web com Ruby on Rails (parte 2)
Desenvolvimento web com Ruby on Rails (parte 2)
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
Jsp
JspJsp
Jsp
 
Backbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVCBackbone.js — Introduction to client-side JavaScript MVC
Backbone.js — Introduction to client-side JavaScript MVC
 
Java beans
Java beansJava beans
Java beans
 
Jsp
JspJsp
Jsp
 
KMUTNB - Internet Programming 5/7
KMUTNB - Internet Programming 5/7KMUTNB - Internet Programming 5/7
KMUTNB - Internet Programming 5/7
 
KMUTNB - Internet Programming 5/7
KMUTNB - Internet Programming 5/7KMUTNB - Internet Programming 5/7
KMUTNB - Internet Programming 5/7
 
Chap4 4 2
Chap4 4 2Chap4 4 2
Chap4 4 2
 

Mehr von Rajiv Gupta

Spring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepSpring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepRajiv Gupta
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with javaRajiv Gupta
 
1. java script language fundamentals
1. java script language fundamentals1. java script language fundamentals
1. java script language fundamentalsRajiv Gupta
 
Introduction to jsf2
Introduction to jsf2Introduction to jsf2
Introduction to jsf2Rajiv Gupta
 
Weblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencastWeblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencastRajiv Gupta
 
Spring aop with aspect j
Spring aop with aspect jSpring aop with aspect j
Spring aop with aspect jRajiv Gupta
 
Spring 3.0 dependancy injection
Spring 3.0 dependancy injectionSpring 3.0 dependancy injection
Spring 3.0 dependancy injectionRajiv Gupta
 
Java spring framework
Java spring frameworkJava spring framework
Java spring frameworkRajiv Gupta
 
Core java 5 days workshop stuff
Core java 5 days workshop stuffCore java 5 days workshop stuff
Core java 5 days workshop stuffRajiv Gupta
 

Mehr von Rajiv Gupta (13)

Spring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by stepSpring5 hibernate5 security5 lab step by step
Spring5 hibernate5 security5 lab step by step
 
GOF Design pattern with java
GOF Design pattern with javaGOF Design pattern with java
GOF Design pattern with java
 
1. java script language fundamentals
1. java script language fundamentals1. java script language fundamentals
1. java script language fundamentals
 
Introduction to jsf2
Introduction to jsf2Introduction to jsf2
Introduction to jsf2
 
Hibernate 3
Hibernate 3Hibernate 3
Hibernate 3
 
Weblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencastWeblogic 11g admin basic with screencast
Weblogic 11g admin basic with screencast
 
Struts2
Struts2Struts2
Struts2
 
Java 7
Java 7Java 7
Java 7
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
Spring aop with aspect j
Spring aop with aspect jSpring aop with aspect j
Spring aop with aspect j
 
Spring 3.0 dependancy injection
Spring 3.0 dependancy injectionSpring 3.0 dependancy injection
Spring 3.0 dependancy injection
 
Java spring framework
Java spring frameworkJava spring framework
Java spring framework
 
Core java 5 days workshop stuff
Core java 5 days workshop stuffCore java 5 days workshop stuff
Core java 5 days workshop stuff
 

Kürzlich hochgeladen

9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 

Kürzlich hochgeladen (20)

9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 

Jsp Notes

  • 1. Tomcat 7 Servlet 3.0 ------------- servelet anno Synch and Aych processing* JEE 5 or JEE 6 ------------ both are same tech... MVC View:jsp Controller: servlet/ filter JSP ----- if both servelt and jsp are same the why two? ------------------------------------------- CGI and Perl Servlet ASP JSP= Java Server Pages -------- to simplify the web app development ASP.net ------ Struts ------- Velocity -------- jsp is same as servlet -------------------------- jsp should be convered in servlet. ------------------------------------ Servlet container
  • 2. JSP container JSP is slow then servlet first time only ---------------------------------------- depends on container u are using* after ward speed of jsp and servlet are same. What ever we can do in servlet we can do in jsp ---------------------------------------------- Servlet and jsp ============== how to learn jsp in 1 hr ------------------------- JSP =========== Nuts and bolts of JSP -------------------- diective ----------- decide behaviour of whole page <%@ ............ %> scriptlet ------------ <% %> pure java code
  • 3. no html and jsp code expresssion ------------ <%= i %> out.prinln(i); expression is an replacement (Shortcut of out.println() ) decleration ------------ <%! %> <%! int i=0;%> <% i++;%> <%=i%> to compare jsp with sevlet ---------------------------------- hit counter programs -------------------- <%! int i=0; String fun() {
  • 4. ruturn "hi"; } %> <% out.println("i:"+i); out.print(fun()); %> <%=i++%> is equivalent to <% out.print(i++); %> JSP key topics ======================= Java bean in jsp EL JSTL JSP std tag liberary Custome tag Should be used in place of scriptlet --------- class MyServlet extends HttpServlet { int i=0; public void fun() {
  • 5. out.print("HI"); } public void doGet(...... req,......res)thr............ { PrintWriter out=res.get........(); out.println("i:"+i); out.print("<h1>india is shining?</h1>"); out.print("hi"); fun(); } } JSP directive ============= <%@ .... %> •page defines page-specific properties such as character encoding, the content type for this pages response and whether this page should have the implicit session object. <%@ page import="foo.*" session="false" %> <%@ page language=•java• import=•java.util.Date(), java.util.Dateformate()• iserrorpage=•false•%> A page directive can use up to thirteen different attributes -------------------- •include Defines text and code that gets added into the current page at translation time <%@ include file="hi.html" %> •taglib Defines tag libraries available to the JSP
  • 6. <%@ taglib tagdir="/WEB-INF/tags/cool" prefix="cool" %> what is the syn of include directive -------------------------------- a.jsp -------------------- <h1>file 1</h2> <%@ include file="b.jsp" %> b.jsp ----------- <h1>file 2</h2> <h1>india is shining!</h1> <%=new Date()%> in theory --------- we should not use include directive if content of b.jsp is changing with time. Scriptlet ========= <% %> pure java code Nothing else only pure java
  • 7. <% out.println(Counter.getCount()); %> Expression ========= <%= %> <%= Counter.getCount() %> Instance Declaration ==================== <%! %> JSP Comments =========== HTML Comment <!-- HTML Comment --> JSP Comment <%-- JSP Comment --%> Understnading ================ <html> <body> <%! int count=0; %> The page count is now: <= ++count %> </body> </html> page for only that page request doGet(..........request, ........res) session===>HttpSession s=req.getSession() application==>getServletContext()
  • 8. Implicit Object ==================== JspWriter out HttpServletRequest request request.setAttribute("key","foo"); String temp=request.getAttribute("key"); HttpServletResponse response HttpSession session session.setAttribute("key","foo"); String temp=session.getAttribute("key"); ServletContext application application.setAttribute("key","foo"); String temp=application.getAttribute("key"); ServletConfig config Throwable exception PageContext pageContext (not in servlet) is an handly way to access any type of scoped variable? Object page (not in servlet) Standard Actions ---------------------- Tags that affect runtime behavior of JSP and response send back to client Std action types: ----------------- <jsp:useBean> <jsp:setProperty> <jsp:getProperty>
  • 9. RequestDispacher rd=request.getRequestDispacher("show.jsp"); rd.forward(req,res); <jsp:include> <jsp:forward> <jsp:plugin> <jsp:param> applet API for the Generated Servlet ============================== jspInit() -------- This method is called from the init() method and it can be overridden jspDestroy() ---------- This method is called from the servlets destroy() method and it too can be overridden _jspService() This method is called from the servlets service() method which means its runs in a separate thread for each request, the container passes the request and response object to this method. You cannot override this method. Initializing your JSP ------------------------- put this in web.xml --------------------- <web-app ...> <servlet> <servlet-name>foo</servlet-name> <jsp-file>/index.jsp</jsp-file> <init-param> <param-name>email</param-name> <param-value>rgupta.mtech@gmail.com</param-value> </init-param> </servlet>
  • 10. <servlet-mapping> <servlet-name>foo</servlet-name> <url-pattern>/index.jsp</url-pattern> </servlet-mapping> </web-app> now getting them in init method =============================== <%! public void jspInit() { ServletConfig sConfig = getServletConfig(); String emailAddr = sConfig.getInitParameter("email"); ServletContext ctx = getServletContext(); ctx.setAttribute("mail", emailAddr); } %> class Fun { Fun(){} } now get attributes in service method =============================== <%= "Mail Attribute is: " + application.getAttribute("mail") %>
  • 11. <%= "Mail Attribute is: " + pageContext.findAttribute("mail") %> <% ServletConfig sConfig = getServletConfig(); String emailAddr = sConfig.getInitParameter("email"); out.println("<br><br>Another way to get web.xml attributes: " + emailAddr ); %> <% out.println("<br><br>Yet another way to get web.xml attributes: " + getServletConfig().getInitParameter("email") ); %> Setting scoped attributes in JSP ================================ Application ----------- in servlet ---------- getServletContext().setAttribute("foo",barObj); in jsp -------- application.setAttribute("foo",barObj); Request -------- in servlet ---------- request.setAttribute("foo",barObj); in jsp -------- request.setAttribute("foo",barObj); Session -------- in servlet ---------- request.getSession().setAttribute("foo",barObj); in jsp -------- session.setAttribute("foo",barObj);
  • 12. Page ------- in servlet ---------- do not apply in jsp -------- pageContext.setAttribute("foo",barObj); Note ============ Using the pageContext to get a session-scoped attribute ------------------------------------------------------------ <%= pageContext.getAttribute("foo", PageContext.SESSION_SCOPE ) %> Using the pageContext to get an application-scoped attribute ---------------------------------------------------------------- <%= pageContext.getAttribute("mail", PageContext.APPLICATION_SCOPE) %> Using the pageContext to find an attribute when you don't know the scope ----------------------------- <%= pageContext.findAttribute("mail") %> ExceptionHandling in JSP --------------------------- Exceptionhandling.jsp -------------------------- <%@ page errorPage="errorpage.jsp" isErrorPage="false"%> <% Dog d=null; String s=null; .... .... d.toString(); %> errorpage.jsp ---------------------- <%@ page isErrorPage="true" %> This is the Error page.The following error occurs:- <br> <%= exception.toString() %>
  • 13. Reuqst dispaching vs redirect ------------------------------------ login.html ========== <form action ="myLogin.jsp". <input type="text" name="name"/> <input type="password" name="pass"/> <input type="submit"/> </form> login app ------------- passing parameter with dispaching ----------------------------- <jsp:include page="/requestParams2.jsp" > <jsp:param name="sessionID" value="<%= session.getId() %>" /> </jsp:include> getting in another servlet and jsp --------------------------------------- <%@ page import="java.util.*" %> <% Enumeration parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String name = (String)parameterNames.nextElement(); out.println(name); out.println(request.getParameter(name) ); } %>
  • 14. Sepration of concern ------------------- no business logic should be done in jsp at any cost <jsp:useBean> <jsp:setProperty> <jsp:getProperty> Basic of jsp model ------------------- script file converted into eq servlet. no diff between servlet and jsp nut and bolts of jsp ----------------- Directive --------- include taglib*
  • 15. page 13 attributes not all imp Scriptlet ------- pure java code must be avoided diff to avoide expression --------- aka of short cut for out.print() decleation ---------- <%! %> whatever u want to put in insta/static comments ------- jsp comm html comm:show in view source include directive and include action ---------------------------------------- if content is changing dynamicall always go for action scope ====== page request session application pageContext Std action --------- <jsp:useBean........./> <jsp:setProperty ............/> <jsp:getProperty ............../> How java bean internally use reflection and serl...? ------------------------------------------------ what is reflection *
  • 16. ============================================================================ Day-2 ============================================================================ EL:Expression Language More on java beans ------------------- <form action ="LoginServlet" method="get"> ID:<input type="text" name="id"/></br> Name:<input type="text" name="name"/></br> Pass:<input type="password" name="pass"/></br> <input type="submit"/> </form> automatic type conversion processing of bean Expression Language Introduction ( E L ) ----------------------------------- Putting java code in jsp is bad habbit then what to do? --------------- Use EL JSP 2.0 spec. EL offers a simpler way to invoke Java code but he code itself belongs somewhere else Although EL looks like Java it behaves differently, so do not try and map the same Java with EL. EL are always within curly braces and prefixed with the dollar sign. The first named variable in the expression is either an implicit object or an attribute how EL make my life easy.... ------------------------------- EL example ------------ old way don't do now --------------------
  • 17. Please contact: <%= application.getAttribute("mail") %> EL way ------ please contact: ${applicationScope.mail} stop JSP from using scripting elements -------------------------------------- <web-app ...> ... <jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group> </jsp-config> ... </web-app> stop using EL ------------- <%@ page isELIgnored="true" %> Note: this takes priority over the DD tag above Scriptless JSP ============= EL provide better way to accept DTO send from controller to view Some Ex: ====== Consiser Servlet (controller) code ----------------------------------- Person p = new Person(); p.setName("Paul"); request.setAttribute("person", p); RequestDispatcher view = request.getRequestDispatcher ("result.jsp");
  • 18. view.forward(request, response); JSP (view) code ----------------- Person is: <%= request.getAttribute("person") %> Does it work? Correct way? -------------- <% Person p = (Person) request.getAttribute("person"); Person is: <%= p.getName() %> or Person is: <%= ((Person) request.getAttribute("person")).getName() %> Correct Way ---------- <jsp:useBean id="person" class="foo.Person" scope="request" /> Person is: <jsp:getProperty name="person" property="name" /> class Person {
  • 19. private String name; .... ... ... } public class Dog { private String dogName; ..... ..... } public class Person { private String personName; private Dog dog; ..... ..... } Person has A dog ---- Dog dog=new Dog(); dog.setDogName("myDog"); Person p=new Person(); p.setPersonName("foo"); p.setDog(dog); request.setAttribute("person", p); -------------------------------------------------------------------------------- ------ Expression Language ==================== More examples -------------- consider controller code ----------------------
  • 20. adding persons dog in request attributes in an servlet ----------------------------------------------------------- foo.Person p = new foo.Person(); p.setName("Paul"); foo.Dog dog = new foo.Dog(); dog.setName("Spike"); p.setDog(dog); request.setAttribute("person", p); getting same in jsp ------------------------ using tags <%= ((Person) request.getAttribute("person")).getDog ().getName() %> using EL Dog's name is: ${person.dog.name} Some more examples -------------------- in servlet --------- String[] footballTeams = { "Liverpool", "Manchester Utd", "Arsenal", "Chelsea" } request.setAttribute("footballList", footballTeams); in jsp ---------
  • 21. Favorite Team: ${footballList[0]} Worst Team: ${footballList["1"]} Note ["one"] would not work but ["10"] would <%-- using the arraylist toString() --------------------------------- All the teams: ${footballList} Another Example -------------- servlet code ---------------- java.util.Map foodMap = new java.util.HashMap(); foodMap.put("Fruit", "Banana"); foodMap.put("TakeAway", "Indian"); foodMap.put("Drink", "Larger"); foodMap.put("Dessert", "IceCream"); foodMap.put("HotDrink", "Coffee"); String[] foodTypes = {"Fruit", "TakeAway", "Drink", "Dessert", "HotDrink"} request.setAttribute("foodMap", foodMap); JSP code --------- Favorite Hot Drink is: ${foodMap.HotDrink}
  • 22. Favorite Take-Away is: ${foodMap["TakeAway"]} Favorite Dessert is: ${foodMap[foodTypes[3]]} EL JSTL JSP std tag library --------------------- core formatting sql xml String functions Custom tags ----------- user defind tags. in case JSTL dont have tag to solve ur problem. then go for custom tags (Dont cook food urself if get cooked food) Ex: There may be cases when you want multiple values for one given parameter name, which is when you use paramValues ============================================================ HTML Form ----------- <html><body> <form action="TestBean.jsp"> name: <input type="text" name="name">
  • 23. ID: <input type="text" name="empID"> First food: <input type="text" name="food"> Second food: <input type="text" name="food"> <input type="submit"> </form> </body></html> JSP Code ----------- Request param name is: ${param.name} <br> Request param empID is: ${param.empID} <br> <%-- you will only get the first value --> Request param food is: ${param.food} <br> First food is: ${paramValues.food[0]} <br> Second food is: ${paramValues.food[1]} <br> Here are some other parameters you can obtain, ----------------------------------------------------- host header -------- Host is: <%= request.getHeader("host•) %> Host is: ${header["host"]} Host is: $header.host} whether Request is post or get ? --------------------------------- Method is: ${pageContext.request.method}
  • 24. Cookie information ----------------- Username is: ${cookie.userName.value} Context init parameter (need to configure in dd) ----------------------- email is: <%= application.getInitParameter("mainEmail") %> email is: {$initParam.mainEmail} What has been covered till now -------------------------------- directive -------- <%@ page import="java.util.*" %> declaration --------- <%! int y = 3; %> EL Expression ------------- email: ${applicationScope.mail} scriptlet --------- <% Float one = new Float(42.5); %> expression --------- <%= pageContext.getAttribute(foo") %> action --------- <jsp:include page="foo.html" /> JSTL ======= The JSTL is hugh, version 1.2 has five libraries,
  • 25. four with custom tags and one with a bunch of functions for String manipulation •JSTL Core - core •JSTL fmt - formatting •JSTL XML - xml •JSTL sql - sql •JSTL function - string manipulation Hello world jstl ====================== <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html><body> ... <c:forEach var="i" begin="1" end="10" > <c:out value="${i}" /> </c:forEach> ... </body></html> Custom tags ==================== A Custom tag is a user defined JSP language element. When a JSP page containing custom tag is translated into a Servlet, the tag is converted to operations on an object called tag handler. -------------------- The Web container then invokes those operations when the JSP page•s servlet is executed. Note: 1. Custom tags can access all the objects available in JSP pages. 2. Custom tags can modify the response generated by the calling page. 3.Custom tags can be nested.
  • 26. Custom tag library consists of one or more Java classes called Tag Handlers and an XML tag library descriptor file (tag library). ---------------- -------------------------- javax.servlet.jsp.tagext. ----------------------------- A class which has to be a tag handler needs to implement <<Tag>> or<<IterationTag >> or <<BodyTag>> or it can also extend TagSupport or BodyTagSupport class. Let us create a custom tag which will does substring operation on given input. If SKIP_BODY ----------- is returned by doStartTag() then if body is present then it is not evaluated. If EVAL_BODY_INCLUDE ----------------- is returned, the body is evaluated and "passed through" to the current output.