Presentation is loading. Please wait.

Presentation is loading. Please wait.

An XML-Based JDBC Connector Servlet Framework Geng Tang 03/05/2001.

Similar presentations


Presentation on theme: "An XML-Based JDBC Connector Servlet Framework Geng Tang 03/05/2001."— Presentation transcript:

1 An XML-Based JDBC Connector Servlet Framework Geng Tang 03/05/2001

2 What is JCS ? zJDBC Connector Servlet

3 Com.jresources.servlets Package zClass JDBCConnectorServlet zpackage com.jresources.servlets; zimport javax.servlet.*; zimport javax.servlet.http.*; zimport java.io.*; zimport com.jresources.jcs.*; zimport java.util.Enumeration; zimport java.util.Properties; zpublic class JDBCConnectorServlet extends HttpServlet { zprivate java.util.Properties initProps = new Properties(); zpublic void init(ServletConfig config) throws ServletException { zsuper.init(config); zEnumeration e = config.getInitParameterNames(); zwhile(e.hasMoreElements()) { zString currParam = (String)e.nextElement(); zinitProps.put(currParam, config.getInitParameter(currParam)); z}

4 zpublic void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { z jcsEngine mainMod = new jcsEngine(); ztry {String qryDoc; zif(request.getPathInfo()==null) { zqryDoc = getServletConfig().getServletContext().getRealPath(request.getServletPath()); z}else { zqryDoc = request.getPathTranslated(); z} zmainMod.processRequest(request, this.initProps,qryDoc); zif(mainMod.getResponseType()==jcsEngine.RESPONSE_REDIRECT) { zresponse.sendRedirect(mainMod.getResponse()); z} else { zPrintWriter out = response.getWriter(); zresponse.setContentType(mainMod.getMIMEType()); zout.println(mainMod.getResponse()); z} x}catch(Exception e) { x String errorMsg = "An error occurred while executing the query " + – request.getServletPath() + " with the JCS servlet: " + e.toString(); z this.getServletContext().log(errorMsg, e); z if(mainMod.getErrorPage()=="") { z throw new ServletException(errorMsg, e); z }else { z response.sendRedirect(mainMod.getErrorPage()); z } z public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {doGet(request, response); z }

5 Method in jcsEngine z public void processRequest(HttpServletRequest request, String qryDoc) throws Exception z { zthis.processRequest(request, null, qryDoc); z} z/** z * Executes the request with custom properties z */ zpublic void processRequest(HttpServletRequest request, Properties customProps, String qryDoc) throws Exception z { z//our results zStringBuffer strResults = new StringBuffer(""); z//open the script zString qryContent = FunctionLib.OpenFile(qryDoc); zqryContent = this.insertFormVariables(qryContent, request); z//check for custom properties...if exist, then apply zif(customProps!=null) { zqryContent = this.insertJCSVariables(qryContent, customProps); z} z//process SQLEncode function calls zString[] workingQuery = new String[1]; zworkingQuery[0] = qryContent; zthis.processSQLEncode(workingQuery, new StringBuffer()); zqryContent = workingQuery[0]; z//parse the query script zjcsQuery objQuery = new jcsQuery(qryContent); z//TODO: reimplement this code as a finite state machine to make it cleaner and more extensible z//set the errorpage for error handling zerrorPage = objQuery.getErrorPage(); z//create a string array to hold the template text zString[] workingTemplate = new String[1];

6 z//open the template file zif(objQuery.getTemplateDoc()!="") { zworkingTemplate[0] = objQuery.getTemplateDoc(); z//process any server-side includes it might have zthis.processSSI(workingTemplate, new StringBuffer(), qryDoc, 0); z} z//instantiate and register the JDBC driver zClass.forName(objQuery.getJDBCDriver()); z//connect to the database and create a statement zConnection conn = DriverManager.getConnection(objQuery.getJDBCURL(), objQuery.getUID(), objQuery.getPWD()); zStatement s = conn.createStatement(); z//if it's a "write" query, execute it and redirect to the redirectURL z//if there is no redirect url, add the template to the results stringbuffer zif(objQuery.IsTransaction()) { zs.executeUpdate(objQuery.getSQL()); z//System.out.println(objQuery.getRedirectURL()); zif(objQuery.getRedirectURL()!="") { zconn.close(); //clean up the db connection zthis.response = objQuery.getRedirectURL(); zthis.responseType = jcsEngine.RESPONSE_REDIRECT; zreturn; z}else { zstrResults.append(workingTemplate[0]); z}

7 z//otherwise, further parse the template for the jcs:resultset tag... z//execute the query, loop thru the rs, apply the template's display zelse{ zif(objQuery.getMaxRows() > -1){ zs.setMaxRows(objQuery.getMaxRows()); z} zResultSet rs = s.executeQuery(objQuery.getSQL()); z//if there is no template, then send the default z//XML document zif(objQuery.getTemplateDoc().equals("")) { zXMLSerializableResultset xrs = new XMLSerializableResultset(rs); zthis.response = xrs.getXML(); zthis.MIMEType = "text/xml"; zthis.responseType = jcsEngine.RESPONSE_WRITE; zrs.close(); zconn.close(); zreturn;

8 z}else { zjcsTemplateParser template = new jcsTemplateParser(); ztemplate.setTemplate(workingTemplate[0]); zstrResults.append(template.getHeader()); zResultSetMetaData rsMetadata = rs.getMetaData(); zint intFields = rsMetadata.getColumnCount(); zString recordOutput; zString currFieldValue; zString AdjFieldValue; zint recordCount = 0; zwhile(rs.next()) { zrecordOutput = template.getBody(); zfor(int i =1; i <= intFields; i++) { zcurrFieldValue = FunctionLib.EncodeSpecialCharacters(rs.getString(i)); zAdjFieldValue = objQuery.UseHTMLLineBreak()?FunctionLib.HTMLLineBreak(currFieldValue):currFieldValue; zrecordOutput = FunctionLib.Replace(recordOutput, "#" + rsMetadata.getColumnName(i) + "#", AdjFieldValue); z} zstrResults.append(recordOutput); zrecordCount++; z} zif(recordCount == 0) { zstrResults.append(objQuery.getEmptyResultsetOutput()); z} zstrResults.append(template.getFooter()); z} zrs.close();

9 z} z//end sql check zconn.close(); zthis.MIMEType = objQuery.getMIMEType(); zthis.responseType = jcsEngine.RESPONSE_WRITE; z//make sure we fill out any form or cgi variables in the template... zString tmpResponse = insertFormVariables(strResults.toString(),request); z//check for custom properties...if exist, then apply zif(customProps!=null) { ztmpResponse = this.insertJCSVariables(tmpResponse, customProps); z} zthis.response=tmpResponse; zreturn; z }

10 Some important files zjcs_taglib.tld zweb.xml

11 jcs_taglib.tld z z<!DOCTYPE taglib z PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" z"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> z z 1.0 z 1.1 z jcs z zA custom JSP tag implementation of the JResources.com DB Connector servlet z z query_object z com.jresources.jcs.jcsCustomTag z com.jresources.jcs.jcsCustomTagOutput z A custom JSP tag implementation of the JResources.com DB Connector servlet z z url z true z z outputvariable z true z

12 Web.xml z z<!DOCTYPE web-app z PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" z "http://java.sun.com/j2ee/dtds/web-app_2.2.dtd"> z z JResources.com Database Connector Servlet z zThe JResources.com Database Connector Servlet is a Java zservlet that provides an XML-based interface to JDBC data zsources. With the JResources.com DB connector servlet, zweb developers now have an easy way to query and modify zJDBC databases without writing a line of Java code. z z jdbc_url z jdbc:odbc:guestbook z z The default URL for the guestbook app's database z

13 (continued) z z output z z This is an example of using JCS from a JSP with custom z properties read from the web application's context parameters. z In Tomcat, these are set up in the WEB-INF/web.xml file z zSample output for the guestbook app z z JCS z z com.jresources.servlets.JDBCConnectorServlet z z defaultDriver z z sun.jdbc.odbc.JdbcOdbcDriver z

14 (continued) z z JCS z z *.jcs z z http://www.jresources.com/jcs/jcs_taglib.tld z z /WEB-INF/jcs_taglib.tld z

15 Guestbook application zCreate a SELECT query zAdding and modifying data zGenerating XML output from query zUsing JCS from within a JSP zUsing XSLT with JCS

16

17

18 guestbook.jcs z z jdbc:odbc:guestbook z select * from guestbook order by date z z<![CDATA[ z ztemplates\header.inc z z Guestbook Entries (as of #system.date#) z z Visitor z z Date z z #fname# #lname# z z #date# z

19 (Continued) z ztemplates\footer.inc z z]]> z z<![CDATA[ z z There are no entries in the guestbook. z z]]> z z HTML z

20

21 guestbook_xml_default.jcs z z jdbc:odbc:guestbook z select * from guestbook order by date z

22

23 guestbook_xml.jcs z z text/xml z jdbc:odbc:guestbook z select * from guestbook order by date z z<![CDATA[ z z#comments# z z #date# z #host# z z]]> z

24

25 guestbook.jsp z z<% ztry{ zjcs.processRequest(request, getServletConfig().getServletContext().getRealPath("/samples/guestbook/guestbook.jcs")); z} zcatch(Exception e){} zif(jcs.getResponseType()==com.jresources.jcs.jcsEngine.RESPONSE_REDIRECT) { zresponse.sendRedirect(jcs.getResponse()); z}else { z%> z z<% z} z%>

26

27 guestbook_tag.jsp z

28

29 guestbook_custom.jsp z z<% zjava.util.Properties prop = new java.util.Properties(); zprop.put("jdbc_url", "jdbc:odbc:guestbook"); zprop.put("output", "This is an example of using JCS from a JSP with custom properties passed from the JSP script to the JCS engine"); ztry{ zjcs.processRequest(request, prop, getServletConfig().getServletContext().getRealPath("/samples/guestbook/jsp.guestbook.jcs")); z}catch(Exception e){} zif(jcs.getResponseType()==com.jresources.jcs.jcsEngine.RESPONSE_REDIRECT) { zresponse.sendRedirect(jcs.getResponse()); z}else { z%> z z<% z} z%>

30 Jsp.guestbook.jcs z z #jcs.jdbc_url# z select * from guestbook order by date z z<![CDATA[ z ztemplates/header.inc z z Guestbook Entries (as of #system.date#) z z Visitor z z Date z

31 z #fname# #lname# z z #date# z z #jcs.output# z ztemplates/footer.inc z z]]> z z HTML z

32

33 guestbook_xsl.jsp z z<% z/* zThis sample uses Xalan 1.1. Download it from http://xml.apache.org. Ensure that xalan.jar and xerces.jar are in Tomcat's classpath. z*/ ztry{ z z XSLTProcessor processor = XSLTProcessorFactory.getProcessor(); z processor.process(new XSLTInputSource(new java.io.StringReader(guestbook.toString())), new XSLTInputSource("file:///" + getServletConfig().getServletContext().getRealPath("/samples/guestbook/guestbook.xsl")), new XSLTResultTarget(out)); z}catch(Exception e) { z%> zAn error occurred processing your operation... z<% z} z%>

34

35 guestbook_tag_custom.jsp z

36

37 guestbook_submit.jcs z z jdbc:odbc:guestbook z select * from guestbook order by date z z<![CDATA[ z ztemplates\header.inc z z Sign the Guestbook: z z Your first name: z Your last name: z Your comments: z <input type="reset" value="Reset" z name="B2"> z

38 (continued) z z Other Guestbook Entries (as of #system.date#) z z Visitor z z Date z z #fname# #lname# z z #date# z ztemplates\footer.inc z z]]> z z HTML z

39 guestbook_add.jcs z z jdbc:odbc:guestbook z zINSERT INTO guestbook ("ID", "fname", "lname", "comments", "host", "date") VALUES ('#system.UID#',' #form.fname# ',' #form.lname# ', ' #form.comments# ', '#CGI.REMOTE_ADDR#', Now()) z z guestbook.jcs z error_page.htm z

40

41

42 guestbook_delete.jcs z z jdbc:odbc:guestbook z zdelete from guestbook where ID = '#form.ID#' z z guestbook.jcs z error_page.htm z

43 guestbook_view_entry.jcs z z jdbc:odbc:guestbook z select * from guestbook where ID = '#form.ID#' z z<![CDATA[ z ztemplates\header.inc z z #fname# #lname#'s Guestbook Entry z Comments: #comments# z Date entered: #date# z Originating Host: #host# z Delete this entry z ztemplates\footer.inc z z]]> z z HTML z

44

45 Summary zReusable zaccess the record in relational database via JDBC without Java zrapid creation of XML data server zportable

46 Questions ?


Download ppt "An XML-Based JDBC Connector Servlet Framework Geng Tang 03/05/2001."

Similar presentations


Ads by Google