Datasource j2ee proyecto web eclipse

0

Por admin | Para la categoría de java j2ee | noticia del 03-12-2009

Habíamos visto en anteriores post como acceder a una base de datos con jdbc y con ibatis en esta ocasición veremos la creación y conexión del mismo ejemplo mediante un datasource

Se mostraran por pantalla los datos almacenados en la base de datos libros_jdbc para su tabla libros

Enlace al ejemplo de j2ee jdbc j2ee jdbc

Configuración del fichero web.xml

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>
	conexionjdbc</display-name>
	<resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/Conexiondatasource</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>

Imagen del fichero de context.xml

contexto

Fichero de configuración del contexto context.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/Conexiondatasource" docBase="Conexiondatasource"
        debug="5" reloadable="true" crossContext="true">
 
    <!-- maxActive: Maximum number of dB connections in pool. Make sure you
         configure your mysqld max_connections large enough to handle
         all of your db connections. Set to -1 for no limit.
         -->
 
    <!-- maxIdle: Maximum number of idle dB connections to retain in pool.
         Set to -1 for no limit.  See also the DBCP documentation on this
         and the minEvictableIdleTimeMillis configuration parameter.
         -->
 
    <!-- maxWait: Maximum time to wait for a dB connection to become available
         in ms, in this example 10 seconds. An Exception is thrown if
         this timeout is exceeded.  Set to -1 to wait indefinitely.
         -->
 
    <!-- username and password: MySQL dB username and password for dB connections  -->
 
    <!-- driverClassName: Class name for the old mm.mysql JDBC driver is
         org.gjt.mm.mysql.Driver - we recommend using Connector/J though.
         Class name for the official MySQL Connector/J driver is com.mysql.jdbc.Driver.
         -->
 
    <!-- url: The JDBC connection url for connecting to your MySQL dB.
         -->
 
  <Resource name="jdbc/Conexiondatasource" auth="Container" type="javax.sql.DataSource"
               maxActive="100" maxIdle="30" maxWait="10000"
               username="root" password="root" driverClassName="com.mysql.jdbc.Driver"
               url="jdbc:mysql://localhost:3306/libros_jdbc"/>
 
</Context>

Imagen resultado de la ejecución

conexiondatasource

Código de la clase Conexionpool.java

1
2
3
4
5
6
7
8
9
10
11
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
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
package conexion;
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import java.io.PrintWriter;
 
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
 
 
import javax.naming.InitialContext;
import java.sql.Statement;
import javax.sql.DataSource;
import javax.naming.NamingException;
 
 
/**
 * Servlet implementation class for Servlet: Conexionpool
 *
 */
 public class Conexionpool extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
 
   private Connection conexion = null;
   private Statement sentenciaSql = null;
   private ResultSet  resultado = null;
 
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public Conexionpool() {
		super();
 
 
	}   	
 
	public void init() throws ServletException { 
 
		try
		{
		InitialContext ctx = new InitialContext();
		DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/Conexiondatasource");
		if ( ds == null ) {
			System.out.print("Data source no encontrado!");
			}
		this.conexion = ds.getConnection();
		//creamos una sentencia sql
		this.sentenciaSql = conexion.createStatement();			
 
		}
		catch (NamingException e)
		{
			System.out.println(e.getMessage());
		}
 
		catch ( SQLException e)
		{
			System.out.println(e.getMessage());	
		}
 
 
 
 
	}
 
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
 
        response.setContentType("Text/html");
 
		PrintWriter salida = response.getWriter();
 
		try
		{
			//ejecutamos la sentencia de selección de los campos menos el id
			resultado = sentenciaSql.executeQuery(" SELECT titulo, autor, tematica  FROM libros;");
 
			//preparamos la salida para una nueva página
			salida.print("<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN' 'http://www.w3.org/TR/html4/loose.dtd'>\n");
			salida.print("<html>\n");
		        salida.print("<head><title>Mostramos los datos</title></head>\n");
		        salida.print("<link rel='stylesheet' type='text/css' href='css/estilo.css'/>\n");	
			salida.println("<body>");
			salida.print("<div id='contenedor'>\n");
			salida.print("<h2> Libros datasource </h2>");
			salida.println("<table id='tabla'>");
			salida.println("<tr>");
			salida.println("<th>titulo</th><th>autor</th><th>tematica</th>");
			salida.println("</tr>");
			while ( resultado.next())
			{   
 
				salida.println("<tr>");				
				salida.println("<td class='impar'>"+resultado.getString("titulo")+"</td>");
				salida.println("<td class='par'>"+resultado.getString("autor")+"</td>");
				salida.println("<td class='impar'>"+resultado.getString("tematica")+"</td>");
				salida.println("</tr>");
			}
 
			   salida.println("</table>");
			   salida.print("<div id='pie'>");
			   salida.print("<p> www.railsymas.com </p>");
			   salida.print("</div>");
			   salida.print("</div>\n");
			   salida.println("</body>");
			   salida.println("</html>");
 
		}
 
		catch( 	SQLException e )
		{
			salida.println("Excepcion Sql : "+ e.getMessage());
		}
 
 
 
 
 
	}  	
 
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}   	  	    
}

Escribe un comentario