1 / 56

What Is JavaServer Pages?

JavaServer Pages (JSP) is a technology for developing web pages that include dynamic content. With JSP, you can create web applications like shopping carts and employee directories, using both standard HTML elements and special JSP elements. JSP offers benefits over Servlets, including easier HTML writing and maintenance, the use of standard website development tools, and separation of business logic from page presentation. JSP also integrates with powerful Enterprise Java APIs and supports both scripting and element-based dynamic content.

jaynej
Download Presentation

What Is JavaServer Pages?

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. What Is JavaServer Pages? • JavaServer Pages is a technology for developing web pages that include dynamic content. • HTML page contains static content that always remains the same • A JSP page can change its content based on any number of variable items, including the identity of the user, the user's browser type, information provided by the user, and selections made by the user. • JSP can be used to create web applications like shopping carts and employee directories. • A JSP page contains standard markup language elements, such as HTML tags, just like a regular web page. • JSP page also contains special JSP elements that allow the server to insert dynamic content in the page

  2. JSP elements can be used for a wide variety of purposes, such as retrieving information from a database or registering user preferences. • When a user asks for a JSP page, the server executes the JSP elements, merges the results with the static parts of the page, and sends the dynamically composed page back to the browser • JSP defines a number of standard elements useful for any web application, such as accessing JavaBeans components, passing control between pages, and sharing information between requests, pages, and users.

  3. Programmers can also extend the JSP syntax by implementing application-specific elements that perform tasks such as accessing databases and Enterprise JavaBeans, sending email, and generating HTML to present application-specific data. • The combination of standard elements and custom elements allows for the creation of powerful web applications.

  4. Dynamic Content With JSP

  5. What is JSP Good For? • Servlets allow us to easily: • read data from user • read HTTP request • create cookies • etc. • It is not convenient to write long static HTML using Servlets • out.println("<h1>BlaBla</h1>" + "blablablablabla " + " lots more here...")

  6. JSP Idea • Use HTML for most of the page • Write Java code directly in the HTML page (similar to Javascript) • Automatically translate JSP to Servlet that actually runs

  7. Benefits of JSP over Servlets • It is easier to write and maintain HTML. • We can use standard website development tools. • JSP’s are translated into servlets. • Separation of Business Logic from Page Presentation

  8. Relationships • In servlets: HTML code is printed from java code • In JSP pages: Java code is embedded in HTML code Java HTML Java HTML

  9. JSP Life Cycle .

  10. Embedding Elements in HTML Pages <html> <body bgcolor="white"> <% java.util.Date clock = new java.util.Date( ); %> <% if (clock.getHours( ) < 12) { %> <h1>Good morning!</h1> <% } else if (clock.getHours( ) < 18) { %> <h1>Good day!</h1> <% } else { %> <h1>Good evening!</h1> <% } %> Welcome to our site, open 24 hours a day. </body> </html> For example, if the current time is 8:53 P.M., the resulting page sent from the server to the browser looks like this: <html> <body bgcolor="white"> <h1>Good evening!</h1> Welcome to our site, open 24 hours a day. </body> </html>

  11. Integration with Enterprise Java APIs JavaServer Pages is built on top of the Java Servlets API, JSP has access to all of the powerful Enterprise Java APIs, including: • JDBC • Remote Method Invocation (RMI) and OMG CORBA support • JNDI ( Java Naming and Directory Interface) • Enterprise JavaBeans (EJB) • JMS ( Java Message Service) • JTA ( Java Transaction API) • This means that you can easily integrate JavaServer Pages with your existing Java Enterprise solutions

  12. The JSP Advantage • JSP supports both scripting and element-based dynamic content, and allows programmers to develop custom tag libraries to satisfy application-specific needs. • JSP pages are precompiled for efficient server processing. • JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.

  13. JSP Page contents: Everything in JSP page can be broken into 2 categories: -> Elements or tags that are processed on the server. -> Everything other than elements that the JSP engine ignores(Template data).

  14. JSP is a Java based language and can utilize the potential of Java language • JSP Uses Tags to render pages into HTML code • JSP Tags can be classified into 5 groups • Directives • Declarations • Expressions • Scriptlets • Standard Actions • JSP Tags start with <% and end with %> • JSP Comments start with <%-- and end with --%>

  15. Directives • JSP directives serve as messages to the JSP container from JSP. • They are used to set global values. General Syntax is: <% @ directive name attribute =“value” %>

  16. Contd… Three types of directives: • Page directive • Include directive • Tag lib directive

  17. Contd… • Page directive: It defines a number of important attributes that effect the whole page. Syntax: <% @ page attribute %> Attributes: • Import <% @ page import = “java.sql.*” %> <%@ page import=“java.util.Collection”%> • Content type (contentType=“text/html;charset=ISO-8859-1) • Session <% @ page Session = “”true” %>

  18. Directives Cont .. • These are parsed and translated by the compiler before the compilation Syntax: <%@directive attribute=“value” ... %> Directive can be: page: use to provide information about it by way of attributes language=“java” the only supported language as of now session=“true” session will be created (default=“true”) errorPage=“errorpage.jsp” Any exception is redirected to it contentType=“text/html;charset=ISO-8859-1” isErrorPage=“false” true only for error page Example: <%@page language="java" import="java.sql.*,mypackage.myclass" session=”false”%>

  19. JSP Syntax Page Directive • Defines attributes that apply to an entire page <%@ page [ language=“java” ] [ extends=“package.class” ] [ import=“package.class” ] [ session=“true | false” ] [ buffer=“none | 8kb | sizekb” ] [ autoFlush=“true | false” ] [ isThreadSafe=“true | false” ] [ info=“text” ] [ errorPage=“relativeURL” ] [ contentType=“mimeType” ] [ isErrorPage=“true | false” ] %>

  20. Directives Cont .. import attribute: A comma seperated list of classes/packages to import <%@ page import="java.util.*,java.io.*" %> <%@ page import="java.util.*,coreservlets.*" %> contentTypeattribute:Sets the MIME-Type of the resulting document (default is text/html) <%@ page contentType="text/plain" %> <%@ page contentType="MIME-Type; charset=Character-Set" %> Note that instead of using the contentType attribute, you can write <% response.setContentType("text/plain"); %> include: used to include other html/jsp pages here <%@ include file=“abc.jsp” %> <%@ include file="relative url" %> taglib: Used to define new tags and prefixes <%@ tagliburi=“tlds/taglib.tld” prefix=“mytag” %>

  21. URI for the JSTL Libraries JSTL consists of five different type of tag libraries , which minimizes the name collisions among the actions in different categories ----------------------------------------------------------------------------------------------------- Library URI Prefix Core http://java.sun.com.jsp/jstl/core c XML processing http://java.sun.com.jsp/jstl/XML x 118Nformating http://java.sun.com.jsp/jstl/fmtfmt Database accesses http://java.sun.com.jsp/jstl/sqlsql Functions http://java.sun.com.jsp/jstl/functions fun

  22. JSP Scripting Elements • Scripting elements let you insert code into the servlet that will be generated from the JSP • Three forms: • Expressions of the form <%= expression %> that are evaluated and inserted into the output, • Scriptlets of the form <% code %> that are inserted into the servlet's _jspService method, and • Declarations of the form <%! code %> that are inserted into the servlet class, outside of any methods

  23. Declarations • Declarations are used to declare variables, methods etc., which will be used later in the page. • JSP Declaratives begins with <%! and ends with %> • Any amount of Java code can be embed in the JSP Declaratives. • Variables and functions defined in the declaratives are class level and can be used anywhere in the JSP page. • Syntax of JSP is as follows: <%! //java codes %> • Examples: • <%! int count = 0; %> • <%! double sqr(double x) { return x * x; } %> • <%! private intint counter ;%>

  24. Declarations Example: <%@page contentType="text/html" language=“java”%> <html> <body> <%! intcnt=0; private intgetCnt() { cnt++; return cnt; } %> Values of Cnt are:<br><%= getCnt()%><br>getCnt()%> </body> </html>

  25. Expressions • Expressions in JSP are single instructions. • Expressions begin with <%= and end with %> • There is no semicolon after the expression • Examples of expressions are as follows: <%= i++ %> <%= myMethod() %>

  26. public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setContentType("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter(); out.println("<H1>A Random Number</H1>"); out.println(Math.random()); ... } Expression Translation <H1>A Random Number</H1> <%= Math.random() %>

  27. Predefined or implicit Variables are used in Expressions • The following predefined variables can be used: • request, the HttpServletRequest • Represents the client’s request as an object and is a subclass of HttpServletRequest. It is used to get client’s form data • response, the HttpServletResponse • Response is a subclass of HttpServletResponse and is used to send out the information from server to client (browser)

  28. Cont.. • session, the HttpSession associated with the request • Represents a storage space common to all pages of the client. Anything stored here is available as long as the session is alive • out, the PrintWriter (a buffered version of type JspWriter) used to send output to the client Represents the write stream of the client and anything written here will be sent to the browser

  29. OtherImplicit variable • PageContext • Page attributes are availablethroughout the object • exception • Exception detailscanbeobtainedthroughthisobject • application • Variables in thisobject are availablethroughout the application, whichmeans all clients canaccess the same variable • config • Uses to getservlet configuration parameters • page • Represents this object

  30. Request Object methods: • Some of the request object methods are as follows: • <%=request.getMethod()%> • <%=request.getRequestURI()%> • <%=request.getProtocol()%> • <%=request.getPathInfo()%> • <%=request.getPathTranslated()%> • <%=request.getContentLength()%> • <%=request.getQueryString()%> • <%=request.getContentType()%> • <%=request.getServerName()%> • <%=request.getServerPort()%> • <%=request.getRemoteUser()%> • <%=request.getRemoteAddr()%> • <%=request.getRemoteHost()%> • <%=request.getAuthType()%>

  31. <HTML> <HEAD> <TITLE>JSP Expressions</TITLE></HEAD> <BODY> <H2>JSP Expressions</H2> <UL> <LI>Current time: <%= new java.util.Date() %> <LI>Your hostname: <%= request.getRemoteHost() %> <LI>Your session ID: <%= session.getId() %> <LI>The <CODE>testParam</CODE> form parameter: <%= request.getParameter("testParam") %> </UL> </BODY> </HTML>

  32. Encoded Unencoded

  33. Scriptlets • Scriptlets are small pieces of Java code that runs immediately. • Scriptlets start with <% and end with %> • These are sections of Java code embedded in the page Unlike expressions, they do not return a value • But may write directly to the page • JSP scriptletslet you insert arbitrary code into the servlet method that will be built to generate the page ( _jspService) • The syntax of a scriptlet is as shown below: <% // Any amount of Java code here %>

  34. Scriptlets • Java code,which is inserted into the servlet Example:   <%   //java codes    String userName=null; userName=request.getParameter("userName"); out.println( userName ) %> • Example: <% for( intinti=0; i<poll. i=0; i<poll.getAnswerCountgetAnswerCount(); i++ ) %>

  35. public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setContentType("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter(); out.println(foo()); bar(); ... } Scriptlet Translation <%= foo() %> <% bar(); %>

  36. HTML Code in Scriptlets • Scriptlets don't have to be entire Java Staments: <% if (Math.random() < 0.5) { %> You <B>won</B> the game! <% } else { %> You <B>lost</B> the game! <% } %> if (Math.random() < 0.5) { out.println("You <B>won</B> the game!"); } else { out.println("You <B>lost</B> the game!"); }

  37. Example <%! int n = 0; %> Page accessed: <%= ++n %> times <% if ( (n % 10) == 0 ) { n = 0; } %>

  38. RESULT

  39. JSP Standard actions • Standard actions: JSP tags JSP action elements result in some sort of action occurring while the JSP page is being executed, such as instantiating a Java object andmaking it available to the page . general tag syntax for JSP standard actions: <jsp:tagattr1="value1" attr2="value2" ... attrN="valueN"> ...body... </jsp:tag>

  40. Standard Actions • JSP Standard actions are predefined into the JSP engine. • JSP Standard actions start with <jsp:actionName and end with </jsp:actionName> • Some of the extensively used actions are: (jsp:useBean, jsp:setProperty, jsp:getProperty – manipulate a JavaBean) • <jsp:useBean> -- Creates an object of given type • <jsp:setProperty> -- Sets variable to a value from HTML • <jsp:getProperty> -- Gets a variable value into HTML • <jsp:include> -- Includes another page • <jsp:forward> -- Redirects the Page

  41. Example : Predefined bean <%@ page language="java" contentType="text/html" %> <html> <body bgcolor="white"> <jsp:useBean id="clock" class="java.util.Date" /> The current time at the server is: <ul> <li>Date: <jsp:getProperty name="clock" property="date" /> <li>Month: <jsp:getProperty name="clock" property="month" /> <li>Year: <jsp:getProperty name="clock" property="year" /> <li>Hours: <jsp:getProperty name="clock" property="hours" /> <li>Minutes: <jsp:getProperty name="clock" property="minutes" /> </ul> </body> </html>

  42. Using User Defined Classes Creating an object of type Abc <jsp:useBean id=“varname” class = “my.package.Abc” /> Getting value of the bean variables into HTML <b>The value of count in object is </b> <i> <jsp:getProperty name=“varname” property=“count” /> Setting Values of Bean: <jsp:setProperty name=“varname" property="*" /> <jsp:setProperty name=“varname" property=“count" param=“html_count" /> <jsp:setProperty name=“varname" property=“count" value=“100" />

  43. Standard Actions The jsp:include Action • This action lets you insert files into the page being generated • The file inserted when page is requested • The syntax looks like this: <jsp:include page="relative URL" flush="true" /> <jsp:include page=“abc.jsp” />

  44. The jsp:forward Action • Forwards request to another page <jsp:forward page="relative URL"/> <jsp:forwardpage=“abc.jsp"/> • Page could be a static value, or could be computed at request time • Examples: <jsp:forward page="/utils/errorReporter.jsp" /> <jsp:forward page="<%= someJavaExpression %>" />

  45. Create a web application using JSP to show welcome message to the user <html> <body bgcolor="wheat"> <form action=“wel.jsp"> <center> Name<input type="text" name="t1"> <input type="submit" value="send"> </center> </form> </body> </html>

  46. Wel.jsp <html> <body bgcolor="yellow"> <h1>Hello <%=request.getParameter("t1")%> Welcome to our website!</h1> </body> </html>

  47. Create a web application using JSP to show current date and time. Index.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> hello! the time is now <%=new java.util.Date()%> </body> </html> OUTPUT hello! the time is now Thu Apr 05 09:11:58 CEST 2012

  48. JSP Example .

More Related