Presentation is loading. Please wait.

Presentation is loading. Please wait.

Accelerating Server Side Programming with Java Server Pages (JSP) Atif Aftab Ahmed Jilani.

Similar presentations


Presentation on theme: "Accelerating Server Side Programming with Java Server Pages (JSP) Atif Aftab Ahmed Jilani."— Presentation transcript:

1 Accelerating Server Side Programming with Java Server Pages (JSP) Atif Aftab Ahmed Jilani

2 Agenda lUnderstanding the need for JSP lEvaluating the benefits of JSP lComparing JSP to other technologies lAvoiding JSP misconceptions lUnderstanding the JSP lifecycle lInstalling JSP pages lLooking at JSP in the real world

3 The Need for JSP lWith Servlets, it is easy to l Read form data l Read HTTP request headers l Set HTTP status codes and response headers l Use cookies and session tracking l Share data among servlets l Remember data between requests l Get fun, high-paying jobs lBut, it sure is a pain to l Use those println statements to generate HTML l Maintain that HTML

4 The JSP Framework lIdea: l Use regular HTML for most of page l Mark servlet code with special tags l Entire JSP page gets translated into a servlet (once), and servlet is what actually gets invoked (for each request)

5 Example Order Confirmation <LINK REL=STYLESHEET HREF="JSP-Styles.css“ TYPE="text/css"> Order Confirmation Thanks for ordering !

6 Benefits of JSP lJSP makes it easier to: l Write HTML l Read and maintain the HTML lJSP makes it possible to: l Use standard HTML tools such as Macromedia DreamWeaver or Adobe GoLive. l Have different members of your team do the HTML layout than do the Java programming lJSP encourages you to l Separate the (Java) code that creates the content from the (HTML) code that presents it

7 Setting Up Your Environment lSet your CLASSPATH. Not. lCompile your code. Not. lUse packages to avoid name conflicts. Not. lPut JSP page in special directory. Not. l install_dir/webapps/ROOT/ (HTML and JSP -- Tomcat) lUse special URLs to invoke JSP page. Not. l Use same URLs as for HTML pages (except for file extensions) lCaveats l Previous rules about CLASSPATH, install dirs, etc., still apply to regular Java classes used by a JSP page

8 Example JSP Expressions <META NAME="description" CONTENT="A quick example of JSP expressions."> <LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css">...

9 Example (Contd.) JSP Expressions Current time: Server: Session ID: The testParam form parameter:

10 Output lIf location was C:\tomcat\webapps\ROOT\Expressions.jsp

11 Translation/Request Time Confusion lWhat happens at page translation time? l JSP constructs get translated into servlet code. lWhat happens at request time? l Servlet code gets executed. No interpretation of JSP occurs at request time. The original JSP page is totally ignored at request time; only the servlet that resulted from it is used. lWhen does page translation occur? l Typically, the first time JSP page is accessed after it is modified. l Page translation does not occur for each request.

12 JSP Life Cycle

13 Invoking Java Code with JSP Scripting Elements

14 Uses of JSP Constructs lScripting elements calling servlet code directly lScripting elements calling servlet code indirectly (by means of utility classes) lBeans lServlet/JSP combo (MVC) lMVC with JSP expression language lCustom tags Simple Application Complex Application

15 Basic Syntax lExpressions Format: Evaluated and inserted into the servlet’s output. Equivalent to out.print(expression) lScriptlets Format: l Inserted verbatim into the servlet’s _jspService method (called by service) lDeclarations Format: l Inserted verbatim into the body of the servlet class, outside of any existing methods

16 JSP Expressions lFormat l lResult Expression evaluated, converted to String, and placed into HTML page at the place it occurred in JSP page That is, expression placed in _jspService inside out.print lExamples Current time: Your hostname:

17 JSP/Servlet Correspondence lOriginal JSP A Random Number lRepresentative resulting servlet code public void _jspService( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter(); out.println(" A Random Number "); out.println(Math.random());... }

18 Predefined Variables(Objects) lrequest l The HttpServletRequest (1st argument to service/doGet) lresponse l The HttpServletResponse (2nd arg to service/doGet) lout l The Writer (a buffered version of type JspWriter) used to send output to the client lsession l The HttpSession associated with the request (unless disabled with the session attribute of the page directive) lapplication l The ServletContext (for sharing data) as obtained via getServletContext().

19 Reading Three Params (JSP) Reading Three Request Parameters <LINK REL=STYLESHEET HREF="JSP-Styles.css“ TYPE="text/css"> Reading Three Request Parameters param1 : param2 : param3 :

20 JSP Scriptlets lFormat l lResult l Code is inserted verbatim into servlet's _jspService lExample <% String queryData = request.getQueryString(); out.println("Attached GET data: " + queryData); %> lXML-compatible syntax l Java Code

21 JSP/Servlet Correspondence lOriginal JSP foo lRepresentative resulting servlet code public void _jspService( HttpServletRequest request, HttpServletResponse response) throws ServletException { response.setContentType("text/html"); HttpSession session = request.getSession(); JspWriter out = response.getWriter(); out.println(" foo "); out.println(bar()); baz();... }

22 JSP Scriptlets: Example lSuppose you want to let end users customize the background color of a page.

23 JSP Scriptlets: Example Color Testing <% String bgColor = request.getParameter("bgColor"); if ((bgColor == null) || (bgColor.trim().equals(""))) { bgColor = "WHITE"; } %> "> Testing a Background of " "

24 JSP Scriptlets: Result

25 Make Parts of the JSP File Conditional Have a nice day! Have a lousy day! lRepresentative result if (Math.random() < 0.5) { out.println("Have a nice day!"); } else { out.println("Have a lousy day!"); }

26 JSP Declarations lFormat l lResult l Code is inserted verbatim into servlet's class definition, outside of any existing methods. lExamples l lDesign consideration l Fields are clearly useful. For methods, it is usually better to define the method in a separate Java class. lXML-compatible syntax l Java Code

27 JSP/Servlet Correspondence lOriginal JSP Some Heading <%! private String randomHeading() { return(" " + Math.random() + " "); } %>

28 JSP/Servlet Correspondence lPossible resulting servlet code public class Xyz implements HttpJspPage { private String randomHeading() { return(" " + Math.random() + " "); } public void _jspService( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HttpSession session = request.getSession(true); JspWriter out = response.getWriter(); out.println(" Some Heading "); out.println(randomHeading());... }

29 JSP Declarations: Example JSP Declarations <LINK REL=STYLESHEET HREF="JSP-Styles.css“ TYPE="text/css"> JSP Declarations Accesses to page since server reboot:

30 JSP Declarations: Result

31 jspInit and jspDestroy Methods lJSP pages, like regular servlets, sometimes want to use init and destroy lProblem: the servlet that gets built from the JSP page might already use init and destroy l Overriding them would cause problems. l Thus, it is illegal to use JSP declarations to declare init or destroy. lSolution: use jspInit and jspDestroy. l The auto-generated servlet is guaranteed to call these methods from init and destroy, but the standard versions of jspInit and jspDestroy are empty (placeholders for you to override).

32 JSP Declarations and Predefined Variables lProblem l The predefined variables (request, response, out, session, etc.) are local to the _jspService method. Thus, they are not available to methods defined by JSP declarations or to methods in helper classes. What can you do about this?

33 JSP Declarations and Predefined Variables lSolution: pass them as arguments. E.g. <%! private void someMethod( HttpSession s) { doSomethingWith(s); } %> lNote that the println method of JspWriter throws IOException l Use “throws IOException” for methods that use println

34 Summary lJSP Expressions Format: l Wrapped in out.print and inserted into _jspService lJSP Scriptlets Format: l Inserted verbatim into the servlet’s _jspService method lJSP Declarations Format: l Inserted verbatim into the body of the servlet class lPredefined variables l request, response, out, session, application lLimit the Java code that is directly in page l Use helper classes, beans, servlet/JSP combo (MVC), JSP expression language, custom tags

35 JSP directives lUse JSP directives to specify: l Scripting language being used l Interfaces a servlet implements l Classes a servlet extends l Packages a servlet imports l MIME type of the generated response

36 JSP Directive lBasic syntax: l l where the valid directive names are: èpage: èinclude: ètaglib:

37 Purpose of the page Directive lGive high-level information about the servlet that will result from the JSP page lCan control l Which classes are imported l What class the servlet extends l What MIME type is generated l How multithreading is handled l If the servlet participates in sessions l The size and behavior of the output buffer l What page handles unexpected errors

38 The import Attribute lFormat l l <%@ page import = "package.class1,...,package.classN" %> lPurpose l Generate import statements at top of servlet definition lNotes l Although JSP pages can be almost anywhere on server, classes used by JSP pages must be in normal servlet dirs èE.g.: è…/WEB-INF/classes or è…/WEB-INF/classes/directoryMatchingPackage èAlways use packages for utilities that will be used by JSP!

39 The Importance of Using Packages lWhat package will the system think that SomeHelperClass and SomeUtilityClass are in?... public class SomeClass { public String someMethod(...) { HelperClass test = new HelperClass(...); String someString = utilityClass.someStaticMethod(...);... } }

40 The Importance of Using Packages (Continued) lWhat package will the system think that HelperClass and SomeUtilityClass are in?... <% HelperClass test = new SomeHelperClass(...); String someString = UtilityClass.someStaticMethod(...); %>

41 Example <%! private String randomID() { int num = (int)(Math.random()*10000000.0); return("id" + num); } private final String NO_VALUE = " No Value "; %> <% String oldID = CookieUtilities.getCookieValue( request, "userID", NO_VALUE); if (oldID.equals(NO_VALUE)) { String newID = randomID(); Cookie cookie = new LongLivedCookie("userID", newID); response.addCookie(cookie); } %> This page was accessed on with a userID cookie of.

42 The contentType and pageEncoding Attributes lFormat l l <%@ page contentType="MIME-Type; charset=Character-Set" %> l lPurpose l Specify the MIME type of the page generated by the servlet that results from the JSP page lNotes l Attribute value cannot be computed at request time l See section on response headers for table of the most common MIME types

43 Generating Excel Spreadsheets First Last Email Address Marty Hall hall@coreservlets.com Larry Brown brown@coreservlets.com Steve Balmer balmer@ibm.com Scott McNealy mcnealy@microsoft.com <%@ page contentType = "application/vnd.ms-excel" %>

44

45 Conditionally Generating Excel Spreadsheets <% boolean usingExcel = checkUserRequest(request); %> <%@ page contentType = "application/vnd.ms-excel" %>

46 The session Attribute lFormat l lPurpose l To designate that page not be part of a session lNotes l By default, it is part of a session l Saves memory on server if you have a high- traffic site l All related pages have to do this for it to be useful

47 The buffer Attribute lFormat l lPurpose l To give the size of the buffer used by the out variable lNotes l Buffering lets you set HTTP headers even after some page content has been generated (as long as buffer has not filled up or been explicitly flushed) l Servers are allowed to use a larger size than you ask for, but not a smaller size l Default is system-specific, but must be at least 8kb

48 The errorPage Attribute lFormat l lPurpose l Specifies a JSP page that should process any exceptions thrown but not caught in the current page lNotes l The exception thrown will be automatically available to the designated error page by means of the "exception“ variable l The web.xml file lets you specify application-wide error pages that apply whenever certain exceptions or certain HTTP status codes result. l The errorPage attribute is for page-specific error pages

49 The isErrorPage Attribute lFormat l lPurpose l Indicates whether or not the current page can act as the error page for another JSP page lNotes l A new predefined variable called exception is created and accessible from error pages l Use this for emergency backup only; explicitly handle as many exceptions as possible l Don't forget to always check query data for missing or malformed values

50 Error Pages: Example … Computing Speed <%! private double toDouble(String value) { return(Double.parseDouble(value)); } %> <% double furlongs = toDouble(request.getParameter("furlongs")); double fortnights = toDouble(request.getParameter("fortnights")); double speed = furlongs/fortnights; %> Distance: furlongs. Time: fortnights. Speed: furlongs per fortnight.

51 Error Pages: Example (Continued) … Error Computing Speed ComputeSpeed.jsp reported the following error:. This problem occurred in the following place:

52 Including Files at Request Time: jsp:include lFormat l lPurpose l To reuse JSP, HTML, or plain text content l To permit updates to the included content without changing the main JSP page(s) lNotes l JSP content cannot affect main page: only output of included JSP page is used l Relative URLs that starts with slashes are interpreted relative to the Web app, not relative to the server root. l You are permitted to include files from WEB-INF

53 Example: A News Headline Page (Main Page) … What's New at JspNews.com Here is a summary of our three most recent news stories:

54 A News Headline Page, (First Included Page) Bill Gates acts humble. In a startling and unexpected development, Microsoft big wig Bill Gates put on an open act of humility yesterday. More details... l Note that the page is not a complete HTML document; it has only the tags appropriate to the place that it will be inserted

55 A News Headline Page: Result

56 Including Files at Page Translation Time: lFormat l lPurpose l To reuse JSP content in multiple pages, where JSP content affects main page lNotes l Servers are not required to detect changes to the included file, and in practice they don't. l Thus, you need to change the JSP files whenever the included file changes. l You can use OS-specific mechanisms such as the Unix "touch" command, or l

57 jsp:include vs.

58 Which Should You Use? lUse jsp:include whenever possible l Changes to included page do not require any manual updates l Speed difference between jsp:include and the include directive (@include) is insignificant lThe include directive ( ) has additional power, however l Main page è l Included page è

59 Include Directive Example: Reusable Footers <%-- The following become fields in each servlet that results from a JSP page that includes this file. -- %> <%! private int accessCount = 0; private Date accessDate = new Date(); private String accessHost = " No previous access "; %> This page © 2003 my-company. This page has been accessed times since server reboot. It was most recently accessed from at.

60 Reusing Footers: Typical Main Page … Some Random Page Information about our products and services. Blah, blah, blah. Yadda, yadda, yadda.

61 Reusing Footers: Result

62 Understanding jsp:include vs. Footer defined the accessCount field (instance variable) If main pages used accessCount, they would have to use @include l Otherwise accessCount would be undefined In this example, the main page did not use accessCount l So why did we use @include?

63 Thank You!


Download ppt "Accelerating Server Side Programming with Java Server Pages (JSP) Atif Aftab Ahmed Jilani."

Similar presentations


Ads by Google