Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 JSP – Java Server Pages Representation and Management of Data on the Internet.

Similar presentations


Presentation on theme: "1 JSP – Java Server Pages Representation and Management of Data on the Internet."— Presentation transcript:

1 1 JSP – Java Server Pages Representation and Management of Data on the Internet

2 2 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(" Bla Bla " + "bla bla bla bla bla " + " lots more here...")

3 3 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

4 4 Relationships In servlets: HTML code is printed from java code In JSP pages: Java code is embedded in HTML code Java HTML Java HTML

5 5 Example Hello World Example Hello World Example Hello !

6 6 Page is in the proj web application: tomcat_home/webapps/proj/HelloWorld.jsp Invoked with URL: http:// : /proj/HelloWorld.jsp?name=snoopy

7 7 Invoked with URL (no parameter): http:// : /proj/HelloWorld.jsp

8 8 JSP Limitations and Advantages JSP can only do what a Servlet can do Easier to write and maintain HTML Easier to separate HTML from code Can use a "reverse engineering technique": create static HTML and then replace static data with Java code

9 9 What does a JSP-Enabled Server do? receives a request for a.jsp page parses it converts it to a Servlet (JspPage) with your code inside the _jspService() method runs it

10 10 Translation of JSP to Servlet Two phases: –Page translation: JSP is translated to a Servlet. Happens the first time the JSP is accessed –Request time: When page is requested, Servlet runs No interpretation of JSP at request time!

11 11 Design Stategy Do not put lengthy code in JSP page Do put lengthy code in a Java class and call it from the JSP page Why? Easier for –Development (written separately) –Debugging (find errors when compiling) –Testing –Code Reuse

12 12 The Source Code In Tomcat 3.2.1, you can find the generated Java and the class files in a subdirectory under tomcat_home/work.

13 13 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 that are evaluated and inserted into the output, –Scriptlets of the form that are inserted into the servlet's _jspService method, and –Declarations of the form that are inserted into the servlet class, outside of any methods

14 14 JSP Expressions A JSP expression is used to insert Java values directly into the output It has the following form: Example: –

15 15 JSP Expressions A JSP Expression is evaluated The result is converted to a string The string is inserted into the page This evaluation is performed at runtime (when the page is requested), and thus has full access to information about the request

16 16 Expression Translation A Random Number 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(" A Random Number "); out.println(Math.random());... }

17 17 Predefined Variables The following predefined variables can be used: –request, the HttpServletRequest –response, the HttpServletResponse –session, the HttpSession associated with the request –out, the PrintWriter (a buffered version of type JspWriter) used to send output to the client

18 18 JSP Expressions JSP Expressions Current time: Your hostname: Your session ID: The testParam form parameter:

19 19 Encoded Unencoded

20 20 JSP Scriplets JSP scriptlets let you insert arbitrary code into the servlet method that will be built to generate the page ( _jspService ) Scriptlets have the following form: Scriptlets have access to the same automatically defined variables as expressions. Why?

21 21 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

22 22 Producing Code Scriptlets can produce output by printing into the out variable Example: <% String queryData = request.getQueryString(); out.println("Attached GET data: " + queryData); %> Would we want to use a scriptlet in this case?

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

24 24 JSP Declaration A JSP declaration lets you define methods or fields that get inserted into the servlet class (outside of all methods) It has the following form: Declarations do not produce output They are used to define variables and methods Should you define a method in a JSP declaration?

25 25 Declaration Example Print the number of times the current page has been requested since the server booted (or the servlet class was changed and reloaded): <%! private synchronized int incAccess() { return ++access; } %> Accesses to page since server reboot: Should accessCount be static?

26 26 public class xxxx implements HttpJspPage { private int accessCount = 0; private synchronized int incAccess() { return ++access;} 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(" Accesses to page since server reboot: "); out.println(incAccess());... }... }

27 27 Predefined Variables As we have seen before, there are variables that can be used in the code There are eight automatically defined variables, sometimes called implicit objects We saw 4 variables: request, response, out, session Other 4 variables: application, config, pageContext, page

28 28 More Details: request, response request: the HttpServletRequest response: the HttpServletResponse The output stream is buffered It is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client Use request to save page specific values

29 29 More Details: out This is the PrintWriter used to send output to the client Actually a buffered version of PrintWriter called JspWriter You can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive

30 30 More Details: session This is the HttpSession object associated with the request Sessions are created automatically, so this variable is bound even if there was no incoming session reference (unless session was turned off using the session attribute of the page directive) Use session to store client specific values

31 31 Another Variable: application This is the ServletContext as obtained via getServletConfig().getContext() Remember: –Servlets and JSP pages can hold constant data in the ServletContext object –Getting and setting attributes is with getAttribute and setAttribute –The ServletContext is shared by all the servlets in the server Use application to store web application specific values

32 32 Another Variable: config This is the ServletConfig of the page, as received in init method Remember: Contains Servlet specific initialization parameters

33 33 Another Variable: pageContext pageContext encapsulates use of server- specific features like higher performance JspWriters Access server-specific features through this class rather than directly, your code will still run on "regular" servlet/JSP engines

34 34 Another Variable: page Simply a synonym for this page is not very useful in JSP pages It was created as a placeholder for the time when the scripting language could be something other than Java

35 35 Note about Predefined Variables Predefined variables are local to the _jspService method. How can we use them in methods that we define? When using out in a method, note that it might throw a IOException

36 36 JSP Directives A JSP directive affects the structure of the servlet class that is created from the JSP page It usually has the following form: Multiple attribute settings for a single directive can be combined: <%@ directive attribute1="value1"... attributeN="valueN" %>

37 37 Three Types of Directives page, which lets you do things like –import classes –customize the servlet superclass include, which lets you insert a file into the servlet class at the time the JSP file is translated into a servlet taglib, which indicates a library of custom tags that the page can include

38 38 page Directive Attributes import attribute: A comma seperated list of classes/packages to import contentType attribute: Sets the MIME-Type of the resulting document (default is text/html) Note that instead of using the contentType attribute, you can write

39 39 More page Directive Attributes isThreadSafe=“true|false” –false indicates that the Servlet should implement the SingleThreadModel session=“true|false” –false indicates that a session should not be created –Saves memory –All related pages must do this!!! buffer=“sizekb|none” – specifies the buffer size for the JspWriter out Default is Server Dependant

40 40 More page Directive Attributes autoflush=“true|false” –Flush buffer when full or throws an exception when buffer isfull extends=“package.class” –Makes Servlet created a subclass of class supplied –Don't use this! Why? info=“message” –A message for the getServletInfo method

41 41 More page Directive Attributes errorPage=“url” –Define a JSP page that handles uncaught exceptions –available to next page by exception variable –example isErrorPage=“true|false” –allows the page to be an error page

42 42 Reading From Database <% Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection("jdbc:oracle:thin:" + "snoopy/snoopy@sol4:1521:stud"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("Select * from a"); ResultSetMetaData md = rs.getMetaData(); int col = md.getColumnCount(); %>

43 43 Note: Is this a convenient way to print out a table? What would be a better way?

44 44 Reading From Database Oops. There was an error when you accessed the database. Here is the stack trace:

45 45 Accessing ReadingDatabase when there is a table "a" Accessing ReadingDatabase when there is no table "a"

46 46 The include Directive This directive lets you include files at the time the JSP page is translated into a servlet The directive looks like this: JSP content can affect main page servers don't notice changes in included files

47 47 Reading From Database Here is an interesting page. Bla, Bla, Bla, Bla. BlaBla.jsp Page Created for Dbi Course. Email us here. Accesses to page since server reboot: AccessCount.jsp

48 48

49 49 Writing JSP in XML We can replace the JSP tags with XML tags that represent – Expressions –Scriptlets –Declarations –Directives

50 50 Java Expression Code Java Java Declaration <jsp:directive.type Attribute = value/>

51 51 Actions JSP actions use constructs in XML syntax to control the behavior of the servlet engine You can –dynamically insert a file, –reuse JavaBeans components, –forward the user to another page, or –generate HTML for the Java plugin

52 52 Available Actions jsp:include - Include a file at the time the page is requested jsp:useBean, jsp:setProperty, jsp:getProperty – manipulate a JavaBean (not discussed today) jsp:forward - Forward the requester to a new page jsp:plugin - Generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin (not discussed today)

53 53 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:

54 54 The jsp:forward Action Forwards request to another page Page could be a static value, or could be computed at request time Examples: " />

55 55 Comments –A JSP comment, ignored by JSP-to-scriptlet translator –An HTML comment, Passed through to resultant HTML –Any embedded JSP scripting elements, directives, or actions are executed normally /* comment */ or // comment –Java comment, Part of the Java code

56 56 Quoting Conventions <\% - used in template text (static HTML) and in attributes where you really want <% %\> - used in scripting elements and in attributes where you really want %> \‘ \” - for using quotes in attributes \\ for having \ in an attribute

57 57 Init and Destroy In JSP pages, like regular servlets, sometimes want to use init and destroy It is illegal to use JSP declarations to override init or destroy, since they are already implemented (usually) by Servlet created Instead use jspInit and jspDestroy –The auto-generated servlet is guaranteed to call these methods from init and destroy –The standard versions of jspInit and jspDestroy are empty (placeholders for you to override)

58 58 Material Not Covered Java beans: Using Java beans you can simplify the process of sharing information between JSP pages and Servlets. (How can you share information now?) Custom Tags: You may define new tags and Java classes that define what should be done when the tag appears in a JSP page

59 59 JSP versus JavaScript Q: Can/Should you have JSP and Javascript in the same page? Q: Can you validate a form using JavaScript? Where should the code go? Q: Can you validate a form using JSP? Where should the code go?


Download ppt "1 JSP – Java Server Pages Representation and Management of Data on the Internet."

Similar presentations


Ads by Google