Está en la página 1de 10

Documento Proyecto En jboss se ha registrado el pool con los siguientes datos . en server/default/deploy mysqliisoftejemplo-ds.xml <?xml version="1.0" encoding="UTF-8"?> <!

-- $Id: mysql-ds.xml 63175 2007-05-21 16:26:06Z rrajesh $ --> <!-- Datasource config for MySQL using 3.0.9 available from: http://www.mysql.com/downloads/api-jdbc-stable.html --> <datasources> <local-tx-datasource> <jndi-name>jdbc/dciisoftejemplo</jndi-name> <connectionurl>jdbc:mysql://localhost:3306/iisoftejemplo</connection-url> <driver-class>com.mysql.jdbc.Driver</driver-class> <user-name>root</user-name> <password></password> <exception-sorter-classname>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</ exception-sorter-class-name> <!-- should only be used on drivers after 3.22.1 with "ping" support <valid-connection-checker-classname>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionCh ecker</valid-connection-checker-class-name> --> <!-- sql to call when connection is created <new-connection-sql>some arbitrary sql</new-connection-sql> --> <!-- sql to call on an existing pooled connection when it is obtained from pool - MySQLValidConnectionChecker is preferred for newer drivers <check-valid-connection-sql>some arbitrary sql</check-validconnection-sql> --> <!-- corresponding type-mapping in the standardjbosscmpjdbc.xml --> <metadata> <type-mapping>mySQL</type-mapping> </metadata> </local-tx-datasource> </datasources>

Copiar el driver del mysql al server a la carpeta lib. En el proyecto se estn creando varios archivos .xml con el fin de ordenar el aplicativo Y permitir el uso del pool de conexiones. El archivo web.xml queda asi <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> <web-app> <description>ejemplo</description> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/dataAccessContext.xml /WEB-INF/applicationContext.xml </param-value> </context-param> <listener> <listenerclass>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>ejemplo</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>ejemplo</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping>

<session-config> <session-timeout> 30 </session-timeout> </session-config>

<welcome-file-list> <welcome-file>redirect.jsp</welcome-file> </welcome-file-list> </web-app>

El archivo donde se configura el pool queda asi dataAccessContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"> <!-- DataAccessContext tiene la declaracion de la conexion. usar el jndi declarado en el servidor - declaracion del sqlMapClient que puede tener cualquier nombre - declaracion de los daos --> <!-- paso 1 estamos recuperando la conexion creada en el servidor. Para esp usamos el jndiName jdbc/dciisoftejemplo cuando se trata de jboss el jndi se recupera poniendo la palabra java./ adelante de tal modo que queda asi: java:/jdbc/dciisoftejemplo en el weblogic se recupera asi: --> jdbc/dciisoftejemplo

<bean id="cineDataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>java:/jdbc/dciisoftejemplo</value>

</property> </bean>

<!-- paso 2 una vez recuperado el jndi declaramos en sqlMapclient SqlMapConfig.xml guarda la declaracion de la lista de xmls de ibatis el dataSource es el recuperado en el paso 1 --> <bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean"> <property name="configLocation" value="WEB-INF/SqlMapConfig.xml"/> <property name="dataSource" ref="cineDataSource"/> </bean>

<!-- Paso 3: declaracion del DAO usa al sqlMapClient declarado en el paso2 --> <bean id="prodDao" class="pack1.dao.ProductoDaoIbatis"> <property name="sqlMapClient" ref="sqlMapClient"/> </bean>

</beans>

El archivos SqlMapConfig.xml tiene algunos cambios para permitir el uso de namespace. ( esto motiv algunos cambios en los archivos de implementacin de los daos con el ibatis) <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE sqlMapConfig PUBLIC "-//iBATIS.com//DTD SQL Map Config 2.0//EN" "http://www.ibatis.com/dtd/sql-map-config-2.dtd"> <sqlMapConfig> <!-errorTracingEnabled="true" activar el log de errores cacheModelsEnabled="true" activar el soporte del cache useStatementNamespaces="true" Activar el modo namespace --> <settings errorTracingEnabled="true" cacheModelsEnabled="true" useStatementNamespaces="true"/>

<sqlMap resource="pack1/ibatis/Producto.xml" /> </sqlMapConfig>

El archivo applicationContext.xml queda asi <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

<bean id="productoService" class="pack1.service.ProductoServiceImpl"> <property name="proddao" ref="prodDao"/> </bean> </beans> El archivo ejemplo-servlet.xml ( es el equivalente del dispatcher-servlet) queda asi: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> <!-- cineController y cinePruebaController son los ID de la declaracion de los constrolles -->

<bean id="urlHandlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"> <property name="mappings"> <value> /prod.htm=productoController /otro.htm=otroController </value> </property> </bean> <!-- cuando se llama a un controller le pasaremos un parametro llamado action el cual tendra como valor el nombre del metodo que queremos ejecutar http://localhost:8080/ProyEjemplo/prueba.htm?action=nombreDeMetodo y defaultMethod es el nombre del metodo que se ejecuta por defecto ejemplo podemos llamar al metodo de la validacion de usuario --> <bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver"> <property name="paramName"> <value>action</value> </property> <property name="defaultMethodName"> <value>consulta1</value> </property> </bean> <bean id="productoController" class="pack1.controller.ProductoController"> <property name="methodNameResolver" ref="methodNameResolver"/> <property name="prodservice" ref="productoService"/> </bean> <bean id="otroController" class="pack1.controller.OtroController"> <property name="methodNameResolver" ref="methodNameResolver"/> <property name="prodservice" ref="productoService"/> </bean> <bean id="xmlViewResolver" class="org.springframework.web.servlet.view.XmlViewResolver"> <property name="order" value="0"/> <property name="location" value="/WEB-INF/ejemplo-views.xml"/> </bean> </beans>

Y el archivo ejemplo-view.xml queda listo para poner alguna informacin <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> </beans>

En los daos de ibatis se estn usando los contextos

ejemplo:

getSqlMapClientTemplate().insert("Producto.ibatis_registrarProducto", bean);

El controller de prueba esta quedando as: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package pack1.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.web.servlet.mvc.multiaction.MultiActionController; import pack1.service.ProductoService; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.util.Assert; import org.springframework.validation.Validator; import org.springframework.web.servlet.ModelAndView; import pack1.bean.ProductoBean; /** * * @author alumno */ public class ProductoController extends MultiActionController { // agregar el service private ProductoService prodservice ; //agregar metodo ser para prodservice

public void setProdservice(ProductoService prodservice) { this.prodservice = prodservice; } public ModelAndView consultaNombre (HttpServletRequest request, HttpServletResponse response){ String nombre = request.getParameter("nombre"); List<ProductoBean> lista = prodservice.buscarProductoPorNombre(nombre); request.getSession().setAttribute("listaprod", lista); ModelAndView mav = new ModelAndView("pintaDatos");//llamar a la pagina de salida return mav; } public ModelAndView consulta1 (HttpServletRequest request, HttpServletResponse response){ ModelAndView mav = new ModelAndView("consultaProdTable");//llamar a la pagina de salida return mav; } public ModelAndView prodAdd(HttpServletRequest request, HttpServletResponse response, ProductoBean prod) { System.out.println("prodAdd:"+prod); List<ProductoBean> productos=null; try { if ( prod!=null && prod.getNombre()!=null && prod.getNombre().length()>0){ // llamar al service para agregar prodservice.agregar(prod); } prod= null; productos= prodservice.buscarTodoslosProductos(); //llamar al service para recuperar la informacion } catch (Exception ex) { ex.printStackTrace(); } request.getSession().setAttribute("productos",productos); ModelAndView mav = new ModelAndView("pagprod");//llamar a la pagina de salida mav.getModel().put("prod", new ProductoBean()); return mav; }

La pagina de agregar datos ser: <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <html> <head><title>producto</title></head> <body> <form:form action="prod.htm?action=prodAdd" method="POST" commandName="prod"> <h4>Producto Nuevo</h4> <table border="1"> <tr> <td>Codigo</td> <td><form:input path="codigo"/></td> </tr> <tr> <td>Nombre</td> <td><form:input path="nombre"/></td> </tr> <tr> <td>stockMinimo</td> <td><form:input path="stockMinimo"/></td> </tr> <tr> <td>stockActual</td> <td><form:input path="stockActual"/></td> </tr> <tr> <td>Precio</td> <td><form:input path="precio"/></td> </tr> <tr> <td>codCategoria</td> <td><form:input path="codCategoria"/></td> </tr>

</table>

<input type="hidden" name="method" value="prodAdd"/><br/> <input type="submit" /> </form:form>

</table>

</body> </html>

Y registrar en el redirect.jsp <%-Views should be stored under the WEB-INF folder so that they are not accessible except through controller process. This JSP is here to provide a redirect to the dispatcher servlet but should be the only JSP outside of WEB-INF. --%> <%@page contentType="text/html" pageEncoding="UTF-8"%> <a href="prod.htm?action=prodAdd" >agrega Producto</a> <br/> <a href="prod.htm?action=consulta1" >Consultar Productos</a> <br/>

También podría gustarte