410 likes | 522 Views
MIS 3150 Module 3 3-Tier Webapps using JSP/JDBC. Arijit Sengupta. Structure of this semester. MIS415. 1. Design. 2. Querying. 4. Advanced Topics. 0. Intro. 3. Applications. Database Fundamentals. Conceptual Modeling. Query Languages. Java DB Applications – JDBC/JSP. XML
E N D
MIS 3150 Module 33-Tier Webapps using JSP/JDBC Arijit Sengupta
Structure of this semester MIS415 1. Design 2. Querying 4. Advanced Topics 0. Intro 3. Applications Database Fundamentals Conceptual Modeling Query Languages Java DB Applications – JDBC/JSP XML Databases Relational Model Advanced SQL Data Mining Normalization Newbie Users Designers Developers Professionals
Today’s Buzzwords • 3-Tier applications • Client – WebServer – ApplicationServer • Basics of JDBC • Basics of JSP Containers - Tomcat • Web Applications using JSP
3 Tier Architecture URL JSP page request HTTP request JavaBean Library JSP container compiles to a servlet properties, call methods response HTTP response DB HTTP page Browser Web server
JDBC • A platform-independent library of classes allowing database access from any Java application • Take advantages of Polymorphism • JDBC is a set of interfaces • Driver, Connection, Statement, ResultSet, etc. • Database vendors (not programmers) will implement these interfaces. • If we switch from one database to another, we just need to load different driver (plug and play)! • YOU DON'T NEED TO MODIFY THE REST OF YOUR PROGRAM!
DriverManager Connection Statement ResultSet Driver Database JDBC
JDBC DriverManager Connection Statement ResultSet Driver Database
JDBC (Contd.) • Register a JDBC driver Driver d = new oracle.jdbc.driver.OracleDriver(); DriverManager.registerDriver (d); • or DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver()); • Or, use the Java reflection abilities Class.forName( "oracle.jdbc.driver.OracleDriver"); • calling Class.forName() will create an instance of a driver and register it with the DriverManager automatically • This is better since we can use a constant: String DRIVER = "oracle.jdbc.driver.OracleDriver"; Class.forName(DRIVER); • For mysql, use: com.mysql.jdbc.driver
JDBC DriverManager Connection Statement ResultSet Driver Database
JDBC (Contd.) • Make a connection String URL = "jdbc:oracle:thin:@unixapps1.wright.edu:1521:ORA2"; // For Oracle String URL = ”jdbc:mysql://localhost/employees"; // For MySQL Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
JDBC DriverManager Connection Statement ResultSet Driver Database
JDBC (Contd.) • Create a statement Statement st = conn.createStatement(); //default:TYPE_FORWARD_ONLY and CONCUR_READ_ONLY • or Statement st =conn.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); //the resultset will be scrollable and sensitive to changes made by others //we can update the resultset
JDBC DriverManager Connection Statement ResultSet Driver Database
JDBC (Contd.) • Execute a query String SQL = "INSERT INTO s" + " VALUES ('222-22-2222')"; int result = st.executeUpdate(SQL); //either the row count for INSERT, UPDATE or DELETE or 0 for SQL statements that return nothing • Execute a query and create a resultset String SQL = "SELECT * FROM Student"; ResultSet rec = st.executeQuery(SQL);
JDBC (Contd.) • Process the resultset while(rec.next()) { System.out.println(rec.getString("snum")); } • or while(rec.next()) { System.out.println(rec.getString(1)); // first column of the resultset } • There are methods like getString(), getInt(), etc. that take either a column name or column position • See http://java.sun.com/j2se/1.3/docs/guide/jdbc/index.html for all JDBC Class documentation
Tomcat – a J2EE Container • Open Source – integrated as an Apache.org project • Can be obtained from http://tomcat.apache.org • Provides full JSP 2.0/Servlet 2.4 functionality
Elements of a Java Server Page • Directives: <%@ %> • Provide global information to the page • Import statements • Scripting language u Declarations: <%! %> • For page-wide variable and method declarations
Elements of a Java Server Page • Scriptlets: <% %> • This is the Java code embedded in the web pages • Expressions: <%= %> • Formats the expression as a string to be included in the output of the web page • Comments: <%-- --%> • User readable comments, contents ignored and removed by the JSP Compiler
JSP Directives • General syntax: • <%@ directive {attribute = "value"} %> • Possible values for directives are: • Page - Information for the page • Include - Specifies the files whose contents are to be included in the output • e.g., <%@ include file="header.html" %> • Taglib • The URI for a library of custom tags that may be used in the page
JSP Page Directive • The page directive may take the following values: • <%@ page language = "java" %> • This variable tells the JSP engine what language will be used in the file • • "java" is the only language supported by JSP in the current specification • <%@ page import = "java.util.*, ItemValue" %> • Comma separated list of classes and packages that are used in the JSP page • Should appear at the top of the file
JSP Page Directive (Contd.) <%@ page session = "true | false" %> • true indicates that session data is available to the page • By default, this is set to true <%@ page buffer = "none | 16kb | sizekb" %> • Determines the size of the output stream buffer • Defaults to 8kb • Use with autoFlush <%@ page autoFlush = "true | false" %> • When set to true, flushes the output buffer when it is full, rather than raising an exception
JSP Page Directive (contd.) <%@ page errorPage = "mypage/error_handler.jsp" %> • Specifies the relative path of the page, where control would be transferred if any exceptions are thrown from this page • The error handling JSP page should have its isErrorPage directive set to true <%@ page isErrorPage = "true | false" %> • Marks the page as an error handler
JSP Declarations • Class and instance variables (of the generated servlet class) may be specified using the JSP Declaration tag: <%! String name = “Web Applications"; int index = 10; int count = 0; %> • Methods may also be specified: <%! private int getNextIndex() { return index ++; } %>
JSP Scriptlets • JSP scriptlets are defined as block of Java code embedded between a pair of • tags, <% and %>. • Example: <% java.util.Date d = new java.util.Date(); out.println(d); %>
JSP Expressions • Useful for embedding the result of a Java expression in a HTML page • The expression is encoded between the tags <%= and %> • The value of the expression is converted to a string and then displayed • Conversion of primitive types to string happens automatically • Example: • The date is <%= new java.util.Date() %>
JSP Implicit Objects • When writing scriptlets and expressions, the following objects (called implicit objects) are available by default: • request javax.servlet.http.HttpServletRequest • response javax.servlet.http.HttpServletResponse • out javax.servlet.jsp.JspWriter • session javax.servlet.http.HttpSession • application javax.servlet.ServletContext • exception java.lang.Throwable
Reading inputs from Forms/URLS • Remember that parameters are passed to Web applications via one of two methods: • GET method: parameters are passed directly through the URL, encoded using the urlencoding method • Quick to create and test – can be created without a form • Can be bookmarked • URL shows in plaintext – not secure • POST method: parameters are encoded and sent to the server separately from the URL • Can only be created via forms (or advanced applications) • Secure – parameters cannot be seen • Reading a single parameter via name: String value = request.getParameter(paramname); String [] values = request.getParameterValues(paramname); /* for multivalued parameters like checkboxes/multiple selectable lists */ • Better way – using “Beans” - shortly
JSP Session Example <html><head><title>Visitor Count -- JSP Session</title> </head> <body bgcolor="#FFFFFF"> <h2>Visitor Count</h2> <p>This JSP page demonstrates session management by incrementing a counter each time a user accesses a page.</p> <%! private int totalHits = 0; %> <% session = request.getSession(true); Integer ival = (Integer)session.getValue("jspsession.counter"); if (ival == null) ival = new Integer(1); else ival = new Integer(ival.intValue() + 1); session.putValue("jspsession.counter", ival); %> <p align="center"> You have hit this page <%= ival %> time<%= (ival.intValue() == 1) ? "" : "s" %>, out of a total of <%= ++totalHits %> page hit<%= (totalHits == 1) ? "" : "s" %>!</p> </body></html>
JSP Actions • Actions are tags that may affect the runtime behavior of the JSP or affect the current out stream; they may also use, modify and/or create objects. • JSP specification defines the following standard actions: • <jsp:useBean> • <jsp:setProperty> • <jsp:getProperty>
JSP Actions • <jsp:include> • <jsp:forward> • <jsp:param> • <jsp:plugin> • New action types are introduced by means of custom tags
What is a JavaBean? • A Java class that (at a minimum) • has an empty constructor • has getters and setters for each of the properties in the class • implements the serializable interface
JSP Actions and Attributes • JSP actions can define named attributes and associated values <%@ page import="People" errorPage="exception.jsp“ %> <jsp:useBean id="myperson" class="People" /> <% myperson.setName("Ramesh"); %> <h1>My name is: <%=myperson.getName()%></h1> <%-- Let's now use the bean syntax --%> Name using Bean is: <jsp:getProperty name="myperson" property="name" />
Beans and HTML forms • You may connect HTML form parameters to Bean properties <jsp:setProperty name="id" property="accountHolder" value = "<%= request.getParameter("accountHolder")%>/> • There is a shorthand for the above: <jsp:setProperty name="id" property="accountHolder" /> • This works if the property name was exactly the same as the form parametername
Beans and HTML forms • If the form parameter name and the property name do not match, then use the following variant of "jsp:setProperty" <jsp:setProperty name=“myperson" property=“age“ param=“myage" /> • Another powerful variation of "jsp:setProperty" examines all the parameter names from the request object and if some of them match with property names, it sets the appropriate properties <jsp:setProperty name=“myperson" property="*" />
Beans and HTML (contd.) <%-- Trying the all powerful syntax --%> <jsp:setProperty name="myperson" property="*" /> Name is: <%=myperson.getName()%> Age is: <%=myperson.getAge()%> Weight is: <%=myperson.getWeight()%>
Including Files • JSP supports two kinds of file inclusion: • Static (using the directive "include") • Dynamic (or Request-Time) • Static inclusion is specified using the "include" directive • e.g., <%@ include file="header.html" %> • In static inclusion, the contents of "header.html" are included in the output of the containing JSP file during the JSP page compilation • If the contents of the "header.html" file change, these changes are not visible to the user of the containing JSP file • Static inclusion is fast (because inclusion is done at compile time)
Including Files (contd.) • Dynamic inclusion is supported by the use of the tag "jsp:include" • e.g., <jsp:include page = "news/headlines.jsp" flush = "true" /> • Each time the containing JSP file is accessed, the JSP engine includes the contents of the latest copy of the file "news/headlines.jsp“ • You may also pass parameters to the included file, e.g: <jsp:include page = "news/headlines.jsp" flush="true"> <jsp:param name="prefers" value="international"/> ... </jsp:include>
Forwarding Files • A request to a JSP file may be forwarded, transparently to the user, to another JSP file • <jsp:forward page = "target" /> • This is used to redirect request from one page to another page • The calling JSP file relinquishes control to the forwarded page • The calling JSP cannot send any data back to the browser before invoking this tag • If data had already been sent by the calling JSP, invoking the "jsp:forward" tag causes an exception to be thrown
Forwarding Requests • You may also pass parameters to the forwarded page • <jsp:forward page="catalog.jsp" /> • <jsp:param name="color" value="red"/> • ... • </jsp:forward> • Parameters passed in this fashion may be accessed by the forwarded JSP (catalog.jsp) by the following call: • request.getParameter("color");
Forwarding Requests • Request forwarding is typically used for authentication <% if(request.getParameter("login-info") == null) %> <jsp:forward page="login.jsp"/> <% else { /* Generate Error message – no login */ } %>
Summary • JSP – JDBC provides a stable and well-tested platform for 3-tier web application design • Supports all major databases and all platforms • With Servlet compilation, performance is high • Many major applications like Wiki, major Government/Funding organizations like NSF – are running on Java/JSP technology. • Web services are well-supported • J2EE provides a well-designed software design and development platform for enterprise systems.