Sei sulla pagina 1di 5

[This reading continues the reading accessingDB-UsingPHP * * * ********** * * *

Getting data from MySQL using Java servlets


Here are two examples. Later in the term, Ill proved a far more robust example that youll nd helpful in real life.

In this example, line numbers are used to help you follow the code. Dont type them in your own file. Be encouraged to try this code. Use a text editor (not a word processing program) and type the file line by line. You must name the file the same name as that in the public class statement [line x]. Note the location of your file when you save it. Then start a terminal window and navigate to that folder so the folder that contains your file is the current working folder (in Unix). Enter the command javac yourfileName.java and press the enter key. For example, this program is called xmlGenericServlet and so is stored in a file called xmlGenericServlet.java. When compiling, type javac xmlGenericServlet.java and press the enter key. If the Java Compiler was not installed on the computer, youll see an error message. If the compiler is installed and you made a typo, youll see an error message that includes the number of the line in your code that is wrong. Fix it and try again! Ultimately youll have code that works. but we have a few things to do first before running it live on the web server. [Advanced or adventurous students may have installed Apache on their own computer (its built into the Mac but you can download it, too, on Macs and any computer). See the instructions about setting up your own web server software from the class homepage. Comments and notes about your program thats stored in the program are shielded from the compiler by using either // (double slashes) for a single line or /* */ for a single or multiple lines of comments. To run this program on the server, your user account will have to have read/write permissions on the folder. Usually creating a subfolder under your publicly-viewable folder on the webserver is the best way to store files. Permissions on the server are not controlled by the professor - if theres a problem speak to the GSLIS Lab Staff.
/* 1 2 3 4 5 6 IMPORT import import import import import import THE LIBRARIES NEEDED FOR THIS PROJECT */ java.net.*; java.sql.*; java.awt.*; java.awt.event.*; java.io.*; javax.servlet.*;

/* DECLARE THE CLASS AND WHAT YOUR CLASSES IS BUILT UPON (extends) */ 8 public class xmlGenericServlet extends GenericServlet { 9 /* declare the variables needed to connect and communicate with SQL */ 10 Connection connection; 11 Statement statement;

12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58

/* ************************************** /* Variables for database access /* ************************************** */ String dbName = "userAccts"; String userName = ""; String password = ""; String realPath = ""; String server = ""; public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { /* -------------------------------------/* What is the server's name? /* -------------------------------------server = request.getServerName(); realPath = getServletContext().getRealPath("/"); // looks like /var/gslis/tomcat5/webapps/xmlDemo/ // NOTE! DOES NOT WORK WITH SYMBOLIC LINKS! and Simmons GSLIS // USES symbolic links so we have to be klunky and hard code! /* ************************************** /* Open connection back to source (browser) /* Get ready to send (to print) data in browser /* ************************************** */ response.setContentType("application/xml"); PrintWriter pw = response.getWriter(); /* /* /* /* /* /* /* /* /* /* /* /* /* --------------------------------------NOTE!!! There are much more efficient ways of parsing XML (using XMLFactories) and better ways of sending data via the server - ServletOutputStream this code is just an example emphasizing DB connectivity Well have an example of this, too. --------------------------------------- */

************************************** Hardcode the XML declaration and our tags. Print the tag; get the data from a database. ************************************** */

/* --------------------------------------/* Send the XML declaration and our root /* --------------------------------------- */ pw.println("<?xml version=\"1.0\"?>"); pw.println("<document>"); /* ************************************** /* Connect to a MySQL database table /* ************************************** */ try {

59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
100 101 102 103 104 105 106 107

/* /* /* /* /* /* /* /* /* /* /* /* /*

THIS IS IMPORTANT */ --------------------------------------Load the correct driver so the web server can communicate with the database For MS Access use: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); connection = DriverManager.getConnection "jdbc:odbc:tableName", "username", "password" Replace "tableName" with the real table; Replace "username" and "password" with the real ones. --------------------------------------- */

Class.forName("com.mysql.jdbc.Driver").newInstance(); /* --------------------------------------/* Create a connection to the database: /* Here were using jdbc to connect to mysql. /* Use odbc if youre using MS Access - but youll need /* a bridge between odbc and jdbc (not described here) /* We prepare for the data by creating a Statement /* that is the bridge for our SQL request to communicate /* with the database itself. /* --------------------------------------- */ connection = DriverManager.getConnection("jdbc:mysql://" + server +":3306/"+dbName, userName, password ); statement = connection.createStatement(); ResultSet rs = statement.executeQuery("SELECT * FROM students"); /* /* /* /* /* --------------------------------------cycle through all the results. Wrap them in xml and print on browser but you could easily use html: e.g., <b> + rs.getString(lname) + </b>); --------------------------------------- */

while (rs.next()) { pw.println("<student>" + rs.getString(1) + "</student>"); } /* --------------------------------------/* No more data; show final tag. /* --------------------------------------- */ pw.print("</document>"); } catch (Exception e) { pw.println("An error has occurred."); if (e instanceof SQLException) { SQLException sqlex3 = (SQLException)e; pw.print("SQL Error code = "+sqlex3.getErrorCode()); } /* --------------------------------------/* Close the connections. /* --------------------------------------- */ } finally {

108 109 110 111 112 113 114 115 } 116 }

if (connection != null) { try { connection.close(); } catch (Exception onclose) { } }

********************* Finally, both students of relational databases and of XML need to know that both technologies work together for real-world information system solutions. Above we passed a single parameter (season=Summer). We can pass other data. In this example, the data passed are names of les (.xml and .xsl) that are processed the same way on the web server as DB transactions are performed - the servlet does all the work. Note, too, that XML may rely on temporary les the same way that many database solutions require creating a temporary database table, integrating those results with html or xml, sending them back to the user (or writing to a le), and then deleting the temporary les.
import javax.xml.transform.TransformerFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import java.io.File; import java.io.PrintWriter; import java.io.IOException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyTransform extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { /* NOTE: because gslis.simmons.edu uses symbolic links we can't use the function that lets our code be independent of the server name: String realPath = getServletContext().getRealPath("/"); So, in this situation, we must actually hardcode the path! */ String realPath ="/gslis/tomcat5/webapps/courses/";

res.setContentType("text/html"); String docName = req.getParameter("docName"); String sheetName = req.getParameter("sheetName"); TransformerFactory factory; Transformer transformer; File oldFile = null; File xslFile = null; PrintWriter out = null; StreamSource oldStream = null; StreamSource xslStream = null; StreamResult newStream = null; factory = TransformerFactory.newInstance(); try { oldFile = new File(realPath+docName); // oldFile should look like "myle.xml" oldStream = new StreamSource(oldFile); xslFile = new File(realPath+sheetName); // sheetName should look like "mysheet.xsl" xslStream = new StreamSource(xslFile); out = res.getWriter(); newStream = new StreamResult(out); transformer = factory.newTransformer(xslStream); transformer.transform(oldStream, newStream); } catch (TransformerException e) { System.out.println(e.getMessage()); } } } filename: accessingDB-UsingJava.rtf Updated: Jan 2, 2012 [Original: April 11, 2009, 3 pm; Updated Jan 2, 2012]

ZZZZZZZZZZZZZZZZZ
5

Potrebbero piacerti anche