Guest User

Untitled

a guest
Nov 16th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.44 KB | None | 0 0
  1. package com.soa.entities;
  2.  
  3. public class Client {
  4.  
  5. private int id;
  6. private String name;
  7. private double savings;
  8.  
  9. public Client() {
  10.  
  11. }
  12.  
  13. public Client(int id, String name, double savings) {
  14. this.id = id;
  15. this.name = name;
  16. this.savings = savings;
  17. }
  18.  
  19. public int getId() {
  20. return id;
  21. }
  22.  
  23. public void setId(int id) {
  24. this.id = id;
  25. }
  26.  
  27. public String getName() {
  28. return name;
  29. }
  30.  
  31. public void setName(String name) {
  32. this.name = name;
  33. }
  34.  
  35. public double getSavings() {
  36. return savings;
  37. }
  38.  
  39. public void setSavings(double savings) {
  40. this.savings = savings;
  41. }
  42.  
  43. }
  44.  
  45. package com.soa.dao;
  46.  
  47. import java.sql.Connection;
  48. import java.sql.DriverManager;
  49. import java.sql.SQLException;
  50.  
  51. public class ConnectionStackOverflow {
  52.  
  53. private final static String user = "root";
  54. private final static String password = "";
  55.  
  56. public static Connection getConexion() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
  57. Class.forName("com.mysql.jdbc.Driver");
  58. Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/homebanking" , user, password);
  59. return connection;
  60. }
  61.  
  62. public static void closeConnection() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
  63. getConexion().close();
  64. }
  65. }
  66.  
  67. package com.soa.controllers;
  68.  
  69. import java.sql.Connection;
  70. import java.sql.PreparedStatement;
  71. import java.sql.ResultSet;
  72. import java.sql.Statement;
  73.  
  74. import com.soa.dao.ConnectionStackOverflow;
  75. import com.soa.entities.Client;
  76.  
  77. public class AccountController {
  78.  
  79. /* Método para insertar un cliente a la DB */
  80. public static void insertClient(String name, String lastname, double savings) {
  81. Connection connection = null;
  82. /* Intentamos conectarnos */
  83. try {
  84. connection = ConnectionStackOverflow.getConexion();
  85.  
  86. /* Si no es nula que entre al método que nos facilita realizar la insercción */
  87. if (connection != null) {
  88. PreparedStatement ps;
  89. String sql = "INSERT INTO accounts(name, lastname, savings) VALUES(?,?,?)";
  90. ps = connection.prepareStatement(sql);
  91. ps.setString(1, name);
  92. ps.setString(2, lastname);
  93. ps.setDouble(3, savings);
  94. ps.executeUpdate();
  95. ps.close();
  96. System.out.println("Query executed");
  97. } else {
  98. System.out.println("Connection appears to be null");
  99. }
  100. } catch (Exception error) {
  101. System.out.println("Cannot even connect");
  102. error.getMessage();
  103. error.printStackTrace();
  104. }
  105. }
  106.  
  107. /*
  108. * Método para retornar un cliente por su id , este es que seguramente se usaría
  109. * en una app de Escritorio, llegando el id por un campo hidden
  110. */
  111. public static Client retriveClient(int id) {
  112. Connection connection = null;
  113.  
  114. String name = null;
  115. double savings = 0;
  116. Client client = null;
  117.  
  118. try {
  119. connection = ConnectionStackOverflow.getConexion();
  120.  
  121. if (connection != null) {
  122. Statement st;
  123. String sql = "SELECT * FROM accounts WHERE id=" + id;
  124. st = connection.createStatement();
  125. ResultSet rs = st.executeQuery(sql);
  126.  
  127. /*
  128. * Mientras haya un resultado en la tabla le decimos que nos lo traiga y que a
  129. * su vez grabe las variables recuperadas en name y savings, y por último lo
  130. * agregamos a un cliente nuevo
  131. */
  132. while (rs.next()) {
  133. name = rs.getString("name");
  134. savings = rs.getDouble("savings");
  135. client = new Client(id, name, savings);
  136. }
  137. /* Lo probamos por consola para ver si funcionó */
  138. System.out.println(client.getSavings());
  139. System.out.println("Query executed");
  140. } else {
  141. System.out.println("Connection appears to be null");
  142. }
  143. } catch (Exception error) {
  144. System.out.println("Cannot even connect");
  145. error.getMessage();
  146. error.printStackTrace();
  147. }
  148. return client;
  149. }
  150.  
  151. /*
  152. * Esta consulta no es recomendada ya que lo ideal es realizar la consulta sobre
  153. * el id y en este caso lo estoy haciendo sobre el name y lastname, va a ser
  154. * untema tuyo como solucionarlo
  155. */
  156. public static double getPersistedSavings(String name, String lastname) {
  157. Connection connection = null;
  158. double savings = 0;
  159. Client client = null;
  160. try {
  161. connection = ConnectionStackOverflow.getConexion();
  162. /* Si la conexión no es nula entonces que pase al métodos de averiguación de datos */
  163. if (connection != null) {
  164. Statement st;
  165. String sql = "SELECT savings FROM accounts WHERE name='" + name + "' AND lastname='" + lastname + "' ";
  166. st = connection.createStatement();
  167. ResultSet rs = st.executeQuery(sql);
  168.  
  169. /* Sólo queremos los savings o saldo, usamos el constructor vacío y le seteamos el valor recuperado */
  170. while (rs.next()) {
  171. savings = rs.getDouble("savings");
  172. client = new Client();
  173. client.setSavings(savings);
  174. }
  175. System.out.println(client.getSavings());
  176. System.out.println("Query executed");
  177. } else {
  178. System.out.println("Connection appears to be null");
  179. }
  180. } catch (Exception error) {
  181. System.out.println("Cannot even connect");
  182. error.getMessage();
  183. error.printStackTrace();
  184. }
  185. return savings;
  186. }
  187.  
  188. }
  189.  
  190. package com.soa.servlets;
  191.  
  192. import java.io.IOException;
  193. import java.io.PrintWriter;
  194.  
  195. import javax.servlet.ServletException;
  196. import javax.servlet.http.HttpServlet;
  197. import javax.servlet.http.HttpServletRequest;
  198. import javax.servlet.http.HttpServletResponse;
  199. import javax.servlet.http.HttpSession;
  200.  
  201. import com.soa.controllers.AccountController;
  202.  
  203. public class InsertClientServlet extends HttpServlet {
  204. private static final long serialVersionUID = 1L;
  205.  
  206. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  207. throws ServletException, IOException {
  208.  
  209. try {
  210.  
  211. /* Recuperamos los datos de los inputs del jsp */
  212. String name = request.getParameter("name");
  213. String lastname = request.getParameter("lastname");
  214. String savings = request.getParameter("savings");
  215.  
  216. /* Parseamos el String y lo pasamos a double */
  217. double doubleSavings = Double.parseDouble(savings);
  218.  
  219. /* LLamamos al método que inserta los datos a la DB */
  220. AccountController.insertClient(name, lastname, doubleSavings);
  221.  
  222. /*
  223. * Además de haberlo insertado creamos una session y le agremos los siguientes
  224. * atributos, name, lastname, savings
  225. */
  226. HttpSession session = request.getSession(false);
  227. session.setAttribute("name", name);
  228. session.setAttribute("lastname", lastname);
  229. session.setAttribute("savings", doubleSavings);
  230.  
  231. /*
  232. * Cuando todo termina que nos derive a otra web donde vamos a consultar los
  233. * savings por datos persistidos y por pasamanos de sessiones
  234. */
  235. getServletConfig().getServletContext().getRequestDispatcher("/querySavings.jsp").forward(request, response);
  236.  
  237. } catch (Exception error) {
  238. error.getMessage();
  239. error.printStackTrace();
  240. }
  241.  
  242. }
  243.  
  244. }
  245.  
  246. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  247. pageEncoding="ISO-8859-1"%>
  248. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  249. <html>
  250. <head>
  251. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  252. <title>Insert title here</title>
  253. </head>
  254.  
  255. <script type="text/javascript">
  256.  
  257. function send() {
  258. var frm = document.frmInsertClient;
  259. frm.submit();
  260. }
  261. </script>
  262.  
  263. <body>
  264. <h1>Insertar Cliente</h1>
  265.  
  266. <form action="InsertClientServlet" method="get" name="frmInsertClient">
  267. <table>
  268. <tr>
  269. <td><label>Nombre: </label></td>
  270. <td><input type="text" name="name" /></td>
  271. </tr>
  272. <tr>
  273.  
  274. <td><label>Apellido: </label></td>
  275. <td><input type="text" name="lastname" /></td>
  276. </tr>
  277. <tr>
  278. <td><label>Saldo: </label></td>
  279. <td><input type="number" name="savings" /></td>
  280. </tr>
  281. <tr>
  282. <td><input type="button" value="boton" onclick="send()" /></td>
  283. </tr>
  284. </table>
  285. </form>
  286.  
  287. </body>
  288. </html>
  289.  
  290. package com.soa.servlets;
  291.  
  292. import java.io.IOException;
  293. import java.io.PrintWriter;
  294. import javax.servlet.ServletException;
  295. import javax.servlet.http.HttpServlet;
  296. import javax.servlet.http.HttpServletRequest;
  297. import javax.servlet.http.HttpServletResponse;
  298. import javax.servlet.http.HttpSession;
  299.  
  300. import com.soa.controllers.AccountController;
  301.  
  302. public class QuerySavingsServlet extends HttpServlet {
  303. private static final long serialVersionUID = 1L;
  304.  
  305. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  306. throws ServletException, IOException {
  307.  
  308. try {
  309. /* Grabados en session */
  310. HttpSession session = request.getSession(false);
  311. PrintWriter pw = response.getWriter();
  312. pw.println("Este saldo es que escribimos en la pantallas pasadas y que lo grabamos en memoria Session");
  313. pw.println("****************************** " + session.getAttribute("savings")
  314. + " **************************************");
  315.  
  316. /* Consultados en la Base de Datos, información persistida */
  317. String name = (String) session.getAttribute("name");
  318. String lastname = (String) session.getAttribute("lastname");
  319. double persistedSavings = AccountController.getPersistedSavings(name, lastname);
  320. pw.println("Este saldo es el que está persistido en la DB y que consultamos por medio una consulta");
  321. pw.println("****************************** " + persistedSavings
  322. + " **************************************");
  323.  
  324. } catch (Exception error) {
  325. error.printStackTrace();
  326. }
  327. }
  328.  
  329. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  330. throws ServletException, IOException {
  331.  
  332. }
  333.  
  334. }
  335.  
  336. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  337. pageEncoding="ISO-8859-1"%>
  338. <%@ page import="com.soa.entities.Client"%>
  339. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  340. <html>
  341. <head>
  342. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  343. <title>Averiguar saldo</title>
  344. </head>
  345.  
  346. <script type="text/javascript">
  347.  
  348. function send() {
  349. var frm = document.frmSavings;
  350. frm.submit();
  351. }
  352. </script>
  353. <body>
  354.  
  355. <h1>Averiguar saldo</h1>
  356.  
  357. <%
  358. session.getAttribute("name");
  359. session.getAttribute("savings");
  360. session.getAttribute("lastname");
  361. %>
  362. Esta es la sessión de <% out.print(session.getAttribute("name")); %><br>
  363.  
  364. <form action="QuerySavingsServlet" method="get" name="frmSavings">
  365. <input type="hidden" name="id" value=<% out.print(session.getAttribute("name")); %> /> <br>
  366. <input type="text" value=<% out.print(session.getAttribute("savings")); %>> <input type="button" value="Averiguar Saldo" onclick="send()" />
  367. </form>
  368. </body>
  369. </html>
  370.  
  371. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  372. xmlns="http://java.sun.com/xml/ns/javaee"
  373. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
  374. id="WebApp_ID" version="3.0">
  375. <display-name>StackOverflowWeb</display-name>
  376. <welcome-file-list>
  377. <welcome-file>index.html</welcome-file>
  378. <welcome-file>index.htm</welcome-file>
  379. <welcome-file>index.jsp</welcome-file>
  380. <welcome-file>default.html</welcome-file>
  381. <welcome-file>default.htm</welcome-file>
  382. <welcome-file>default.jsp</welcome-file>
  383. </welcome-file-list>
  384. <servlet>
  385. <servlet-name>InsertClientServlet</servlet-name>
  386. <servlet-class>com.soa.servlets.InsertClientServlet</servlet-class>
  387. </servlet>
  388. <servlet-mapping>
  389. <servlet-name>InsertClientServlet</servlet-name>
  390. <url-pattern>/InsertClientServlet</url-pattern>
  391. </servlet-mapping>
  392.  
  393. <servlet>
  394. <servlet-name>QuerySavingsServlet</servlet-name>
  395. <servlet-class>com.soa.servlets.QuerySavingsServlet</servlet-class>
  396. </servlet>
  397. <servlet-mapping>
  398. <servlet-name>QuerySavingsServlet</servlet-name>
  399. <url-pattern>/QuerySavingsServlet</url-pattern>
  400. </servlet-mapping>
  401. </web-app>
Add Comment
Please, Sign In to add comment