Li Tak Sing COMPS311F. A web page that counts the number of times that you have visited the page. You can try the page at:

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
Advertisements

7 Copyright © 2005, Oracle. All rights reserved. Maintaining State in J2EE Applications.
JSP and Servelets.
CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
Cookie in a servlet. Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Java Server Pages (JSP)
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
An introduction to Java Servlet Programming
18-Jun-15 JSP Java Server Pages Reference: Tutorial/Servlet-Tutorial-JSP.html.
JSP Java Server Pages Reference:
2/16/2004 Dynamic Content February 16, /16/2004 Assignments Due – Message of the Day Part 1 Due – Reading and Warmup Work on Message of the Day.
JSP Architecture  JSP is a simple text file consisting of HTML or XML content along with JSP elements  JSP packages define the interface for the compiled.
Chapter 4 Servlets Concept of Servlets (What, Why, and How) Servlet API Third-party tools to run servlets Examples of Using Servlets HTML tag with GET.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external.
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
Comp2513 Java Servlets and Sessions Daniel L. Silver, Ph.D.
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
Java Servlets and Java Server Pages Carol Wolf Computer Science.
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
Li Tak Sing COMPS311F. Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can.
Chapter 7 Java Server Pages. Objectives Explain how the separation of concerns principle applies to JSP Describe the operation and life-cycle of a JSP.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
JAVA SERVER PAGES CREATING DYNAMIC WEB PAGES USING JAVA James Faeldon CS 119 Enterprise Systems Programming.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
Session tracking There are a number of problems that arise from the fact that HTTP is a "stateless" protocol. In particular, when you are doing on- line.
16-Oct-15 JSP Implicit Objects. 2 JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer.
Web Application Development * These slides have been adapted and modified from CoreServlets course material (Marty Hall) and LUMS cs391 (Umair Javed).
Java Servlets & Java Server Pages Lecture July 2013.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Session Management.
JSP Fundamentals Elements of a JSP Using Beans with JSP Integrating Servlets and JSP.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 27 JavaServer Page.
Chapter 2 Web app architecture. High-level web app architecture  When a client request coming in and needs servlet to serve dynamic web content, what.
Saving Client State Session Tracking: Maintain state about series of requests from same client over time Using Cookies: Clients hold small amount of their.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
S ERVLETS Cookies Handling 5-Dec-15. S ERVLETS - C OOKIES H ANDLING Cookies are text files stored on the client computer and they are kept for various.
Li Tak Sing COMPS311F. A web page that counts the number of times that you have visited the page. You can try the page at:
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
Introduction to Servlets. Introduction Servlet is a language to develop the server side applications, and it is also server side component. It can develop.
Vakgroep Informatietechnologie – Onderzoeksgroep (naam) Web Centric Design of Distributed Software.
©SoftMooreSlide 1 Session Tracking with Servlets.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
CSC 2720 Building Web Applications Managing Users' States – Cookies, URL-Rewriting, Hidden Fields and Session Management APIs.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 43 JavaServer Page.
©SoftMoore ConsultingSlide 1 Overview of Servlets and JavaServer Pages (JSP)
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
1 Chapter 27 JavaServer Page. 2 Objectives F To know what is a JSP page is processed (§27.2). F To comprehend how a JSP page is processed (§27.3). F To.
Session Tracking Parts of this presentation was provided by SSE.
Introduction To HTML Dr. Magdi AMER. HTML elements.
ClaRA web services V. Gyurjyan Clas12 Software Meeting
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
8-Mar-16 More About Servlets Session Tracking. Persistent information A server site typically needs to maintain two kinds of persistent (remembered) information:
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
Developing JavaServer Pages
Java Servlets By: Tejashri Udavant..
Java Servlets.
Sessions.
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Cookies Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when later visiting the.
Introduction to Java Servlets
Pre-assessment Questions
Servlet Session Tracking: Session API
Presentation transcript:

Li Tak Sing COMPS311F

A web page that counts the number of times that you have visited the page. You can try the page at: You can get the source at:

Count public class Count extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String count = null; Cookie cookie[] = request.getCookies(); if (cookie != null) { for (Cookie c : cookie) { if (c.getName().equals("count")) { count = c.getValue(); }

Count if (count == null) { out.println("You are new here."); count = "1"; } else { out.println("You have visited this site for " + count + " times."); count = Integer.toString(Integer.parseInt(count) + 1); } response.addCookie(new Cookie("count", count)); } finally { out.close(); }

A page that allows that users to select the size of the fonts. You can try the page at: You can get the source at:

FontSize public class FontSize extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String size = null; if (request.getParameter("size") != null) { size = request.getParameter("size"); response.addCookie(new Cookie("size", size)); }

FontSize if (size == null) { Cookie cookie[] = request.getCookies(); if (cookie != null) { for (Cookie c : cookie) { if (c.getName().equals("size")) { size = c.getValue(); } if (size==null) { size="3"; }

FontSize out.println(" "); out.println("Font size: "); out.println(" 3 "); out.println(" 4 "); out.println(" 5 "); out.println(" "); out.println(" This text is just used to test the servlet. "); out.println(" Click this to reload the page "); out.println(" "); } finally { out.close(); }

Other useful methods of Cookie public void setDomain(String pattern) Specifies the domain within which this cookie should be presented. By default, cookies are only returned to the server that sent them. This is the reason why cookie is dangerous. For example, when you visit site A and accept a cookie. Then when you visit site B and sent that cookie to site B. In this way, site B would know that you have visited site A. If that happens to many sites, then site B will now have your profile of internet surfing. Public String getDomain() Returns the domain name set for this cookie.

Other useful methods of Cookie public void setPath(String pattern) Sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories. This method can be used to specify something more general. For example, someCookie.setPath("/") specifies that all pages on the server should receive the cookie. Note that the path specified must include the current directory. Public String getPath() Get the path to which this cookie applies.

Other useful methods of Cookie public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds. A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value is the maximum age when the cookie will expire, not the cookie's current age. A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted. If you don't set this, the cookie will last only for the current session (i.e. until the user quits the browser), and will not be stored on disk.public int getMaxAge() Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.

A cookie that expires in 10 seconds You can try the page at: You can get the source at:

A cookie that expires in 10 seconds public class Expire extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { if (request.getParameter("create") != null) { Cookie c = new Cookie("expire", "10"); c.setMaxAge(10); response.addCookie(c); } Cookie cookie[] = request.getCookies();

A cookie that expires in 10 seconds int fontsize = 3; if (cookie != null) { for (Cookie c : cookie) { if (c.getName().equals("expire")) { fontsize=10; }

A cookie that expires in 10 seconds out.println(" "); out.println("The font size is "+fontsize+"."); out.println(" "); out.println("Click this to revisit this page"); } finally { out.close(); }

Attributes of servlets As a servlet would only be instantiated once in a Web server, all requests to the servlet would use the same copy of the servlet. Therefore, we can define attributes for the servlet if we want them to be shared amoung all users of the servlet.

Differences between attributes of a servlet and cookies An attribute of a servlet is shared by all users of the servlet. A cookie is used by only one user. So if you want to have something to be shared by all users, then use an attribute to store it. If you only want it to be used by a user, then use a cookie to store it. When you use an attribute to store a value, make the access to the value thread safe as that value may be accessed by multiple threads at the same time.

An example of a fixed size buffer You can try the page at: You can get the source at:

Buffer The code for the buffer: private int data[] = new int[3]; private int no = 0; private synchronized int get() { while (no == 0) { try { wait(); } catch (Exception e) { } notifyAll(); return data[--no]; }

Buffer private synchronized void put(int num) { while (no == data.length) { try { wait(); } catch (Exception e) { } data[no++] = num; notifyAll(); }

Buffer protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { if (request.getParameter("get") != null) { int i = this.get(); out.println("The integer got from the buffer:" + i + " "); } else if (request.getParameter("input") != null) { int i = Integer.parseInt(request.getParameter("input").trim()); this.put(i); }

Buffer out.println("Number in the buffer:"); for (int i = 0; i < no; i++) { out.print(data[i] + " "); } out.println(); out.println(" "); out.println("put an integer to the buffer:"); out.println(" "); out.println("<input type='submit' name='submit' value='put'"); out.println(" ");

Buffer out.println("get an integer from the buffer"); out.println("<input type='submit' name='get' value='get'"); out.println(" "); } finally { out.close(); }

HttpSection We have seen how to use cookies to keep session information. There is another way to handle session information in servlets, which is using HttpSection. HttpSection is an interface, not a class. Therefore you cannot create an HttpSection directly. This is created by a method of HttpServletRequest like this: HttpSection sect=req.getSession(true).

getSession() There are two getSession() method of HttpServletRequest : HttpSection getSession() This method will always create a session if the request object doesn’t return one. HttpSection getSession(boolean create) The create parameter specifies whether a session should be created if the request object doesn’t return one. One import thing: you should get the session object before any response works. Actually, it is better that you get the session at the before of any doGet or doPost methods.

Looking up information associated with a session HttpSession objects live on the server; they're just automatically associated with the requester by a behind-the- scenes mechanism like cookies or URL-rewriting. You can use getAttribute("key") to look up a previously stored value.

Some examples of using HttpSession HttpSession session = request.getSession(true); ShoppingCart previousItems = (ShoppingCart)session.getAttribute("prev iousItems"); if (previousItems != null) { doSomethingWith(previousItems); } else { previousItems = new ShoppingCart(...); doSomethingElseWith(previousItems); }

Associating Information with a Session To access a named value, use getAttribute: public object getAttribute(String name) Returns the object bound with the specified name in this session, or null if no object is bound under the name. To set a named value, use setAttribute: public void setAttribute(String name, Object value) Binds an object to this session, using the name specified. If an object of the same name is already bound to the session, the object is replaced. After this method executes, and if the object implements HttpSessionBindingListener, the container calls HttpSessionBindingListener.valueBound.

Comparison of using cookies and HttpSession When using cookies, we can only deal with Strings. With HttpSession, we can store any types of objects. Cookies are always stored in client sides and have to be passed over the internet to the server. For HttpSession, the data is stored in the server side and there is no need to go through the unsafe network. So HttpSession is much better than using cookies.

Redo Count with HttpSession You can try the page at: You can get the source at:

Redo Count with HttpSession public class SessionCount extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { Integer count =(Integer)session.getAttribute("count");

Redo Count with HttpSession if (count == null) { out.println("You are new here."); count = 1; } else { out.println("You have visited this site for " + count + " times."); count++; } session.setAttribute("count", count); } finally { out.close(); }

The page that changes font size You can try the page at: You can get the source at:

The page that changes font size public class SessionFontSize extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { Integer size = null; if (request.getParameter("size") != null) { size = Integer.parseInt(request.getParameter("size")); session.setAttribute("size", size); }

The page that changes font size if (size == null) { Cookie cookie[] = request.getCookies(); size=(Integer)session.getAttribute("size"); } if (size==null) { size=3; } out.println(" "); out.println("Font size: "); out.println(" 3 "); out.println(" 4 "); out.println(" 5 "); out.println(" ");

The page that changes font size out.println(" "); out.println(" This text is just used to test the servlet. "); out.println(" Click this to reload the page "); out.println(" "); } finally { out.close(); }

Other useful methods of HttpSession public void setMaxInactiveInterval(int interval) Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. A negative time indicates the session should never timeout. publit int getMaxInactiveInterval() Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. After this interval, the servlet container will invalidate the session. The maximum time interval can be set with the setMaxInactiveInterval method. A negative time indicates the session should never timeout.

A session that expires after 10 seconds of being inactive You can try the page at: You can get the source at:

ExpireSession public class SessionExpire extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session; if (request.getParameter("create")!=null) { session=request.getSession(); session.setMaxInactiveInterval(10); } else { session=request.getSession(false); }

ExpireSession response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { int fontsize = 3; if (session!=null) { fontsize=10; }

ExpireSession out.println(" "); out.println("The font size is "+fontsize+"."); out.println(" "); out.println("Click this to revisit this page"); } finally { out.close(); }

JSP Java Server Page JSP is an alternative way to handle HTTP requests. Contrary to Java Servlets, the basic structure of a JSP is an HTML file. Java code is embedded in the HTML code specified by

A simple JSP <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "

A simple JSP Hello world Hello World Time is:

The output You can try the JSP page at: The source is at: sep/web/webapplicaiton/web/hello.jsp In order to view the code, you need to right click on the browser and select view soruce.

A simple JSP In the JSP page, Java code should be placed between. Every JSP page has several predefined variables: request. This variable specifies the data included in an http request. This variable takes value from the clients' browser to pass it over to the server. response. This variable specifies the data included in the http response. It is used with cookies and also in http headers. out. This variable specifies the output stream otherwise known as printwriter in a page context. session. This variable specifies the data associated with httpsession object with a specific session of a user. The main purpose of this object is to use the session information to maintain multiple page requests.

Methods of JSP variables. request Cookie[] getCookies(): get all the cookies for this request. String getParameter(String name): get the value of the named parameter. out This is a PrintWriter. Therefore, you can use println() etc to write to the final page. session Object getAttribute(String name). Get a named attribute void setAttribute(String name, Object obj). Set a named attribute void setMaxInactiveInterval(int i). Set the maximum inactive interval before the end of the session.

Methods of JSP variables. response void addCookie(Cookie c). Add a cookie.

In the last example, we use the following code write the current time: Time is: This can be shorten as: Time is: So is equilvalent to

The count example

Static attributes in Servlets Since Servlets are also Java classes, you can also use static attributes to store values that can be shared by all servlets. For example, if you want a single database connect to be used by all servlets, you can use a static attribute to store the connection and it would be accessible by all servlets. On the other hand, a normal attribute in a servlet can only be used by the servlet only.

CountVisit This is to count the visitor to a site, not a page. You can try the servlet at: The source is at: oct/CountVisit.java oct/CountVisit2.java

CountVisit.java public class CountVisit extends HttpServlet { public static int count=0; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { PrintWriter out=response.getWriter(); out.println("You have visit this site for "+count+" times."); count++; } catch (Exception e) { e.printStackTrace(); }

CountVisit2 public class CountVisit2 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { PrintWriter out=response.getWriter(); out.println("You have visit this site for "+CountVisit.count+" times."); CountVisit.count++; } catch (Exception e) { e.printStackTrace(); }

JSP Java Server Page JSP is an alternative way to handle HTTP requests. Contrary to Java Servlets, the basic structure of a JSP is an HTML file. Java code is embedded in the HTML code specified by

A simple JSP <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "

A simple JSP Hello world Hello World Time is:

The output You can try the JSP page at: The source is at: sep/web/webapplicaiton/web/hello.jsp In order to view the code, you need to right click on the browser and select view soruce.

A simple JSP In the JSP page, Java code should be placed between. Every JSP page has several predefined variables: request. This variable specifies the data included in an http request. This variable takes value from the clients' browser to pass it over to the server. response. This variable specifies the data included in the http response. It is used with cookies and also in http headers. out. This variable specifies the output stream otherwise known as printwriter in a page context. session. This variable specifies the data associated with httpsession object with a specific session of a user. The main purpose of this object is to use the session information to maintain multiple page requests.

Methods of JSP variables. request Cookie[] getCookies(): get all the cookies for this request. String getParameter(String name): get the value of the named parameter. out This is a PrintWriter. Therefore, you can use println() etc to write to the final page. session Object getAttribute(String name). Get a named attribute void setAttribute(String name, Object obj). Set a named attribute void setMaxInactiveInterval(int i). Set the maximum inactive interval before the end of the session.

Methods of JSP variables. response void addCookie(Cookie c). Add a cookie.

In the last example, we use the following code write the current time: Time is: This can be shorten as: Time is: So is equilvalent to

The count example You can try the JSP at: You can download the source at: sep/web/webapplicaiton/web/count.jsp sep/web/webapplicaiton/web/count.jsp

count.jsp <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" " Count

count.jsp Count <% String count = null; Cookie cookie[] = request.getCookies(); if (cookie != null) { for (Cookie c : cookie) { if (c.getName().equals("count")) { count = c.getValue(); }

count.jsp if (count == null) { out.println("You are new here."); count = "1"; } else { out.println("You have visited this site for " + count + " times."); count = Integer.toString(Integer.parseInt(count) + 1); } response.addCookie(new Cookie("count", count)); %>

expire.jsp You can try the JSP page at You can download the source at: sep/web/webapplicaiton/web/expire.jsp sep/web/webapplicaiton/web/expire.jsp

expire.jsp <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" " <% if (request.getParameter("create") != null) { Cookie c = new Cookie("expire", "10"); c.setMaxAge(10); response.addCookie(c); }

expire.jsp Cookie cookie[] = request.getCookies(); int fontsize = 3; if (cookie != null) { for (Cookie c : cookie) { System.out.println("cookie:" + c.getName() + ":" + c.getValue() + " "); if (c.getName().equals("expire")) { fontsize = 10; } }%>

expire.jsp JSP Page '> The font size is.

expire.jsp Click this to revisit this page

SessionCount You can try this at The source can be downloaded at: sep/web/webapplicaiton/web/sessioncount.jsp sep/web/webapplicaiton/web/sessioncount.jsp

sessioncount.jsp <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" " Session Count

sessioncount.jsp Session Count <% Integer count = (Integer) session.getAttribute("count"); if (count == null) { out.println("You are new here."); count = 1; } else { out.println("You have visited this site for " + count + " times."); count++; } session.setAttribute("count", count);%>

sessionexpire You can try this at The source can be downloaded at: sep/web/webapplicaiton/web/sessionexpire.jsp sep/web/webapplicaiton/web/sessionexpire.jsp

sessionexpire.jsp <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" " <% if (request.getParameter("create") != null) { session = request.getSession(); session.setMaxInactiveInterval(10); } else { session = request.getSession(false); } %>

sessionexpire.jsp SessionExpire SessionExpire

sessionexpire.jsp <% int fontsize = 3; if (session != null) { fontsize = 10; }%> '> The font size is. Click this to revisit this page

sessionexpire.jsp

JSP directives Directives are used to pass high-level information to the server about how a specific page should be translated. The general format of a JSP directive looks like the following where one or more attribute values may be specified.

The page directive The page direction is used to specify properties of the JSP page. import: contentType: The session attribute is used to enable or disable the use of the predefined session variable. The default value is true.

The page directive The isThreadSafe attribute indicates that the page is thread-safe. The default is true. If this value is false, then requests for the JSP page will be handled serially. Note that if this value is true, then the programmer is responsible to sychronize access to shared variables. The include directive enables the contents of a separate resource to be merged into the current JSP page at the place of the directive appears.

JSP declarations This is to decare variables and methods for use in the same JSP. For example, the following declare a method that calculate the factorial of an integer:

JSP declarations Then, code in the same JSP page can now use this method.

A JSP that calculate the factorial You can try the page at The source can be downloaded at: sep/web/webapplicaiton/web/factorial.jsp sep/web/webapplicaiton/web/factorial.jsp

factorial.jsp <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" " <%! private int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } }%>

factorial.jsp Factorial Factorial

factorial.jsp <% String nva = request.getParameter("n"); int n = 0; if (nva != null) { n = factorial(Integer.parseInt(nva.trim())); %> The factorial of is. <% } %>

factorial.jsp

Database connection for a JSP If you want to have one database connection for all request to a page, the connection should be created as a JSP declaration. <%! private java.sql.Connection con = con(); private java.sql.Connection con() { java.sql.Connection re = null; try { Class.forName("com.mysql.jdbc.Driver"); re = java.sql.DriverManager.getConnection("jdbc:mysql:// /jdatabase", "user", "password"); } catch (Exception e) { e.printStackTrace(); } return null; } %>

Javabeans JSP declarations can be used to instantiate objects shared by requests for the same JSP page. But there are times that different JSP pages may want to share objects. JavaBeans are software components that support more flexible sharing. To facilitate sharing, JavaBeans must be coded according to certain specific coding convention.

JavaBeans A JavaBean must have a constructor with no parameters. To use a JavaBean, you will need to place a tag in a JSP page. There are two ways to use a JavaBean:

Invoking the methods of a JavaBean

JavaBean Lets create a JavaBean called javabean.CountVisit. Note that a JavaBean has to be in a package. package javabean; public class CountVisit { public int count=0; synchronized public void addCount() { count++; } synchronized public int count() { return count; }

A JSP page that uses javabean.CountVisit You can try the page at The source can be downloaded at: sep/web/webapplicaiton/web/javabeanCount.jsp sep/web/webapplicaiton/web/javabeanCount.jsp

javabeanCount.jsp <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" " Using Javabean to count

javabeanCount.jsp Using Javabean to count This page has been visied times.

Scopes of JavaBeans Two distinct instantiations can co-exist independently with the same bean as long as they have different scopes. The legitimate scopes from high to low are application, session, page and request. When the scope is application, different end-users will share the same instantiation of the bean. Once created, the bean continues to live until the Web server restarts. When the scope is session, each end-user will have his or her own bean. A user does not share the bean with another user. A session bean will live until the session expires based on the value of MaxInactiveInterval or after session.invalidate( ) is called whichever happens first.

Scopes of JavaBeans When the scope is page, no two JSP pages can share the same instantiation of a bean. The difference between the page and request scopes is very subtle and does not concern us in this course.

Comparision of session, JSP declarations and JavaBean Values in a session are accessible by one user only and can be used in different JSP pages. Values stores in JSP declarations are accessible by all users but is limited to a single page. When a Javabean's scope is page or request, it is like JSP declaration. It is shared by all users but is limited to a single JSP page. When a Javabean's scope is session, it is like a session value and is shared by a single user and can be used in different JSP pages.

Comparision of session, JSP declarations and JavaBean When a Javabean's scope is application, it is shared by all users and can be used in different JSP pages. It is like static attributes in servlet.

javabeanCount2 This is exactly the same as javabeanCount. The two pages share the same JavaBean called count. So the two pages have the same counter. You can try the page at