Jsp Notes

9,078 views

Published on

JSP, EL. JSTL introduction

Published in: Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
9,078
On SlideShare
0
From Embeds
0
Number of Embeds
3
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Jsp Notes

  1. 1. Tomcat 7Servlet 3.0------------- servelet anno Synch and Aych processing*JEE 5 or JEE 6------------both are same tech...MVCView:jspController: servlet/ filterJSP-----if both servelt and jsp are same the why two?-------------------------------------------CGI and PerlServletASPJSP= Java Server Pages-------- to simplify the web app developmentASP.net------Struts-------Velocity--------jsp is same as servlet--------------------------jsp should be convered in servlet.------------------------------------Servlet container
  2. 2. JSP containerJSP 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. 3. no html and jsp codeexpresssion------------ <%= 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. 4. ruturn "hi"; }%><% out.println("i:"+i); out.print(fun());%><%=i++%>is equivalent to<% out.print(i++);%>JSP key topics=======================Java bean in jspELJSTLJSP std tag liberaryCustome tagShould be used in place of scriptlet ---------class MyServlet extends HttpServlet{ int i=0; public void fun() {
  5. 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. 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. 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 pagerequest doGet(..........request, ........res)session===>HttpSession s=req.getSession()application==>getServletContext()
  8. 8. Implicit Object====================JspWriter outHttpServletRequest request request.setAttribute("key","foo"); String temp=request.getAttribute("key");HttpServletResponse responseHttpSession session session.setAttribute("key","foo"); String temp=session.getAttribute("key");ServletContext application application.setAttribute("key","foo"); String temp=application.getAttribute("key");ServletConfig configThrowable exceptionPageContext 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. 9. RequestDispacher rd=request.getRequestDispacher("show.jsp"); rd.forward(req,res); <jsp:include> <jsp:forward> <jsp:plugin> <jsp:param> appletAPI 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. 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. 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. 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 dont 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. 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. 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 jspnut and bolts of jsp----------------- Directive --------- include taglib*
  15. 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. 16. ============================================================================Day-2============================================================================EL:Expression LanguageMore 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 conversionprocessing of beanExpression 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 oran attribute how EL make my life easy.... ------------------------------- EL example ------------ old way dont do now --------------------
  17. 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 aboveScriptless JSP=============EL provide better way to accept DTO send from controller to viewSome Ex:======Consiser Servlet (controller) code----------------------------------- Person p = new Person(); p.setName("Paul"); request.setAttribute("person", p); RequestDispatcher view = request.getRequestDispatcher("result.jsp");
  18. 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() %>orPerson 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. 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. 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 Dogs name is: ${person.dog.name} Some more examples -------------------- in servlet --------- String[] footballTeams = { "Liverpool", "Manchester Utd", "Arsenal", "Chelsea" } request.setAttribute("footballList", footballTeams); in jsp ---------
  21. 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. 22. Favorite Take-Away is: ${foodMap["TakeAway"]}Favorite Dessert is: ${foodMap[foodTypes[3]]}ELJSTLJSP std tag library--------------------- core formatting sql xml String functionsCustom 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 givenparameter name, which is when you use paramValues============================================================HTML Form-----------<html><body><form action="TestBean.jsp"> name: <input type="text" name="name">
  23. 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. 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. 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 manipulationHello 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 isexecuted.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. 26. Custom tag library consists of one or more Java classescalled Tag Handlers and an XML tag library descriptor file (tag library). ---------------- --------------------------javax.servlet.jsp.tagext.-----------------------------A class which has to be a tag handlerneeds to implement <<Tag>> or<<IterationTag >> or <<BodyTag>>orit 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 notevaluated.If EVAL_BODY_INCLUDE----------------- is returned, the body is evaluated and "passed through" to the currentoutput.

×