4. jsp

583 views

Published on

JSP (Java Server Pages) Lecture # 4
Breif detail lecture about the JSP with example code the tutorial thing such as how to create, deploy etc etc

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
583
On SlideShare
0
From Embeds
0
Number of Embeds
149
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

4. jsp

  1. 1. IMRAN DAUDFOUNDATION UNIVERSITYINSTITUTE OF MANAGEMENT ANDCOMPUTER SCIENCESImran DaudFUIMCSWeb EngineeringJSP
  2. 2. Intro to JSP Sun‟s Solution for developing dynamic websites. Server side scripting support for creating databasedriven web applications. Web file always has „.jsp‟ extension. Insert java code into JSP file. On receiving request, JSP pages are loaded intoserver memory for its execution. JSP Services are efficient and client is served in shortperiod of time.
  3. 3. Web-Server for JSP Number of web-servers are available. Apache TomCat WebSphere GalssFish etc
  4. 4. Setup NetBeans Start NetBeans Goto File->New Project…
  5. 5. Name & Location for Project
  6. 6. Choose Web-Server
  7. 7. Install New Web-Server
  8. 8. Installation and Login DetailsFirst Installrequiredweb-server.Give serverlocationUsername &Password
  9. 9. We use Already Installed with NetBeans
  10. 10. Test Web-Server Run jsp file to test server by clicking green playbutton.
  11. 11. JSP Tags <% (scriptless) <@ (directive page, include and taglib) <%-- (comment)
  12. 12. JSP Tags DirectivesIn the directives we can import packages, define error handlingpages or the session information of the JSP page. DeclarationsThis tag is used for defining the functions and variables to be usedin the JSP. ScripletsIn this tag we can insert any amount of valid java code and thesecodes are placed in _jspService method by the JSP engine. ExpressionsWe can use this tag to output any data on the generated page. Thesedata are automatically converted to string and printed on the outputstream
  13. 13. Directive<%@directive attribute="value" %> Where directive may be: page: page is used to provide the information about it.Example: <%@page language="java" %> include: include is used to include a file in the JSP page.Example: <%@ include file="/header.jsp" %> taglib: taglib is used to use the custom tags in the JSP pages(custom tags allows us to defined our own tags).Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
  14. 14. Attributes can be language="java"This tells the server that the page is using the java language. Current JSP specification supportsonly java language.Example: <%@page language="java" %> extends="mypackage.myclass"This attribute is used when we want to extend any class. We can use comma(,) to import morethan one packages.Example: <%@page language="java" import="java.sql.*,mypackage.myclass" %> session="true"When this value is true session data is available to the JSP page otherwise not. By default thisvalue is true.Example: <%@page language="java" session="true" %> errorPage="error.jsp"errorPage is used to handle the un-handled exceptions in the page.Example: <%@page language="java" session="true" errorPage="error.jsp" %> contentType="text/html;charset=ISO-8859-1"Use this attribute to set the mime type and character set of the JSP.Example: <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1" %>
  15. 15. Adding Scriptless <% opening tag %> closing tag To print message<% =“Hello World” %> To print <% = new java.util.Date() %>
  16. 16. JSP Declarations you must use the <%! and %> sequences to encloseyour declarations.<%!Date theDate = new Date();Date getDate() {out.println( "In getDate() method");return theDate;}%>Hello! The time is now <%= getDate() %>
  17. 17. Practice Make website counter…….
  18. 18. Declaration and Website Counter<%! static int i=0; private int getCount(){ return ++i; }%><%=getCount()%>
  19. 19. Variables in Scriptless request:request represents the clients request and is a subclass of HttpServletRequest. Usethis variable to retrieve the data submitted along the request.Example:<%//java codesString userName=null;userName=request.getParameter("userName");%> response:response is subclass of HttpServletResponse. session:session represents the HTTP session object associated with the request. out:out is an object of output stream and is used to send any output to the client.
  20. 20. Handling „Request‟ Steps Make index page with „form‟ containing username andpassword. Use post or get method within form tag. Make two buttons submit and rest. Handle request in another jsp page. Methods to use are: Request Pagecontext(to redirect page)
  21. 21. Request methods very useful pre-defined variable is "request". It is of type javax.servlet.http.HttpServletRequest <%request.getRemoteHoste(); orrequest.getRemoteAddr(); %>
  22. 22. JSP Session Associate any data with session by using . As long as session is maintained with user data willbe accessible on any page of website. Session object is associated with each user visitingthat website. Example: Associate username with session withwebsite of three pages.
  23. 23. How to Mix Scriptless and HTML
  24. 24. Import package <%@page import="java.util.*" %> <HTML> <BODY><% System.out.println( "Evaluating date now" );Date date = new Date(); %> Hello! The time is now <%= date %> </BODY> </HTML>
  25. 25. JSP Beans JSP introduces another organized way to retrieveform data (but also supports other functionalities). That is by introducing bean.(This is not full beans) Define java with settter andgetter functions.
  26. 26. Bean Proporties i) It has a public no-args constructor ii) It has set and get methods for its properties. iii) It may have any general functions.
  27. 27. Steps in Creating JSP Beans Create html page with form data by setting actionpage. Create java class with setter and getter function withsame name as defined in form fccccdcx. Create JSP page that will handle request data withfollowing tags. <jsp:useBean id=“mybean” class=“package.className"scope="session"/> <jsp:setProperty name="mybean" property="*" /> Retrieve data by following command. <%=mybean.getPassword()%>
  28. 28. Scope of Bean Scope= “Page” (only in current page of page specified) Scope = “request” (within request) Scope = “session” (all pages)
  29. 29.  If we access parameter in third page using „request‟object then it shows null value. But same can be accessed using session object, ifscope is set to session. Now we can also access parameter through „request‟object with following command in 2nd page. <jsp:forward page="session.jsp" /> Use following to include page in existing page <jsp:include = “page.jsp” flush = “false” />
  30. 30. Quiz Use beans to make website counter……
  31. 31. Tag Libraries Also known as custom tags defined by user. Use to initiate any custom action. Custom actions include form processing, accessingdatabases and other enterprise services such as emailand directories, and flow control.
  32. 32. Features of Custom Tags They can be customized via attributes passed from the callingpage. They have access to all the objects available to JSP pages. They can modify the response generated by the calling page. They can communicate with each other. You can create andinitialize a JavaBeans component, create a variable that refersto that bean in one tag, and then use the bean in another tag. They can be nested within one another, allowing for complexinteractions within a JSP page.
  33. 33. Custom Tags Declare Tag Libraries <%@ taglib uri="/tlt" prefix="tlt" %> „Uri‟ attribute refers to a URI that uniquely identifies the taglibrary. The prefix attribute distinguishes tags provided by a given taglibrary from those provided by other tag libraries.
  34. 34. StepsTo define a tag, you need to: First declare the tags in a tag librarydescriptor(TLD). Develop a tag handler and helper classes for the tag.
  35. 35. Tag HandlerTag Handler Tag handler object is invoked by jsp container toevaluate custom tag. This tag handler is java file with all custom actionsdefined in it. We only use overridden functions
  36. 36. Classes to Import for handler TagSupport SimpleTagSupport
  37. 37. Tag Library Descriptor (TLD)
  38. 38. How to ? Create New File Tag Library Descriptor. Create Tag Handler file. Set functionality in tag handler. (once tag handler file is createdit automatically will write basic tags in TLD file). Call custom tag using following <%@taglib uri="mytld" prefix="mytag" %> <mytag:mytaghandler/>
  39. 39. Database Pre-Req: MySQL Server MySQL Workbench Create Database with table and attributes. WAMP Server Important Include SQL Library in Library folder before stating toimplement your project.
  40. 40. Steps to follow Import SQL Package in JSP File <%@ page language="java" import="java.sql.*" %> Load MySQL Driver Class.forName("com.mysql.jdbc.Driver"); Create Connection with SQL Server Connection c=DriverManager.getConnection("jdbc:mysql://localhost:3300/mydb","root", "123"); Statement s= c.createStatement(); ResultSet Statement ResultSet rs=s.executeQuery("Select * from student");
  41. 41. Show Results while (rs.next()) {out.println(rs.getString("myfield")+"<br>");}
  42. 42. JSTL Use JSTL Tags are used for Iteration and conditionals Tags for manipulating XML documents Internationalization tags SQL tags.
  43. 43. JSTL
  44. 44. JSTL Steps Add JSTL library by right clicking on library folder ofproject. To use JSTL in JSP file use following <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
  45. 45. JSTL Core Tags
  46. 46. JSTL SQL Tags
  47. 47. JSTL Functions
  48. 48. JSTL Format Tags
  49. 49. Reference http://www.csl.mtu.edu/cs2321/ Netbeans.org Roseindia.net Jsptut.com tutorialspoint.com/jsp

×