DataSource & DriverManager
In this part of the JEE 5 tutorials, we will compare DataSource object with the DriverManager object.In this chapter, we will have two examples. One of the examples will use a DriverManager, the other one will use a DataSource to connect to a MySQL database.
mysql> describe books; +--------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +--------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | author | varchar(30) | YES | | NULL | | | title | varchar(40) | YES | | NULL | | | year | int(11) | YES | | NULL | | | remark | varchar(100) | YES | | NULL | | +--------+--------------+------+-----+---------+----------------+ 5 rows in set (0.27 sec)We will use a books table.
DriverManager
The first example will use a DriverManager.
style.css
* { font-size: 12px; font-family: Verdana } td { border: 1px solid #ccc; padding: 3px } th { border: 1px solid #ccc; padding: 3px; background: #009999; color: white }This is the stylesheet file.
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>DriverManager</servlet-name> <servlet-class>com.zetcode.DriverManagerExample</servlet-class> </servlet> <servlet-mapping> <servlet-name>DriverManager</servlet-name> <url-pattern>/DriverManager</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> </web-app>In the web.xml configuration file, we configure our servlet.
DriverManagerExample.java
package com.zetcode; import java.io.*; import java.net.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.*; import javax.servlet.http.*; public class DriverManagerExample extends HttpServlet { static final String url = "jdbc:mysql://localhost:3306/books"; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, "root", ""); Statement stmt = con.createStatement(); ResultSet result = stmt.executeQuery("SELECT * FROM books"); out.print("<html>"); out.print("<head>"); out.print("<title>Servlet NewServlet</title>"); out.print("<link rel='stylesheet' href='style.css' type='text/css'>"); out.print("</head>"); out.print("<body>"); out.print("<table>"); out.print("<tr>"); out.print("<th>Author</th>"); out.print("<th>Title</th>"); out.print("<th>Year</th>"); out.print("<th>Remark</th>"); out.print("</tr>"); while (result.next()) { out.print("<tr>"); out.print("<td>"); out.print(result.getString("author")); out.print("</td>"); out.print("<td>"); out.print(result.getString("title")); out.print("</td>"); out.print("<td>"); out.print(result.getString("year")); out.print("</td>"); out.print("<td>"); out.print(result.getString("remark")); out.print("</td>"); out.print("</tr>"); } con.close(); } catch (SQLException ex) { Logger.getLogger(DriverManagerExample.class.getName()).log( Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(DriverManagerExample.class.getName()).log( Level.SEVERE, null, ex); } finally { out.close(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }The example will display a books table from the books database in a html table.
static final String url = "jdbc:mysql://localhost:3306/books";We provide the connection url. This is an url for a MySQL database.
Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection(url, "root", "");We load the driver and get the connection to the database.
Figure: DriverManager
DataSource
The next example uses the DataSource facility. We use the same data.
style.css
* { font-size: 12px; font-family: Verdana } td { border: 1px solid #ccc; padding: 3px } th { border: 1px solid #ccc; padding: 3px; background: #009999; color: white }Simple stylesheet.
resin-web.xml
<web-app xmlns="http://caucho.com/ns/resin"> <!-- - Configures the database. - - jndi-name specifies the JNDI name - type specifies the driver class - path is a driver-specific configuration parameter --> <database> <jndi-name>jdbc/mysql</jndi-name> <driver> <type>com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource</type> <url>jdbc:mysql://localhost:3306/books</url> <user>root</user> <password></password> </driver> </database> <!-- - Configures the initialization servlet. The bean-style init - it used to look up the JNDI DataSource in the configuration file. --> <servlet> <servlet-name>datasource</servlet-name> <servlet-class>com.zetcode.DataSourceExample</servlet-class> <init> <data-source>${jndi:lookup('jdbc/mysql')}</data-source> </init> </servlet> <servlet-mapping> <url-pattern>/DataSource</url-pattern> <servlet-name>datasource</servlet-name> </servlet-mapping> </web-app>This is the resin-web.xml configuration style. It is Resin specific. It overrides the configuration in the web.xml file. In our file, we configure the datasource and the servlet mapping.
The DataSource configuration is done within the <database> tags. We specify the driver type, connection url, user name and password.
In our example, we use the JNDI (The Java Naming and Directory Interface) API. This API is used to look up data and objects via a name. The JNDI enables separation of resource configuration from the application code.
DataSourceExample.java
package com.zetcode; import java.io.*; import java.net.*; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.*; import javax.servlet.http.*; import javax.sql.DataSource; public class DataSourceExample extends HttpServlet { private DataSource _ds = null; public void setDataSource(DataSource ds) { _ds = ds; } public void init() throws ServletException { if (_ds == null) { throw new ServletException("datasource not properly configured"); } } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { Connection conn = _ds.getConnection(); Statement stmt = conn.createStatement(); ResultSet result = stmt.executeQuery("SELECT * FROM books"); out.print("<html>"); out.print("<head>"); out.print("<title>DataSource</title>"); out.print("<link rel='stylesheet' href='style.css' type='text/css'>"); out.print("</head>"); out.print("<body>"); out.print("<table>"); out.print("<tr>"); out.print("<th>Author</th>"); out.print("<th>Title</th>"); out.print("<th>Year</th>"); out.print("<th>Remark</th>"); out.print("</tr>"); while (result.next()) { out.print("<tr>"); out.print("<td>"); out.print(result.getString("author")); out.print("</td>"); out.print("<td>"); out.print(result.getString("title")); out.print("</td>"); out.print("<td>"); out.print(result.getString("year")); out.print("</td>"); out.print("<td>"); out.print(result.getString("remark")); out.print("</td>"); out.print("</tr>"); } out.print("</table>"); out.println("</body>"); out.println("</html>"); result.close(); stmt.close(); conn.close(); } catch (SQLException ex) { Logger.getLogger(DataSourceExample.class.getName()).log( Level.SEVERE, null, ex); } finally { out.close(); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }The example will display a books table from the books database in a html table too.
public void setDataSource(DataSource ds) { _ds = ds; }The method is called by the Resin application server at configuration time.
public void init() throws ServletException { if (_ds == null) { throw new ServletException("datasource not properly configured"); } }The
init()
method checks whether the datasource was configured properly.
Connection conn = _ds.getConnection();We get the connection from the datasource object.
This chapter of the JEE tutorials was about DataSource and DriverManager.
Figure: DataSource
In this chapter we have briefly mentioned DataSource and DriverManager.
Exceptions
In this part of the JEE tutorials we will work with Exceptions.In our next example, we will work with both kinds of exceptions. We will react to three kind of system exceptions and one kind of application exception. We will have system errors and application warnings. To inform user about exceptions, we will create message windows. This will be created using css and JavaScript. The example is quite complicated. Works on Firefox and Opera.
style.css
* { font-size: 12px; font-family: Verdana } form { margin-top: 5%; } input, textarea { border: 1px solid #ccc } .message { position: absolute; display: none; background: #577580; width: 235px; height: 150px; cursor: move; padding: 5px; color: white; } .header { font-weight: bolder; margin-bottom: 7px; } a#close { position: absolute; display: block; border: 1px solid #ccc; padding: 2px; width: 60px; bottom: 20px; left: 88px; text-decoration: none; font-weight: bolder; color: white; }This is a stylesheet applied to our example. The
.message
class creates a message window for us. It is initially not visible.
The .header
class creates header of the message window.
The close
selector defines style for an anchor, that will
serve as our close button.
util.js
var savedTarget = null; var orgCursor = null; var dragOK = false; var dragXoffset = 0; var dragYoffset = 0; function showError() { if (msg.style.display == 'block') { msg.style.display = 'none'; msg.innerHTML = ''; } else { msg.style.display = 'block'; msg.innerHTML = '<b>Error</b><p>'; var string = error + '</p><center>'; string += '<a id="close" href="javascript:showError()">'; string += 'close</a></center>'; msg.innerHTML += string; } } function showWarning() { if (msg.style.display == 'block') { msg.style.display = 'none'; msg.innerHTML = ''; } else { msg.style.display = 'block'; msg.innerHTML = '<b>Warning</b><p>'; var string = warning + '</p><center>'; string += '<a id="close" href="javascript:showWarning()">'; string += 'close</a></center>'; msg.innerHTML += string; } } function moveHandler(e){ if (e == null) { e = window.event } if (e.button <= 1 && dragOK){ savedTarget.style.left = e.clientX - dragXoffset + 'px'; savedTarget.style.top = e.clientY - dragYoffset + 'px'; return false; } } function cleanup(e) { document.onmousemove = null; document.onmouseup = null; savedTarget.style.cursor = orgCursor; dragOK = false; } function dragHandler(e){ var htype='-moz-grabbing'; if (e == null) { e = window.event; htype = 'move';} var target = e.target != null ? e.target : e.srcElement; orgCursor = target.style.cursor; if (target.className == "message") { savedTarget = target; target.style.cursor = htype; dragOK = true; dragXoffset = e.clientX - parseInt(msg.style.left); dragYoffset = e.clientY - parseInt(msg.style.top); document.onmousemove = moveHandler; document.onmouseup = cleanup; return false; } } document.onmousedown = dragHandler;The util.js file will have most of the javascript code. The
showWarning()
function displays the
application warning message window, the showError()
displays
the system error message window. The moveHandler()
,
cleanup()
and dragHandler()
fuctions enable to move the window with the mouse pointer. The javascript
code is adapted from hunlock.com.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Exceptions</title> <link rel="stylesheet" href="style.css" type="text/css"> <script src="util.js" type="text/javascript" ></script> <script type="text/javascript"> <%! String error; String warning; String okm; %> <% error = (String) request.getAttribute("ErrorMessage"); warning = (String) request.getAttribute("Warning"); okm = (String) request.getAttribute("OkMessage"); %> var error = "<%=error%>"; var warning = "<%=warning%>"; var okm = "<%=okm%>"; </script> </head> <body> <h2>Exceptions</h2> <center> <form action="ProcessServlet" > <table> <tr> <td>From</td> <td><input type="text" name="from"></td> </tr> <tr> <td>To</td> <td><input type="text" name="to"></td> </tr> <tr> <td>Subject</td> <td><input type="text" name="subject"></td> </tr> <tr> <td>Message</td> <td><textarea cols="25" rows="8" name="message"></textarea></td> </tr> </table> <br> <input type="submit" value="submit"> </form> </center> <div id="messageID" class="message"></div> <script type="text/javascript"> msg = document.getElementById('messageID'); msg.style.top = (window.innerHeight-235) / 2; msg.style.left = (window.innerWidth-150) / 2; </script> <% if (error != null) { %> <script> showError(); </script> <% } else if (warning != null) { %> <script type="text/javascript"> showWarning(); </script> <% } else if (okm != null) { out.print(okm); } %> </body> </html>The index.jsp file creates a html form. It is also a place, where message windows will pop up.
var error = "<%=error%>"; var warning = "<%=warning%>"; var okm = "<%=okm%>";Here we can see, how data from java code is passed to javascript. These JavaScript variables will determine, which message window will appear on the screen.
<div id="messageID" class="message"></div>The message window is a simple div tag. It is initially not visible. If an exception occurs, the div is made visible by the javascript code. The visibility of the tag is changed from none to block.
msg = document.getElementById('messageID'); msg.style.top = (window.innerHeight-235) / 2; msg.style.left = (window.innerWidth-150) / 2;This javascript code positions the window into the middle of the screen.
<% if (error != null) { %> <script> showError(); </script> <% } else if (warning != null) { %> <script type="text/javascript"> showWarning(); </script> <% } else if (okm != null) { out.print(okm); } %>This embedded java code decides, which message window to display. If no exception occurs, we simply output All OK message.
Figure: Message Window
Process.java
package com.zetcode; import java.io.*; import java.net.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import javax.servlet.*; import javax.servlet.http.*; import com.mysql.jdbc.CommunicationsException; public class Process extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); Connection con; String url = "jdbc:mysql://localhost:3306/"; try { this.testForm(request); Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(url, "root", ""); con.close(); } catch (CommunicationsException ex) { request.setAttribute("ErrorMessage", "Cannot connect to database"); RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); } catch (SQLException ex) { request.setAttribute("ErrorMessage", ex.getMessage()); RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); } catch (ClassNotFoundException ex) { request.setAttribute("ErrorMessage", "MySQL driver not found"); RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); } catch (UserException ex) { request.setAttribute("Warning", ex.getMessage()); RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); } request.setAttribute("OkMessage", "All OK"); RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); } public void testForm(HttpServletRequest request) throws UserException { String from = (String) request.getParameter("from"); String to = (String) request.getParameter("to"); String subject = (String) request.getParameter("subject"); String message = (String) request.getParameter("message"); if (from.isEmpty() || to.isEmpty() || subject.isEmpty() || message.isEmpty() ) { throw new UserException("Form not correctly filled"); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }This is the servlet, where the exceptions arise. It does nothing in particular, only enables us the test various error conditions. The servlet will react to four different exceptions:
CommunicationsException
,
SQLException
, ClassNotFoundException
and UserException
. We can test the CommunicationsException
by shutting down the MySQL database. The SQLException will arise, when we e.g.
provide invalid password to the database user. If we do not include MySQL driver
library , we will have the ClassNotFoundException. Finally, the UserExeption will
occur, when at least one of the form parameters is empty.
sudo /etc/init.d/mysql stopHere we stop the MySQL database server.
} catch (CommunicationsException ex) { request.setAttribute("ErrorMessage", "Cannot connect to database"); RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp"); dispatcher.forward(request, response); }This exception will react to the system error, caused by the lost connection. The code sets an attribute to the request and forwards back to the index.jsp page.
public void testForm(HttpServletRequest request) throws UserException { String from = (String) request.getParameter("from"); String to = (String) request.getParameter("to"); String subject = (String) request.getParameter("subject"); String message = (String) request.getParameter("message"); if (from.isEmpty() || to.isEmpty() || subject.isEmpty() || message.isEmpty() ) { throw new UserException("Form not correctly filled"); } }The
testForm()
method will test if all parameters
are set. If not, we throw an UserExeption.
UserException.java
package com.zetcode; public class UserException extends Exception { public UserException(String msg) { super(msg); } public String getMessage() { return super.getMessage(); } }The UserException is an application exception. This exception will cause the warning message windows.
In this chapter we have briefly mentioned exceptions.
Java Beans
In this part of the JEE tutorials, we will talk about client side Java Beans components. This is a technology directly supported by the JavaServer pages.Technically Java Beans are Java classes conforming to particular conventions. A bean can be a particular specialized Java Swing component (e.g. a chart ) that can be plugged into the application, a server side component called Enterprise Java Bean, EJB or a client side component. In this chapter, we will talk about client side Java Beans.
- The class must have a no-argument public constructor
- The properties of the Bean must be accessible using accessor methods
- The class should be serializable
A Bean
In the Bean example we have a form that sends data to a jsp page. The JSP page will output those data. This time we do not use scriptlets or expressions, but we use Java Beans technology.
style.css
* { font-size: 12px; font-family: Verdana } input { border: 1px solid #ccc }This is a css file for the code example.
index.css
<%@page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <title>Bean</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body> <form action="show.jsp" method="post"> <table> <tr> <td>Author</td> <td><input type="text" name="author"></td> </tr> <tr> <td>Title</td> <td><input type="text" name="title"></td> </tr> <tr> <td>Available</td> <td><input type="checkbox" name="available" value="true"></td> </tr> </table> <br> <input type="submit" value="submit"> </form> </body> </html>Here we define a simple form. We have three input boxes. The author, title and the availability of the book. The parameters are sent to the show.jsp page.
MyBean.java
package com.zetcode; import java.io.Serializable; public class MyBean implements Serializable { private String author = ""; private String title = ""; private String available = ""; public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getAvailable() { return available; } public void setAvailable(String available) { this.available = available; } }This is our bean. It is a simple java class. Has no argument constructor. It implements the
Serializable
interface. We have three properties of a Bean.
Each of the property names begins with small letter. Each of the accessor methods is
public. The properties are private.
The accessor methods consists of two parts. The first part begins with get,
set or is and the second part
is the name of the property with first letter capitalized.
show.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <title>Show</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body> <jsp:useBean id="MyBean" class="com.zetcode.MyBean" scope="page"> <jsp:setProperty name="MyBean" property="author" param="author" /> <jsp:setProperty name="MyBean" property="title" param="title" /> <jsp:setProperty name="MyBean" property="available" param="available" /> </jsp:useBean> <jsp:getProperty name="MyBean" property="author"/><br> <jsp:getProperty name="MyBean" property="title"/><br> <jsp:getProperty name="MyBean" property="available"/> </body> </html>The show.jsp page sets the parameters into the bean and prints them.
<jsp:useBean id="MyBean" class="com.zetcode.MyBean" scope="page"> ... </jsp:useBean>We use this element to declare that our JSP page will use a bean. The id parameter identifies the bean. The class parameter is a fully clasified classname. The scope parameters sets the bean validity for this page only.
<jsp:getProperty name="MyBean" property="author"/><br>This element retrieves the author property from the bean.
Another Bean
Next we modify our previous example a bit.
show.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%> <html> <head> <title>Show</title> <link rel="stylesheet" href="style.css" type="text/css"> </head> <body> <jsp:useBean id="MyBean" class="com.zetcode.MyBean" scope="page"> <jsp:setProperty name="MyBean" property="*"/> </jsp:useBean> <jsp:getProperty name="MyBean" property="author"/><br> <jsp:getProperty name="MyBean" property="title"/><br> <jsp:getProperty name="MyBean" property="available"/> </body> </html>We slightly change the show.jsp page.
<jsp:setProperty name="MyBean" property="*"/>This element will automatically fill the bean properties with the request parameters. This works only if the parameter names match the bean property names.
In this chapter we have briefly mentioned Java Beans.
కామెంట్లు లేవు:
కామెంట్ను పోస్ట్ చేయండి