Presentation is loading. Please wait.

Presentation is loading. Please wait.

INVOKING JAVA CODE WITH JSP SCRIPTING ELEMENTS. Creating Template Text A large percentage of your JSP document consists of static text (usually HTML),

Similar presentations


Presentation on theme: "INVOKING JAVA CODE WITH JSP SCRIPTING ELEMENTS. Creating Template Text A large percentage of your JSP document consists of static text (usually HTML),"— Presentation transcript:

1 INVOKING JAVA CODE WITH JSP SCRIPTING ELEMENTS

2 Creating Template Text A large percentage of your JSP document consists of static text (usually HTML), known as template text. HTML look normal, and it simply “passed through” to the client by the servlet created to handle the page. There are 2 minor exceptions to the “template text is passed straight through” rule First, if you want to have in the output, you need to put in the template text Second, if you want a comment to appear in the JSP page but not in the resultant document, use HTML comments of the form are passed through to the client normally.

3 Invoking Java Code from JSP There are a number of different ways to generate dynamic content from JSP,(Simple application or small development team To Complex application or large development team) Call Java code directly. Place all Java code in JSP page. Appropriate only for very small amounts of code. Call Java code indirectly. Develop separate utility classes. Insert into JSP page only the Java code needed to invoke the utility classes. Use beans. Develop separate utility classes structured as beans. Use jsp:useBean, jsp:getProperty, and jsp:setProperty to invoke the code. Use the MVC architecture. Have a servlet respond to original request, look up data, and store results in beans. Forward to a JSP page to present results. JSP page uses beans. Use the JSP expression language. Use shorthand syntax to access and output object properties. Usually used in conjunction with beans and MVC. Use custom tags. Develop tag handler classes. Invoke the tag handlers with XML-like custom tags.

4 Limiting the Amount of Java Code in JSP Pages You have two options – Put 25 lines of Java code directly in the JSP page – Put those 25 lines in a separate Java class and put 1 line in the JSP page that invokes it Why is the second option much better? – Development. You write the separate class in a Java environment (editor or IDE), not an HTML environment – Compilation. You can press the Build button in IDE to compile a regular java class - Debugging. If you have syntax errors, you see them immediately at compile time. Simple print statements can be seen. – Testing. You can write a test routine with a loop that does 10,000 tests and reapply it after each change. – Reuse. You can use the same class from multiple pages.

5 Types of JSP Scripting Elements JSP scripting elements let you insert Java code into the servlet that will be generated from the JSP page. There are three forms: 1. Expressions of the form, which are evaluated and inserted into the servlet’s output. 2. Scriptlets of the form, which are inserted into the servlet’s _jspService method (called by service). 3. Declarations of the form, which are inserted into the body of the servlet class, outside any existing methods.

6 Using JSP Expressions A JSP expression is used to insert values directly into the output. It has the following form: The expression is evaluated, converted to a string, and inserted in the page. This evaluation is performed at runtime (when the page is requested) and thus has full access to information about the request. For example, the following shows the date/time that the page was requested. Current time:

7 Predefined Variables To simplify the expressions, you can use a number of predefined variables (or “implicit objects”). The system simply tells you what names it will use for the local variables in _jspService (the method that replaces doGet in servlets that result from JSP pages). request, the HttpServletRequest. response, the HttpServletResponse. session, the HttpSession associated with the request (unless disabled with the session attribute of the page directive) out, the Writer (a buffered version of type JspWriter) used to send output to the client. application, the ServletContext. This is a data structure shared by all servlets and JSP pages in the Web application and is good for storing shared data. Here is an example: Your hostname:

8 JSP/Servlet Correspondence JSP expressions basically become print (or write) statements in the servlet that results from the JSP page. Whereas regular HTML becomes print statements with double quotes around the text, JSP expressions become print statements with no double quotes. Instead of being placed in the doGet method, these print statements are placed in a new method called _jspService that is called by service for both GET and POST requests. Original JSP A Random Number Representative resulting servlet code public void _jspService(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { response.setContentType("text/html"); HttpSession session = request.getSession(); JspWriter out = response.getWriter(); out.println(" A Random Number "); out.println(Math.random());... }

9 XML Syntax for Expressions XML authors can use the following alternative syntax for JSP expressions: Java Expression Don’t mix the XML version and the standard JSP version ( ) in the same page. To use the XML version, you must use XML syntax in the entire page. This requirement means that you have to enclose the entire page in a jsp:root element. Most developers use this XML version when they are either generating XML documents or when the JSP page is itself the output of some XML process Note that XML elements, unlike HTML ones, are case sensitive. So, be sure to use jsp:expression in lower case.

10 Example: JSP Expressions JSP Expressions JSP Expressions Current time: Server: Session ID: The testParam form parameter:

11 Comparing Servlets to JSP Pages : Reading Three Params (Servlet) JSP works best when the structure of the HTML page is fixed but the values at various places need to be computed dynamically. If the structure of the page is dynamic, JSP is less beneficial. Sometimes servlets are better in such a case. If the page consists of binary data or has little static content, servlets are clearly superior. Sometimes neither servlets nor JSP alone, but rather a combination of the two. (Integrating Servlets and JSP: The Model View Controller (MVC) Architecture). ThreeParams.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

12 public class ThreeParams extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Three Request Parameters"; out.println(" \n" + " " + title + " \n" + " ”+ " " + title + " \n" + " \n" + " param1 : “+ request.getParameter("param1") + " param2 : “+ request.getParameter("param2") + " param3 : “+ request.getParameter("param3") + " \n" + " "); }

13 ThreeParams.jsp Reading Three Request Parameters Reading Three Request Parameters param1 : param2 : param3 : The three parameters example of a servlet outputs the values of three designated form parameters. JSP is also producing the same result for three parameters. But the JSP version is clearly superior: shorter, simpler, and easier to maintain.

14

15 Writing Scriptlets JSP scriptlets let you insert arbitrary code into the servlet’s _jspService method (which is called by service). Scriptlets have the following form: If you want to explicitly send output to the resultant page, you could use the out variable, as in the following example. <% String queryData = request.getQueryString(); out.println("Attached GET data: " + queryData); %> you can accomplished the same effect more easily by using a combination of a scriptlet and a JSP expression, as below. Attached GET data:

16 Or, you can use a single JSP expression, as here. Attached GET data: The following snippet specifies that the current page is sent to the client as Microsoft Word, not as HTML (which is the default). Note: Remember that JSP expressions contain Java values (which do not end in semicolons), whereas most JSP scriptlets contain Java statements (which are terminated by semicolons).

17 JSP/Servlet Correspondence It is easy to understand how JSP scriptlets correspond to servlet code: the scriptlet code is just directly inserted into the _jspService method: no strings, no print statements, no changes whatsoever. Original JSP foo Representative resulting servlet code public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HttpSession session = request.getSession(); JspWriter out = response.getWriter(); out.println(" foo "); out.println(bar()); baz();... }

18 XML Syntax for Scriptlets The XML equivalent of is Java Code If you use the XML version you must use XML syntax consistently for the entire page. Remember that XML elements are case sensitive; be sure to use jsp:scriptlet in lower case.

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

20

21 Using Scriptlets to Make Parts of the JSP Page Conditional Another use of scriptlets is to conditionally output HTML or other content that is not within any JSP tag. Key to this approach are the facts that (a) code inside a scriptlet gets inserted into the resultant servlet’s _jspService method (called by service)exactly as written and (b) that any static HTML (template text) before or after a scriptlet gets converted to print statements. Example Wish for the Day

22 Have a nice day! Have a lousy day! Representative result – if (Math.random() < 0.5) { out.println(“ Have a nice day! "); } else { out.println(“ Have a lousy day! "); }

23

24 Using Declarations A JSP declaration lets you define methods or fields that get inserted into the main body of the servlet class (outside the _jspService method that is called by service to process the request). A declaration has the following form: Since declarations do not generate output, they are normally used in conjunction with JSP expressions or scriptlets. In principle, JSP declarations can contain field (instance variable) definitions, method definitions, inner class definitions, or even static initializer blocks

25 JSP/Servlet Correspondence JSP declarations result in code that is placed inside the servlet class definition but outside the _jspService method. Since fields and methods can be declared in any order, it does not matter whether the code from declarations goes at the top or bottom of the servlet. Original JSP Some Heading <%! private String randomHeading() { return(“ " + Math.random() + " "); } %>

26 Possible resulting servlet code public class xxxx 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(); JspWriter out = response.getWriter(); out.println(" Some Heading "); out.println(randomHeading());... }...

27 XML Syntax for Declarations The XML equivalent of is Field or Method definition Servers are required to support this syntax as long as authors don’t mix the XML version (... ) and the standard ASP-like version ( ) in the same page. The entire page must follow XML syntax if you are going to use the XML form Remember that XML elements are case sensitive; be sure to use jsp:declaration in lower case

28 Declaration Example JSP Declarations JSP Declarations Accesses to page since server reboot:

29 Implicit Objects (Predefined variables) JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables JSP supports nine Implicit Objects which are listed below:

30 request: This is the HttpServletRequest object associated with the request. response: This is the HttpServletResponse object associated with the response to the client. out: This is the PrintWriter object used to send output to the client. session: This is the HttpSession object associated with the request. application: This is the ServletContext object associated with application context. config:This is the ServletConfig object associated with the page. pageContext: This encapsulates use of server-specific features like higher performance JspWriters. page: This is simply a synonym for this, and is used to call the methods defined by the translated servlet class. exception: The Exception object allows the exception data to be accessed by designated JSP.

31 request This variable is the HttpServletRequest associated with the request; it gives you access to the request parameters, the request type (e.g., GET or POST), and the incoming HTTP request headers (e.g., cookies). response This variable is the HttpServletResponse associated with the response to the client. The response object also defines the interfaces that deal with creating new HTTP headers. Through this object the JSP programmer can add new cookies, HTTP status codes etc.

32 out This variable is the Writer used to send output to the client. out is object of JspWriter. The out variable is used almost exclusively in scriptlets since JSP expressions are automatically placed in the output stream session This variable is the HttpSession object associated with the request. The session object is used to track client session between client requests.

33 application This variable is the ServletContext as obtained by getServletContext. Servlets and JSP pages can store persistent data in the ServletContext object rather than in instance variables. The difference between storing data in instance variables and storing it in the ServletContext is that the ServletContext is shared by all servlets and JSP pages in the Web application, whereas instance variables are available only to the same servlet that stored the data. config This variable is the ServletConfig object for this page. In principle, you can use it to read initialization parameters, but, in practice, initialization parameters are read from jspInit, not from _jspService.

34 pageContext JSP introduced a class called PageContext to give a single point of access to many of the page attributes. The PageContext class has methods getRequest, getResponse, getOut, getSession, and so forth. The pageContext variable stores the value of the PageContext object associated with the current page. Passing pageContext is easier If a method or constructor needs access to multiple page-related objects page This variable is simply a synonym for this and it is object of Object class. This object is an actual reference to the instance of the page exception : This is an object of Throwable class. The exception object is a wrapper containing the exception thrown from the previous page. It is typically used to generate an appropriate response to the error condition.

35 Problem with implicit objects – 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? Solution: pass them as arguments. E.g. public class SomeClass { public static void someMethod(HttpSession s) { doSomethingWith(s); } …


Download ppt "INVOKING JAVA CODE WITH JSP SCRIPTING ELEMENTS. Creating Template Text A large percentage of your JSP document consists of static text (usually HTML),"

Similar presentations


Ads by Google