li tak sing comps311f. static attributes in servlets since servlets are also java classes, you can...

53
Li Tak Sing COMPS311F

Upload: emil-benson

Post on 12-Jan-2016

218 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 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

Li Tak Sing

COMPS311F

Page 2: 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

Static attributes in ServletsSince 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.

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

CountVisitThis is to count the visitor to a site, not a

page.You can try the servlet at:

http://plbpc001.ouhk.edu.hk/tma/CountVisithttp://plbpc001.ouhk.edu.hk/tma/CountVisit2

The source is at:http://plbpc001.ouhk.edu.hk/~mt311f/2010-

oct/CountVisit.javahttp://plbpc001.ouhk.edu.hk/~mt311f/2010-

oct/CountVisit2.java

Page 4: 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

CountVisit.javapublic 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(); } }

Page 5: 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

CountVisit2public 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(); } }

Page 6: 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

JSPJava Server PageJSP 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 <% and %>

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

A simple JSP<%@page contentType="text/html"

pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD

HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html> <head> <meta http-equiv="Content-Type"

content="text/html; charset=UTF-8">

Page 8: 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

A simple JSP <title>Hello world</title> </head> <body> <H2>Hello World</H2> Time is: <% out.println(new

java.util.Date().toString());%> </body></html>

Page 9: 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

The output You can try the JSP page at:

http://plbpc001.ouhk.edu.hk/tma/jsp/hello.jspThe source is at:

http://plbpc001.ouhk.edu.hk/~mt311f/2010-sep/web/webapplicaiton/web/hello.jsp

In order to view the code, you need to right click on the browser and select view soruce.

Page 10: 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

A simple JSPIn 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.

Page 11: 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

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.

outThis is a PrintWriter. Therefore, you can use println() etc

to write to the final page.session

Object getAttribute(String name). Get a named attributevoid setAttribute(String name, Object obj). Set a named

attributevoid setMaxInactiveInterval(int i). Set the maximum

inactive interval before the end of the session.

Page 12: 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

Methods of JSP variables.response

void addCookie(Cookie c). Add a cookie.

Page 13: 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

<%= %> In the last example, we use the following

code write the current time:Time is: <% out.println(new

java.util.Date().toString()); %>This can be shorten as:Time is: <%= new java.util.Date().toString()

%>

So <%= xxx %> is equilvalent to <% out.println(xxx); %>

Page 14: 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

The count exampleYou can try the JSP at:

http://plbpc001.ouhk.edu.hk/tma/jsp/count.jsp

You can download the source at:http://plbpc001.ouhk.edu.hk/~mt311f/2010-

sep/web/webapplicaiton/web/count.jsp

Page 15: 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

count.jsp<%@page contentType="text/html"

pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML

4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html> <head> <meta http-equiv="Content-Type"

content="text/html; charset=UTF-8"> <title>Count</title> </head> <body>

Page 16: 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

count.jsp <H2>Count</H2> <% String count = null; Cookie cookie[] =

request.getCookies(); if (cookie != null) { for (Cookie c : cookie) { if (c.getName().equals("count")) { count = c.getValue(); } } }

Page 17: 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

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)); %> </body></html>

Page 18: 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

expire.jspYou can try the JSP page at

http://plbpc001.ouhk.edu.hk/tma/jsp/expire.jsp

You can download the source at:http://plbpc001.ouhk.edu.hk/~mt311f/2010-

sep/web/webapplicaiton/web/expire.jsp

Page 19: 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

expire.jsp<%@page contentType="text/html"

pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML

4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><% if (request.getParameter("create") !=

null) { Cookie c = new Cookie("expire", "10"); c.setMaxAge(10); response.addCookie(c); }

Page 20: 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

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

c.getName() + ":" + c.getValue() + "<br>"); if (c.getName().equals("expire")) { fontsize = 10; } } }%>

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

expire.jsp<html> <head> <meta http-equiv="Content-Type"

content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <font size='<%=fontsize%>'> The font size is <%=fontsize%>. </font>

Page 22: 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

expire.jsp <form> <input type='submit' name='create'

value='create a cookie'/> </form> Click <a href='expire.jsp'>this</a> to

revisit this page

</body></html>

Page 23: 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

SessionCountYou can try this at

http://plbpc001.ouhk.edu.hk/tma/jsp/sessioncount.jsp

The source can be downloaded at:http://plbpc001.ouhk.edu.hk/~mt311f/2010-

sep/web/webapplicaiton/web/sessioncount.jsp

Page 24: 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

sessioncount.jsp<%@page contentType="text/html"

pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML

4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html> <head> <meta http-equiv="Content-Type"

content="text/html; charset=UTF-8"> <title>Session Count</title> </head>

Page 25: 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

sessioncount.jsp <body>

<h1>Session Count</h1>

<% 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);%>

</body>

</html>

Page 26: 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

sessionexpireYou can try this at

http://plbpc001.ouhk.edu.hk/tma/jsp/sessionexpire.jsp

The source can be downloaded at:http://plbpc001.ouhk.edu.hk/~mt311f/2010-

sep/web/webapplicaiton/web/sessionexpire.jsp

Page 27: 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

sessionexpire.jsp<%@page contentType="text/html"

pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01

Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><% if (request.getParameter("create") != null)

{ session = request.getSession(); session.setMaxInactiveInterval(10); } else { session = request.getSession(false); }%>

Page 28: 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

sessionexpire.jsp<html> <head> <meta http-equiv="Content-Type"

content="text/html; charset=UTF-8"> <title>SessionExpire</title> </head> <body> <h1>SessionExpire</h1>

Page 29: 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

sessionexpire.jsp <% int fontsize = 3; if (session != null) { fontsize = 10; }%> <font size='<%=fontsize%>'> The font size is <%=fontsize%>. </font> <form> <input type='submit' name='create'

value='create a session'/> </form> Click <a href='sessionexpire.jsp'>this</a>

to revisit this page

Page 30: 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

sessionexpire.jsp

</body></html>

Page 31: 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

JSP directivesDirectives 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.

<%@ directive-name attribute-name1 = “value1” attribute-name2 = “value2” ... %>

Page 32: 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

The page directiveThe page direction is used to specify

properties of the JSP page.import:

<%@ page import="java.util.*, java.text.*" %>

contentType:<%@ page contentType="text/html; charset=Big5" %>

The session attribute is used to enable or disable the use of the predefined session variable. The default value is true.<%@ page session="false" %>

Page 33: 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

The page directiveThe 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.<%@ page isThreadSafe="false" %>

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.<%@ include file="/abc.html" %>

Page 34: 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

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:<%! private long factorial(int n) {

if (n==0)return 1;

elsereturn n*factorial(n-1);

}%>

Page 35: 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

JSP declarations <%! ... %>Then, code in the same JSP page can now

use this method.

Page 36: 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

A JSP that calculate the factorialYou can try the page at

http://plbpc001.ouhk.edu.hk/tma/jsp/factorial.jsp

The source can be downloaded at:http://plbpc001.ouhk.edu.hk/~mt311f/2010-

sep/web/webapplicaiton/web/factorial.jsp

Page 37: 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

factorial.jsp<%@page contentType="text/html"

pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML

4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%! private int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } }%>

Page 38: 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

factorial.jsp<html> <head> <meta http-equiv="Content-Type"

content="text/html; charset=UTF-8"> <title>Factorial</title> </head> <body> <h1>Factorial</h1>

Page 39: 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

factorial.jsp <% String nva = request.getParameter("n"); int n = 0; if (nva != null) { n =

factorial(Integer.parseInt(nva.trim())); %> The factorial of <%=nva%> is <%=n%>.<br> <% } %>

Page 40: 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

factorial.jsp <form> <input type="text" name="n"

size="10"> <input type="submit"

name="submit" value="submit"> </form> </body></html>

Page 41: 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

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://127.0.0.1/jdatabase", "user", "password");

} catch (Exception e) { e.printStackTrace(); } return null; }%>

Page 42: 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

JavabeansJSP 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.

Page 43: 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

JavaBeansA JavaBean must have a constructor with

no parameters. To use a JavaBean, you will need to place a <jsp:useBean> tag in a JSP page.

There are two ways to use a JavaBean:<jsp:useBean id = "count" scope =

"application" class = "chapter40.Count"> </jsp:useBean>

<jsp:useBean id="count" scope="application" class="chapter40.Count" />

Page 44: 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

Invoking the methods of a JavaBean<% count.increaseCount(); %>

Page 45: 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

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; }}

Page 46: 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

A JSP page that uses javabean.CountVisitYou can try the page at

http://plbpc001.ouhk.edu.hk/tma/jsp/javabeanCount.jsp

The source can be downloaded at:http://plbpc001.ouhk.edu.hk/~mt311f/2010-

sep/web/webapplicaiton/web/javabeanCount.jsp

Page 47: 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

javabeanCount.jsp<%@page contentType="text/html"

pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01

Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><jsp:useBean id="count" scope="application"

class="javabean.CountVisit"/><html> <head> <meta http-equiv="Content-Type"

content="text/html; charset=UTF-8"> <title>Using Javabean to count</title> </head>

Page 48: 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

javabeanCount.jsp<body> <h1>Using Javabean to count</h1> This page has been visied <

%=count.count()%> times. <% count.addCount(); %> </body></html>

Page 49: 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

Scopes of JavaBeansTwo 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.

Page 50: 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

Scopes of JavaBeansWhen 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.

Page 51: 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

Comparision of session, JSP declarations and JavaBeanValues 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.

Page 52: 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

Comparision of session, JSP declarations and JavaBeanWhen 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.

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

javabeanCount2This 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

http://plbpc001.ouhk.edu.hk/tma/jsp/javabeanCount2.jsp