Web Programming II JSP (Java Server Pages) ASP request processing. The Problem. The Problem. Enterprise Application Development using J2EE



Similar documents
2. Follow the installation directions and install the server on ccc

Services. Custom Tag Libraries. Today. Web Development. Role-Based. Development. Code Reuse. Tag Libraries Custom Tags. Tag Lifecycle.

Outline. CS 112 Introduction to Programming. Recap: HTML/CSS/Javascript. Admin. Outline

Agenda. Summary of Previous Session. Application Servers G Session 3 - Main Theme Page-Based Application Servers (Part II)

Java Server Pages and Java Beans

Web Programming with Java Servlets

Web Container Components Servlet JSP Tag Libraries

Model-View-Controller. and. Struts 2

JSP Java Server Pages

Web Frameworks and WebWork

An introduction to web programming with Java

2.8. Session management

CS412 Interactive Lab Creating a Simple Web Form

Creating Java EE Applications and Servlets with IntelliJ IDEA

In this chapter, we lay the foundation for all our further discussions. We start

WIRIS quizzes web services Getting started with PHP and Java

CrownPeak Java Web Hosting. Version 0.20

BAPI. Business Application Programming Interface. Compiled by Y R Nagesh 1

Application Security

Course Name: Course in JSP Course Code: P5

How To Understand The Architecture Of Java 2Ee, J2Ee, And J2E (Java) In A Wordpress Blog Post

Hello World RESTful web service tutorial

Building Web Applications, Servlets, JSP and JDBC

Design Approaches of Web Application with Efficient Performance in JAVA

Real SQL Programming 1

DTS Web Developers Guide

Development. with NetBeans 5.0. A Quick Start in Basic Web and Struts Applications. Geertjan Wielenga

Web Applications. For live Java training, please see training courses at

Rapid Application Development. and Application Generation Tools. Walter Knesel

Web Applications and Struts 2

Java EE Introduction, Content. Component Architecture: Why and How Java EE: Enterprise Java

Complete Java Web Development

Exam Prep. Sun Certified Web Component Developer (SCWCD) for J2EE Platform

Introduction to J2EE Web Technologies

Glassfish, JAVA EE, Servlets, JSP, EJB

HTML Forms and CONTROLS

Servlets. Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun

Developing XML Solutions with JavaServer Pages Technology

CSI 2132 Lab 8. Outline. Web Programming JSP 23/03/2012

7 Web Databases. Access to Web Databases: Servlets, Applets. Java Server Pages PHP, PEAR. Languages: Java, PHP, Python,...

Developing Web Applications using JavaServer Pages and Servlets

Web Development in Java Part I

JavaScript By: A. Mousavi & P. Broomhead SERG, School of Engineering Design, Brunel University, UK

Website Planning Checklist

Tutorial: Building a Web Application with Struts

CS Developing Web Applications with Java Technologies

Web Pages. Static Web Pages SHTML

c. Write a JavaScript statement to print out as an alert box the value of the third Radio button (whether or not selected) in the second form.

Simplify Your Web App Development Using the Spring MVC Framework

Java 2 Platform, Enterprise Edition (J2EE) Bruno Souza Java Technologist, Sun Microsystems, Inc.

Client-Server Architecture & J2EE Platform Technologies Overview Ahmed K. Ezzat

Web Application Development Using Borland JBuilder 8 WebLogic Edition

JWIG Yet Another Framework for Maintainable and Secure Web Applications

PA165 - Lab session - Web Presentation Layer

CS506 Web Design and Development Solved Online Quiz No. 01

BEST WEB PROGRAMMING LANGUAGES TO LEARN ON YOUR OWN TIME

Core Java+ J2EE+Struts+Hibernate+Spring

JavaScript and Dreamweaver Examples

Web Development 1 A4 Project Description Web Architecture

Security Code Review- Identifying Web Vulnerabilities

HTML Form Widgets. Review: HTML Forms. Review: CGI Programs

Controlling Web Application Behavior

<Insert Picture Here>

JAVA/J2EE DEVELOPER RESUME

Java Server Pages combined with servlets in action. Generals. Java Servlets

A Guide to Understanding Web Application Development Corey Benson, SAS Institute, Inc., Cary, NC Robert Girardin, SAS Institute, Inc.

Struts Tools Tutorial. Version: M5

HTML Tables. IT 3203 Introduction to Web Development

Implementing the Shop with EJB

Portals, Portlets & Liferay Platform

Programming on the Web(CSC309F) Tutorial: Servlets && Tomcat TA:Wael Aboelsaadat

Web Application Architecture (based J2EE 1.4 Tutorial)

How to use JavaMail to send

Web Application Programmer's Guide

NGASI AppServer Manager SaaS/ASP Hosting Automation for Cloud Computing Administrator and User Guide

Esigate Module Documentation

Further web design: HTML forms

Web Development and Core Java Lab Manual V th Semester

Outline. Lecture 18: Ruby on Rails MVC. Introduction to Rails

Web Applications. Originals of Slides and Source Code for Examples:

Java and Web. WebWork

Outline. Lecture 9: Java Servlet and JSP. Servlet API. HTTP Servlet Basics

Java Server Pages (JSP)

Web Frameworks. web development done right. Course of Web Technologies A.A. 2010/2011 Valerio Maggio, PhD Student Prof.

Intell-a-Keeper Reporting System Technical Programming Guide. Tracking your Bookings without going Nuts!

Introduction to XHTML. 2010, Robert K. Moniot 1

Website as Tool for Compare Credit Card Offers

Script Handbook for Interactive Scientific Website Building

ACI Commerce Gateway Hosted Payment Page Guide

Implementing Specialized Data Capture Applications with InVision Development Tools (Part 2)

Japan Communication India Skill Development Center

Developing an EJB3 Application. on WebSphere 6.1. using RAD 7.5

Transcription:

Enterprise Application Development using J2EE Shmulik London Lecture #6 Web Programming II JSP (Java Server Pages) How we approached it in the old days (ASP) <HTML><TITLE>Multiplication Table</TITLE> <H2>Multiplication Table</H2> <TABLE border="1" cellpadding="2" cellspacing="0"> <TR height="20" bgcolor="#f0f0f0"><td width="20"></td> <% FOR J=1 TO 10 %> <TD width="20"><%=j%></td> <% NEXT FOR I=1 TO 10 %> <TR height="20"><td width="20" bgcolor="#f0f0f0"><%=i%></td> <% FOR J=1 TO 10 %> <TD width="20"><%=i*j%></td> <% NEXT NEXT %> </TABLE> </HTML> Interdisciplinary Center Herzeliza Israel Note: this example is superficial we don t need the server for the data, we might as well do it in client side JavaScript The Problem ASP request processing ResultSet result = statement.executequery( "SELECT course_id, name, hours FROM courses"); response.setcontenttype("text/html"); PrintWriter writer = response.getwriter(); writer.println( <html><body><table border=\"1\">"); writer.println("<td>id</td><td>name</td> ); while(result.next()) { long id = result.getlong(1); String name = result.getstring(2); writer.println("<td>"+id+"</td> + <td> +name+ </td> ); writer.println( </table></body></html> ); Internet The ASP page is parsed and the embedded scripts are executed to generate dynamic content IIS ISAPI Filter ASP Page File-system static content and templates Courses Database The Problem Writing HTML in Java is cumbersome and inefficient (both runtime and development cycle) We would like Web Designers to do design the page and programmers to do the logic (separation of concerns) And some continued this way in JSP <HTML> <TITLE>Multiplication Table</TITLE> <H2>Multiplication Table</H2> <TABLE border="1" cellpadding="2" cellspacing="0"> <TR height="20" bgcolor="f0f0f0"><td width="20"></td> <% for (int j=1; j<=10; j++) { %> <TD width="20"><%=j%></td> <% %> <% for (int i=0; i<=10; i++) { %> <TR height="20"><td width="20" bgcolor="f0f0f0"><%=i%></td> <% for (int j=1; j<=10; j++) { %> <TD width="20"><%=i*j%></td> <% %> </TABLE> </HTML> 1

But you re too smart for that <HTML> <TITLE>Multiplication Table</TITLE> <H2>Multiplication Table</H2> <TABLE border="1" cellpadding="2" cellspacing="0"> <TR height="20" bgcolor="f0f0f0"><td width="20"></td> <% for (int j=1; j<=10; j++) { %> <TD width="20"><%=j%></td> <% %> Scripting elements make <% for (int i=0; i<=10; i++) { %> <TR height="20"><td width="20" bgcolor="f0f0f0"><%=i%></td> <% for (int j=1; j<=10; j++) { %> <TD width="20"><%=i*j%></td> <% %> </TABLE> </HTML> the code messy and don t allow for good separation of concerns (design / logic) JSP offer better alternatives. Avoid scripting elements! Example (Query Form) <html> <head><title>course Search</title></head> <body> <h1>course Search</h1> <form action="course-info" method="post"> <table border="0"> <td>enter course code</td> <td><input name="code" type="text" size="10"/></td> <td><input type="submit" value="submit"/></td> </table> </form> </body> </html> Scripting Elements Imagine large pages, containing both scripting elements, JavaScript / DHTML, CSS, sometimes Applets or ActiveX controls.. server side script that generate client side script!, pages delegates control to each other.. This results in a jungle that is impossible to maintain Example (JSP Template) <html> <body> <h1>course Details</h1> <b>name:</b> ${coursename <br/> <b>code:</b> ${coursecode <br/> <b>credit points:</b> ${creditpoints <br/> </body> JSP as a Template Engine Example (Servlet) protected void dopost(httpservletrequest request Request Fetch data or compute Servlet JSP Page Use the data to fill in a JSP template Return the result of merging the static html of the template with the dynamic data String code = request.getparameter( code ); String coursename = fetch data using code String creditpoints = fetch data request.setattribute( coursename, coursename); request.setattribute( coursecode, code); request.setattribute( creditpoints, creditpoints); RequestDispatcher dispatcher = request.getrequestdispatcher( "/course-info.jsp"); dispatcher.forward(request, response); 2

JSP request processing JSP Tags Internet Upon first request the JSP is parsed and is compiled into a Servlet. The Servlet include code to dump static HTML code segments that appeared in the original JSP page Controller Servlet JSP container JSP Page JSP compiler JSP defines a set of HTML-like tags that allow to add dynamic content to a page In addition it provide a simple way for writing your own custom tags You can find numerous of tag libraries (often open source) Template Engines Many web frameworks use the idea of a template engine JSP, Velocity, FreeMarker (Java) Django (Python) Ruby on Rails (Ruby) Grails (Groovy) Lift (Scala) Example: include Tag Includes the content of another page (static or dynamic) in the current page <html> <body> <jsp:include page="header.html /> <jsp:include page="menu.jsp /> <h1>my special page</h1> Here is the content of my special page...... <jsp:include page="footer.html"/> </body> </html> Beyond Placeholders Sometimes we need more than just placeholders Lists / Tables Conditional segments Common elements header, footer.. We use JSP Tags for this Again not embedded code! Example Using <jsp:include> to include a result of a Servlet Again: this example is superficial we don t need the server for the data, we might as well do it in client side JavaScript 3

Example Using <jsp:include> to include a result of a Servlet multiplication_table.jsp <h2>multiplication Table</h2> <form method="get" action="multiplication_table.jsp" > Rows <select name="rows"><option value="3">3</option> </select> Columns <select name="columns"> </select> <input type="submit" value="go"> </form> multiplication_table.jsp MultiplicationTableServlet <jsp:include page="/multiplication_table_servlet" flush="true"> <jsp:param name="rows" value="<%=request.getparameter("rows")%>"/> <jsp:param name="columns" value="<%=request.getparameter("columns")%>"/> </jsp:include> MultiplicationTableServlet JSTL protected void doget( HttpServletRequest request, HttpServletResponse response) throws IOException { try { int rows = Integer.parseInt( request.getparameter("rows")); int columns = Integer.parseInt( request.getparameter("columns")); PrintWriter writer = response.getwriter(); printtable(writer, rows, columns); catch (NumberFormatException e) { System.out.println("Illegal parameter value"); JSTL - JSP Standard Tag Library Collection of tags for functions that are common to many web apps flow control, formatting, IO Introduces EL expressions Note: JSTL introduce many Tags, but not all make sense, Tags that access the database or read files directly from the JSP page is a bad idea! In general all the logic of fetching the data should be done in lower layer MultiplicationTableServlet private void printtable( PrintWriter writer, int rows, int columns) { writer.println("<table border=\"1\" cellpading >"); writer.println("<tr height=\"20\" bgcolor=</td>"); for (int j=1; j<=columns; j++) { writer.println("<td width=\"20\">"+j+"</td>"); for (int i=1; i<=rows; i++) { writer.println( "<TR height=\"20\"><td width=\"20\" " + "bgcolor=\"f0f0f0\">"+i+"</td>"); if Tag <%@ page import="sokoban.web.*"%> <%@ taglib prefix="c uri="http://java.sun.com/jstl/core" %> <jsp:include page="/header.html"/> <p>welcome to our Sokoban server. <c:if test="${!(empty sessioninfo.message)"> <p><font color="#cc3300"> <c:out value="${sessioninfo.message" /> </font></p> </c:if> EL Expressions 4

foreach Tag <%@ page iselignored ="false" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <body> <h1>course List</h1> <table border="1" cellpadding="3" cellspacing="0"> <th width="80" align="center">symbol</th> <th width="400" align="center">name</th> <th width="120" align="center">instructor</th> <c:foreach var="course" items="${courses"> <td align="center">${course.symbol</td> <td align="center">${course.name</td> <td align="center">${course.instructor</td> </c:foreach> </table> </body> </html> Custom Tag Example Repeated HTML code Again, this example is superficial we are better off using JavaScript here as expanding the tag in the server will result-in large html sent to the client, and redundant server load Servlet Side public void doget(httpservletrequest request ) { ResultSet results = statement.executequery( SELECT * FROM courses ); List<CourseInfo> courses = new ArrayList<CourseInfo>(); while (results.next()) { CourseInfo course = new CourseInfo(); course.setsymbol(results.getstring( symbol )); course.setname(results.getstring( name )); request.setattribute( courses, courses); request.getrequestdispatcher( /course-list.jsp ). forward(request, response); Note: there might be too many results to be sent in a single request, it is always a good idea to limit the number of results and page through them Custom JSP Tag <%@ taglib prefix="examples uri="http://www.idc.ac.il/j2ee/examples" %> <h2>recommended EJB Books</h2> <table border=0> <td><examples:rank rank="5"/></td> <td>enterprise JavaBeans / Reichard Monson-Haefel</td> <td><examples:rank rank="5"/></td> <td>mastering Enterprise JavaBeans / Ed Roman</td> <td><examples:rank rank="4"/></td> <td>ejb Design Patterns / Floyd Marinescu</td> Tag Libraries JSP allows you to add additional tags through tag-libraries You can wrap a commonly used presentation code in a new tag and provide it to the web-designer You can find numerous tag libraries (notably JSTL) or develop your own Custom JSP Tag package examples.web.tags; import java.io.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class RankTag extends TagSupport { private static final int MAX_RANK = 5; private int rank; public void setrank(int rank) { this.rank = rank; 5

Custom JSP Tag public int dostarttag() throws JspException { JspWriter writer = pagecontext.getout(); try { writer.println("<table border=0 width=50>"); writer.println("<tr height=20 width=50>"); for (int i=0; i<max_rank; i++) { writer.println(i<rank? <td width=10><image + src=\"res/icons/star.gif\"</td>") : <td width=10> </td>"); writer.println("</table>"); catch (IOException e) { e.printstacktrace(); return EVAL_PAGE; WAFs Such a framework is referred to as WAF (Web Application Framework) There are many Java based WAFs, on top of JSP and/or Servlets We ll describe a general design for working with JSP & Servlets. It is used in Struts2 and other WAFs Custom JSP Tag <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, <taglib> <tlibversion>1.1</tlibversion> <jspversion>1.1</jspversion> <shortname>examples</shortname> <uri>http://www.idc.ac.il/j2ee/examples</uri> <tag> <name>rank</name> <tagclass>examples.ranktag</tagclass> <attribute> <name>rank</name> <required>true</required> <rtexprvalue>false</rtexprvalue> </attribute> </tag> </taglib> Model2 Model2* applies a design pattern known as MVC to the problem The client directs all requests to a single controller Servlet The controller process the request, acts on the model and forwards the request to another Servlet/JSP for rendering The target Servlet/JSP render the response according to attributes passed by the controller via request/session attributes Web Application Framework Real applications consists of many Webpages both dynamic & static Pages forward/redirect request to other pages, include other pages, and call components to perform logic We need a consistent framework for organizing all presentation and logic components and the interaction between them Model2 (MVC) JSP Pages (View) Servlet (Controller) Forward request after setting attributes in request or session JavaBeans / EJB / Database (Model) 6

Example (ex3) Using JavaBeans login.jsp game.jsp MapRenderingServlet MIDletResponseServlet Developer Works with Java & HTML JSP Page Web-Designer Works with designer tools ControllerServlet JavaBeans Component (logic) Passing parameters Mortgage Calculator Example public class ControllerServlet extends HttpServlet { public void doget(httpservletrequest request, ) { request.setattribute( price, new Float(price)); forward Controller Servlet Price: ${price Rendering JSP page Using JavaBeans JSP allows to separate presentation from logic by using JavaBeans You embed a JavaBean in your page Set its properties, typically according to request parameters values The bean calculates the value of other properties accordingly Retrieve the value of the calculated property and include it in the page MortgageCalcBean /** * A JavaBean component for calculating a mortgage * monthly payment */ public class MortgageCalcBean implements Serializable { // The requested amount of the loan private double loanamount; // The annual interest private double interest; // The requested period of the load in years. private int years; Hold the value of the properties of the bean 7

MortgageCalcBean public double getloanamount() { return loanamount; public void setloanamount(double loanamount) { this.loanamount = loanamount; public double getinterest() { return interest; public void setinterest(double interest) { this.interest = interest; Setter/Getter methods, define the properties of the bean mortgage_calculator.jsp <jsp:usebean id="calc" class="mortgagecalcbean"/> <jsp:setproperty name="calc" property="loanamount" param="loanamount"/> <jsp:setproperty name="calc" property="interest" <jsp:setproperty name="calc" <form method="post" action="mortgage_calc.jsp" > Amount: <input type="text" name="loanamount" value="<%=calc.getloanamount()%>"><br> Interest: <input type="text" name="interest" value="<%=calc.getinterest()%>"><br> Years: <input type="text" name="years" value="<%=calc.getyears()%>"><br> <input type="submit" value="calculate"> </form> Monthly Payment $ <jsp:getproperty name="calc" property="monthlypayment"/> MortgageCalcBean Packaging public double getmonthlypayment() { double monthlypayment = calculatemonthlypayment(); return monthlypayment; private double calculatemonthlypayment() { double monthlyinterest = interest * 0.01 / 12; int months = years * 12; double debt = Math.pow(1+monthlyInterest, months); double monthlypayment = loanamount*debt*monthlyinterest/(debt-1); monthlypayment = Math.floor(monthlyPayment*100)/100.0; return monthlypayment; Read only property to return the result A web-application consists of many elements Static HTML pages and resources (images, clips, ) JSP pages and tag-libraries Servlets, Java classes, JARs Configuration files (descriptors) mortgage_calculator.jsp Packaging <h1 align="center">simple Mortgage Calculator</h1> <p> Below is a simple calculator for calculating the monthly payment of the mortgage. Please enter the required loan amount, the interest you expect to get for the loan and the period of the loan in years; then press the 'calculate' button. </p> tabs, tables to enhance the look of the page J2EE defines a standard form for packaging web-applications The packaging unit is called a web-module It has standard folder structure and contains standard descriptor files The module is packaged as a WAR file (Web Achieve) essentially a zip of the folder It can either be packaged standalone or as part of a J2EE application together with other web modules and ejb modules 8

Packaging application.xml <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE application PUBLIC '-//Sun Microsystems, <application> <display-name>examples</display-name> <module> <web> <web-uri>examples.war</web-uri> <context-root>/examples</context-root> </web> </module> </application> Example Apache Ant and other insects Servlet and supporting classes tag library definition for JSTL JBoss specific web application descriptor web application descriptor resources libraries required by JSTL web-pages JSP & static Manual packaging is tedious & error-prone Application server tools & IDEs provide varying level of support for packaging, deployment and editing descriptor files - often not enough We ll use Apache Ant, which is a generic build tool and de-facto standard building Java applications More on Ant in a separate presentation web.xml <web-app> <servlet> <servlet-name>courselistservlet</servlet-name> <servlet-class>courselistservlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>courselistservlet</servlet-name> <url-pattern>/course_list</url-pattern> </servlet-mapping> <env-entry> <env-entry-name>jdbc/idcdb</env-entry-name> <env-entry-value>!org.gjt.mm.mysql.driver!jdbc:mysql://localhost: </env-entry-value> <env-entry-type>java.lang.string</env-entry-type> </env-entry> </web-app> 9