Component Based Software Engineering Masato Suzuki School of Information Science Japan Advanced Institute of Science and Technology 1 Schedule Mar. 10 13:30-15:00 : 09. Introduction and basic concepts 15:10-16:40 : 10. Client side components(1) Mar. 11 13:30-15:00 : 11. Client side components(2) 15:10-16:40 : 12. Server side components(1) Mar. 17 13:30-15:00 : 13. Server side components(2) 15:10-16:40 : 14. Frameworks and middlewares Mar. 19 12:30-14:00 : 15. State-of-the-art topics 2
#12 Server side components(1) Contents!! Web application!! Servlet and JSP: dymamic creation of WEB pages 3 Client/Server architecture style Physical structure: A server and multiple (independent) clients Customer submit/cancel!"#$! %&#'"(! show status Manager Functinal req: Submit/cancel from any costomer client at any time Show status report from manager's client. Using GUI and no specical software is required to any clients Non-functional req: Location independent for clients Scalability 4
Client/Server (cont.) Logical structure!! Communicate through request/responce pair.!! Behavior is as same as a regular procedure call. request = new Request(tf.getText(),...); response = server.submit(request); if (response.getstatus() ==... ) Response submit(request request) { DB.add(request.getDay(),... ); } submit/cancel Resv. logic add/update ResvDB Structure of request/response are simple. Building independent server for each app. will raise development costs. 5 WEB Applications We generally employ the style of WEB application for implementation of typical C/S systems.!! WEB browser is easier to use than stand alone app.!! WEB server is more general to provide services. Servlets are used for extention of a WEB server. Web Browser Web Server an applet http a servlet an applet a script script engine a script script engine application services 6
HTTP(HyperText Transfer Protocol) [RFC2616]!! Aimed communication with text documents!! HTML documents are searched/ aquired/ displayed and shared on the WEB.!! Communication is achieved by specifying uniformed location of documents (URL). f1 <a href= http://h2/f2.html >f2</a> h1 f2 GET f1.html HTTP/1.1... GET f2.html HTTP/1.1... h2 7 Scripting Languages!! Describe dynamic operations such as read/write of variables, arith. op. etc.!! Code in JavaScript is performed as a part of browser.!! External scripts are written in Perl/Ruby, executed as another process using the CGI mechiasm. a.class an applet Web Browser a.html <object classid= java:applet > </object> Web Server a.html x.cgi CGI script engine <form action= x.cgi > </form> interpreter 8
CGI mechanism is harmful CGI (Common Gateway Interface) has many problems.!! Overhead caused by running as another process loses the scalability.!! Some parameters encoded as a part of URL may cause severe security issues. Web Browser name pass Send suzuki *** login.html <html> <form action= login.cgi >... <input type= submit name= Send...> </form> </html> invoked as many as the number of clients secret information is exposed login.cgi? ID=suzuki&PW=foo login.cgi DB 9 Servlet: Server side components!! Dynamic extension of WEB servers.!! Independent to platforms (Java VM is required)!! Running on multi-threads reduce overheads.!! Low opportunity to expose secure data. Web Browser Request(*) Web Server (Apache) a servlet a JSP container(tomcat) Response(*) Servlet APIs (*)javax.servlet.http. HttpServletRequest Servlet.class.class 10
Objects for handling Status!! HTTP is transient, no persistent status.!! Status are provided by some (internal) objects!! Container holds these objects. WEB Browser cookie addcookie request param[...] response out WEB Server(Apache/Tomcat) session Attribute application ServletPath config timeout encode getcookie session Attribute exception Message (capacity of cookie is small [< 4KB]) 11 Structure of a Servlet It generates response from request. Writing HTML strings to out makes a page. import java.io.*; import java.servlet.*; import java.servlet.http.*; public class myloginservlet extends HttpServlet { public void doget(httpserveltrequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession session = request.getsession(true); response.setcontexttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html><body>"); out.print("name=");... out.print("pass=");... out.println("</body></html>"); }... response out <html> <body> name=... pass=... </body> </html> 12
Dynamic creation Dynamic creation is achieved by writing variables as the result of some operations. public class VacancyServlet extends HttpServlet { public void doget(httpserveltrequest request, HttpServletResponse response) throws IOException, ServletException { // initializations are omitted String day = request.getparameter( day ); int num = db.getvacancy(day); out.println("<table><tr>"); out.print("vacancy(" + day + )= + num);... out.println("</tr></table>"); }... (Object db is an abstraction of a database.) browser num 3 request response day 10/20 db 20 21 3 4 out <table><tr> vancancy(10/20)=3 </tr></table> vacancy(10/20)=3 13 Problems in Servlet coding!! Servlet is a powerful, flexible mechanism for dynamic creation of WEB pages, but!! Developers must describe many routine codes. They are non-productive works. Eg. create table for vacancy in [10/21,10/30] request from 10/21 db to 20 21... 30 3 4 2 10/30 It is also hard to understand. String from= request.getparameter( from ); String to = request.getparameter( to ); int fromday = DaytoInt(from); int today = DaytoInt(to); out.println("<table>"); for (int d= fromday; d <= today; d++) { num = db.getvacancybyday(d); out.println("<tr>vacancy(" + d + )= + num + </td> ); } out.println("</table>"); 14
From JSP to Servlet!! JSP(Java Server Page) is a scripting language which generates a HTML page dynamically.!! JSP script is converted to servlet code (in Java )!! Expressions/variables can be described. A JSP script (Vacancy.jsp) <% String day =... %> <% int num = db.getvacancy(day); %> <html> <body> <table> vacancy(${day}) = ${num} </table> </body> </html> Complied when it is loaded first. A source of servlet (Vacancy.java) class VacancyServlet extends javax.servlet.httpservlet { public void doget( HTTPServletRequest req, HTTPServletResponce res) {... String day=req.getparameter( day ); int num= db.getvacancy(day); out.print( vancancy( ); out.print(day); out.print( )= );... Pre-compiled, deployed as.class. 15 Usage of JSP(1)!! Inputs are read as parameters from a form generated by another HTML file.!! Outputs are calculated and written in the JSP file. Example: query the number of available (single, twin) rooms date 10/10 query Result 10/10: S1T2 OK index.html <form action="query.jsp"> <table><tr> <td>date</td> <td><input type="text"... ></td> </tr></table> <input type="submit"...> </form> query.jsp read <% String date = param[ date ] %> <% query.jsp String result = getresult(...); %> <h1>result</h1> calculate <table><tr> <td>${date}:</td> write <td>${result}</td> </tr></table> 16
Usage of JSP(2) Transition to another page is achieved by jsp:forward. login.jsp <table><tr> <td> ${param["name"]} </td> <td> ${param[ pass ]} </td> </tr></table> <jsp:forward page= check.jsp /> All outputs are discarded. All parameters are unchanged. check.jsp <% Welcome String name=param["name"]; name suzuki suzuki String pass=param["pass"]; pass *** if (authorize(name,pass)) { %> If we use <jsp:include> instead, Welcome ${name} it back to the previous page after the operation in included file are finished. 17 Usage of JSP(3) It is better to implement complex logics by JavaBeans. usebean create a new instance of external JavaBean and initialize it. setproperty/getproperty are used for interaction to the Bean. calendar.jsp <jsp:usebean id="mycal" class="cal.mycalendar.class" /> <jsp:setproperty name="mycal" property="year" value=... /> <jsp:setproperty name="mycal" property="month" value=... /> <jsp:setproperty name="mycal" property="day" value=... /> <p>result: <jsp:getproperty name="mycal" property="dayofweek" /> </p> mycal setproperty mycal usebean year 2009 month 3 day 1 dayofweek Sunday getproperty 18
MyCalendar.java public class MyCalendar { String year = "1900"; String month = "1"; String day = "1"; String dayofweek = ""; String[] dayname={"","sunday","monday","tuesday","wednesday", "Thursday","Friday","Saturday"}; public MyCalendar() { } public void setyear(string y) { year = y; calc(); } public void setmonth(string m) { month = m; calc(); } public void setday(string d) { day = d; calc(); } public String getdayofweek() { return dayofweek; } private void calc() { java.util.calendar calendar = java.util.calendar.getinstance(); int yy = new Integer(year).intValue(); int mm = new Integer(month).intValue(); int dd = new Integer(day).intValue(); calendar.set(yy,mm-1,dd); int dw = calendar.get(calendar.day_of_week); dayofweek = dayname[dw]; /* exception handling is required */ } }; 19 Summary!! WEB application!! Using WEB brower as a client.!! Using WEB server as a server.!! Extended by applet and servlet respectively.!! Dynamiac creation of WEB pages!! Interact with request and response.!! Inputs are read from the request.!! Outputs are written to out (inside the response)!! Servlet coding is boring, so we generally use JSP.!! JSP can use external JavaBeans. Complex (or secret) logics are implemented in JavaBeans. 20
!! JSP!! Tag libraries!! Database access Next Chapter Client side components (2)!! JavaEE and 3 tier Model!! Business logics!! Persistence for POJO (Plain Old Java Objects) 21 Exercise Review the content of my lecture by answering the following simple questions.!! What is a web application?!! Why we usually implement a C/S systems as a web application?!! What is a servlet?!! What is the difference of servlet and applet?!! What is the JSP?!! Why we usually prefer using JSP to coding servlet directly?!! Trace the behavior of calender.jsp line by line. 22