Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

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

2 Interacting with other Resources

3 JSP Cooperation We will consider several ways in which JSP and other resources cooperate -Forwarding the request handling to other resources -Including the content of other sources -Including the code of other JSP files -Forwarding exception handling to other JSPs

4 Actions JSP actions use constructs in XML syntax to control the behavior of the Servlet engine Using actions, you can -forward the request to another resource in the application -dynamically include a resource content in the response

5 The forward Action jsp:forward - Forwards the requester to a new resource }"> <jsp:param name="parameterName" value="{parameterValue | }" /> * This action is translated to an invocation of the RequestDispatcher

6 The include Action jsp:include - Include a resource content at run time }"> <jsp:param name="parameterName" value="{parameterValue | }" /> * This action is also translated to an invocation of the RequestDispatcher

7 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 In Tomcat 5.x, generated Servlet is updated when included files change (unlike old versions...)

8 Include - Action File1.jsp Servlet1 File2.jsp Servlet2 HTML content HTML content HTML content

9 Include Directive File1.jsp File2.jsp Servlet HTML content

10 include Action vs. Directive When a resource is included using the include action, the generated Servlet uses the dispatcher to include its content at runtime When a file is included using the include directive, the file itself is included verbatim into the JSP code, prior to the Servlet generation Question: in which of the above options can the included element change the HTTP headers or status?

11 Including JSP Here is an interesting page. Bla, Bla, Bla, Bla. BlaBla.jsp Accesses to page since Servlet init: Page Created for Dbi Course at. Email us here. AccessCount.jsp dbimail.jsp

12 out.write(" \r\n"); out.write(" Including JSP \r\n"); out.write(" \r\n"); out.write(" Here is an interesting page. \r\n"); out.write(" Bla, Bla, Bla, Bla. \r\n"); out.write(" \r\n"); out.write(" Accesses to page since Servlet init: \r\n"); out.print( ++accessCount ); out.write(" \r\n"); org.apache.jasper.runtime.JspRuntimeLibrary. include(request, response, "/dbimail.jsp", out, false); out.write(" \r\n"); BlaBla_jsp.java

13 Included Counter Suppose that the file BlaBla2.jsp is similar the BlaBla.jsp How will the counter of BlaBla2.jsp act? What if we used a JSP action instead of a JSP directive for the counter?

14 Error Pages We can set one JSP page to be the handler of uncaught exceptions of another JSP page, using JSP directives -Defines a JSP page that handles uncaught exceptions -The page in url must have true in the page-directive: -The variable exception holds the exception thrown by the calling JSP

15 Reading From Database <% Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con = DriverManager.getConnection ("jdbc:oracle:thin:" + "snoopy/snoopy@sol4:1521:stud"); %> Connection Established!! connect.jsp

16 Connection Error Oops. There was an error when you accessed the database. Here is the stack trace: errorPage.jsp

17

18

19 Custom JSP Tags

20 JSP code may use custom tags - tags that are defined and implemented by the programmer The programmer defines how each of the custom tags is translated into Java code There are two methods to define custom tags: -Tag libraries - used in old versions of JSP -Tag files - much simpler, introduced in JSP 2.0

21 Tag Libraries A tag library consists of: -Tag handlers - Java classes that define how each of the new tags is translated into Java code -A TLD (Tag Library Descriptor) file, which is an XML file that defines the structure and the implementing class of each tag

22 package dbi; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; public class DateTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { getJspContext().getOut().print(new java.util.Date()); } DateTag.java A Simple TagLib Example

23 1.0 2.0 date dbi.DateTag empty dbi-taglib.tld Hello. The time is: taglibuse.jsp

24 Tag Files JSP 2.0 provides an extremely simplified way of defining tags The idea: for each custom tag, write a tag file tagName.tag that implements the tag translation using JSP code This way, the programmer can avoid creating tag handlers and TLD files

25 The Simplified Example Hello. The time is: date.tag taguse.jsp

26 Other Capabilities of Custom Tags Attributes -You can define the possible attributes of the Tags -These can be accessed during the Tag translation Tag Body -Tag translation may choose to ignore, include or change the tag body

27 Java Beans in JSP

28 Motivation Software components (e.g. objects, data structures, primitives) are extensively used in Web applications For example: -Service local variables -Attributes forwarded in requests -Session attributes, like users information -Application attributes, like access counters

29 Motivation Standard actions are used to manipulate components: declaration, reading from the suitable context, setting of new values (according to input parameters), storing inside the suitable context, etc. Java Beans provide a specification for automatic handling and manipulation of software components in JSP (and other technologies...)

30 Java Beans: The Idea Java Beans are simply objects of classes that follow some (natural) coding convention: -An empty constructor -A readable property has a matching getter -A writable property has a matching setter Use JSP actions to access and manipulate the bean, and special action attributes to specify the properties of the bean, like its scope

31 Example 1: Access Counter In the following example, we use a Bean to maintain an access counter for requests to the pages

32 package dbi; public class CounterBean { private int counter; public CounterBean() { counter = 0; } public int getCounter() { return counter; } public void setCounter(int i) { counter = i; } public void increment() { ++counter; } } Bean must reside in a package Bean is created by an empty constructor counter is readable and writable other methods can be used Counter Bean CounterBean.java

33 Bean Example <jsp:useBean id="accessCounter" class="dbi.CounterBean" scope="application"/> Welcome to Page A Accesses to this application: Page B invokes getCounter() pageA.jsp

34 Bean Example <jsp:useBean id="accessCounter" class="dbi.CounterBean" scope="application"/> Welcome to Page B Accesses to this application: Page A pageB.jsp

35 dbi.CounterBean accessCounter = null; synchronized (application) { accessCounter = (dbi.CounterBean) _jspx_page_context.getAttribute("accessCounter", PageContext.APPLICATION_SCOPE); if (accessCounter == null) { accessCounter = new dbi.CounterBean(); _jspx_page_context.setAttribute("accessCounter", accessCounter, PageContext.APPLICATION_SCOPE); } From the Generated Servlet

36 Example 2: Session Data In the following example, we use a Bean in order to keep a user's details throughout the session

37 package dbi; public class UserInfoBean { private String firstName; private String lastName; public UserInfoBean() { firstName = lastName = null;} public String getFirstName() {return firstName;} public String getLastName() {return lastName;} public void setFirstName(String string) {firstName = string;} public void setLastName(String string) {lastName = string;} } UserInfoBean.java

38 Information Form Fill in your details: Your First Name: Your Last Name: infoForm.html

39 Page A Hello, Have a nice session! User Info B Match parameters to corresponding properties infoA.jsp

40 Page B Hello, Have a nice session! User Info A infoB.jsp

41 Advantages of Java Beans Easy and standard management of data -Automatic management of bean sharing and lots more Good programming style -Allow standard but not direct access to members -You can add code to the setters and getters (e.g. constraint checks) without changing the client code -You can change the internal representation of the data without changing the client code Increase of separation between business logic (written by programmers) and HTML (written by GUI artists)

42 JSP Expression Language

43 JSP expression language is a comfortable tool to access useful objects in JSP This language provides shortcuts in JavaScript- like syntax An expression in EL is written as ${expr} For example: Hi, ${user}. Welcome

44 EL Variables JSP EL does not recognize JSP's implicit objects, but rather has its own set: param, paramValues, header,headerValues, cookie, initParam, pageScope, requestScope, sessionScope, applicationScope Each of these objects maps names to values For example, use param["x"] or param.x to get the value of the parameter x

45 EL Variables (cont) A variable that is not an EL implicit object is looked up at the page, request, session (if valid) and application scopes That is, x is evaluated as the first non null element obtained by executing pageContext.getAttribute("x"), request.getAttribute("x"), etc.

46 Object Properties In JSP EL, Property p of Object o is referred to as o[p] Property p of Object o is evaluated as follows: -If o is a Map object, then o.get(p) is returned -If o is a List or an array, then p is converted into an integer and o.get(p) or o[p] is returned -Otherwise, treat o as a bean, convert p to a string, and return apply the corresponding getter of o The term o.p is equivalent to o["p"]

47 An Example <% response.addCookie(new Cookie("course","dbi")); session.setAttribute("dbiurl",new java.net.URL("http://www.cs.huji.ac.il/~dbi/index.html")); String[] strs = {"str1","str2"}; session.setAttribute("arr", strs); %> JSP Expressions Write the parameter x: elcall.jsp

48 EL Examples Expression-Language Examples Parameter x : ${param["x"]} Cookie course : ${cookie.course.value} Header Connection : ${header.Connection} Path of session attr. dbiurl : ${sessionScope.dbiurl.path} Element arr[${param.x}] : ${arr[param.x]} el.jsp


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

Similar presentations


Ads by Google