Advertisement
Guest User

Untitled

a guest
Oct 17th, 2016
283
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.00 KB | None | 0 0
  1. <%@page contentType="text/html" pageEncoding="UTF-8"%>
  2. <!DOCTYPE html>
  3. <%
  4. String usuario = "";
  5. HttpSession sesionOk = request.getSession();
  6. if (sesionOk.getAttribute("usuario") == null) { //Verifica que este logueado
  7. %>
  8. <jsp:forward page="login.jsp"/>
  9. <%
  10. } else {
  11. usuario = (String)sesionOk.getAttribute("usuario");
  12. }
  13. %>
  14.  
  15. <html>
  16. <head>
  17. <meta charset="UTF-8">
  18.  
  19. <link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,700" rel="stylesheet">
  20.  
  21. <link rel="stylesheet" type="text/css" href="editar.css">
  22. <title>Legislatura Pro Cordoba Sur</title>
  23. </head>
  24.  
  25. <body>
  26.  
  27. <header> MENU -> <%=usuario%> - <a href="cerrarsesion.jsp">Cerrar Sesion</a> </header>
  28.  
  29. <div id="mainContainer">
  30.  
  31. <FORM id="formulario" action="agregarComentarioServlet?codigo=<%= request.getParameter("codigo") %>" method="POST">
  32. <table id="tablaForm">
  33. <tr>
  34. <td class="labelD">Fecha:</td> <td><input type="date" size=30 value="" name="fecha"/></td>
  35. </tr>
  36. <tr>
  37. <td class="label">Texto:</td><td colspan="3"><input type="text" size=80 value="" name="texto"/></td>
  38. </tr>
  39. <tr>
  40. <td class="label">Agregar adjunto</td><td><input type="file" size=30 value="" name="filename"/></td>
  41. </tr>
  42. <tr>
  43. <td colspan="4" class="Cabecera"><input class="boton" type="submit" name="agregar" value="Agregar"/></td>
  44. </tr>
  45.  
  46. </table>
  47.  
  48. </FORM>
  49. <br>
  50. <br>
  51. <br> ${requestScope.error}
  52.  
  53. </div>
  54.  
  55. <footer>Pro Cordoba Sur - 2016</footer>
  56.  
  57. </body>
  58. </html>
  59.  
  60. import com.mysql.jdbc.Connection;
  61. import java.io.File;
  62. import java.io.IOException;
  63. import java.sql.DriverManager;
  64. import java.sql.PreparedStatement;
  65. import java.sql.SQLException;
  66. import javax.servlet.ServletException;
  67. import javax.servlet.annotation.MultipartConfig;
  68. import javax.servlet.annotation.WebServlet;
  69. import javax.servlet.http.HttpServlet;
  70. import javax.servlet.http.HttpServletRequest;
  71. import javax.servlet.http.HttpServletResponse;
  72. import javax.servlet.http.HttpSession;
  73. import javax.servlet.http.Part;
  74.  
  75. /**
  76. *
  77. * @author Facu
  78. */
  79. @WebServlet(urlPatterns = {"/agregarComentarioServlet"})
  80. @MultipartConfig(fileSizeThreshold=1024*1024*10, // 10 MB
  81. maxFileSize=1024*1024*50, // 50 MB
  82. maxRequestSize=1024*1024*100) // 100 MB
  83. public class agregarComentarioServlet extends HttpServlet {
  84. private static final String UPLOAD_DIR = "archivos";
  85. Connection connection;
  86.  
  87. protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  88. throws ServletException, IOException {
  89. HttpSession sesionOk = request.getSession();
  90.  
  91. if ( (sesionOk.getAttribute("usuario") == null) ){//Verifica que este logueado
  92. request.getRequestDispatcher("login.jsp").forward(request, response);
  93. }
  94.  
  95. if(request.getParameter("codigo")==null){
  96. String error="<div class=error>Intentando agregar un comentario sin codigo</div>";
  97. request.setAttribute("error", error);
  98. request.getRequestDispatcher("menuServlet").forward(request, response);
  99. }
  100.  
  101. try {
  102. connectDB();
  103. } catch (SQLException ex) {
  104. String error="<div class=error>Error al conectar con la base de datos</div>";
  105. request.setAttribute("error", error);
  106. request.getRequestDispatcher("menu.jsp").forward(request, response);
  107.  
  108. } catch (ClassNotFoundException ex) {
  109. String error="<div class=error>Driver no cargado</div>";
  110. request.setAttribute("error", error);
  111. request.getRequestDispatcher("menu.jsp").forward(request, response);
  112. }
  113.  
  114. subirArchivo(request, response);
  115.  
  116. PreparedStatement preparedStmt=null;
  117. try {
  118.  
  119. String sql="INSERT INTO comentario (fecha, codigo, texto) VALUES (?,?,?)";
  120.  
  121. String fecha= request.getParameter("fecha");
  122. String codigoStr=request.getParameter("codigo");
  123. int codigo=Integer.parseUnsignedInt(codigoStr);
  124. String texto=request.getParameter("texto");
  125.  
  126. preparedStmt = connection.prepareStatement(sql);
  127. preparedStmt.setString(1, fecha);
  128. preparedStmt.setInt(2, codigo);
  129. preparedStmt.setString(3, texto);
  130.  
  131. preparedStmt.execute();
  132. request.getRequestDispatcher("editarServlet?codigo="+codigo).forward(request, response);
  133.  
  134.  
  135. } catch (SQLException ex) {
  136. String error="<div class=error>La consulta es incorrecta</div>";
  137. request.setAttribute("error", error);
  138. request.getRequestDispatcher("menu.jsp").forward(request, response);
  139. }catch (NumberFormatException ex){
  140. String error="<div class=error>El estado es invalido</div>";
  141. request.setAttribute("error", error);
  142. request.getRequestDispatcher("menuServlet").forward(request, response);
  143. }finally{
  144. try { if (preparedStmt != null) preparedStmt.close(); } catch (Exception e) {};
  145. try { if (connection != null) connection.close(); } catch (Exception e) {};
  146. }
  147. }
  148.  
  149. void connectDB() throws SQLException, ClassNotFoundException{
  150.  
  151. Class.forName("com.mysql.jdbc.Driver"); //Carga el driver
  152.  
  153. String url = "jdbc:mysql://127.0.0.1:3306/expediente";
  154. String username = "root";
  155. String password = "123456";
  156.  
  157. connection = (Connection) DriverManager.getConnection(url, username, password);
  158.  
  159. }
  160.  
  161. String subirArchivo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
  162. try {
  163. // gets absolute path of the web application
  164. String applicationPath = request.getServletContext().getRealPath("");
  165. // constructs path of the directory to save uploaded file
  166. String uploadFilePath = applicationPath + File.separator + UPLOAD_DIR;
  167. // creates the save directory if it does not exists
  168. File fileSaveDir = new File(uploadFilePath);
  169. if (!fileSaveDir.exists()) {
  170. fileSaveDir.mkdirs();
  171. }
  172. String fileName = null;
  173. //Get all the parts from request and write it to the file on server
  174. for (Part part : request.getParts()) {
  175. fileName = (String) getFileName(part);
  176. part.write(uploadFilePath + File.separator + fileName);
  177. }
  178. return fileName;
  179.  
  180. } catch (IOException | ServletException ex) {
  181. String error="<div class=error>Error al subir el archivo</div>";
  182. request.setAttribute("error", error);
  183. request.getRequestDispatcher("menu.jsp").forward(request, response);
  184. }
  185.  
  186. return "";
  187. }
  188.  
  189. private String getFileName(Part part) {
  190. String contentDisp = part.getHeader("content-disposition");
  191. String[] tokens = contentDisp.split(";");
  192. for (String token : tokens) {
  193. if (token.trim().startsWith("filename")) {
  194. return token.substring(token.indexOf("=") + 2, token.length()-1);
  195. }
  196. }
  197. return "";
  198. }
  199.  
  200.  
  201. // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  202. /**
  203. * Handles the HTTP <code>GET</code> method.
  204. *
  205. * @param request servlet request
  206. * @param response servlet response
  207. * @throws ServletException if a servlet-specific error occurs
  208. * @throws IOException if an I/O error occurs
  209. */
  210. @Override
  211. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  212. throws ServletException, IOException {
  213. processRequest(request, response);
  214. }
  215.  
  216. /**
  217. * Handles the HTTP <code>POST</code> method.
  218. *
  219. * @param request servlet request
  220. * @param response servlet response
  221. * @throws ServletException if a servlet-specific error occurs
  222. * @throws IOException if an I/O error occurs
  223. */
  224. @Override
  225. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  226. throws ServletException, IOException {
  227. processRequest(request, response);
  228. }
  229.  
  230. }
  231.  
  232. java.lang.IllegalStateException: No puedo reenviar después de que la respuesta se haya llevado a cabo.
  233. agregarComentarioServlet.processRequest(agregarComentarioServlet.java:73)
  234. agregarComentarioServlet.doPost(agregarComentarioServlet.java:168)
  235. javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
  236. javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
  237. org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement