Advertisement
Guest User

PostStory.java

a guest
Feb 27th, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.96 KB | None | 0 0
  1. import java.io.*;
  2. import javax.servlet.*;
  3. import javax.servlet.http.*;
  4. import java.sql.*;
  5. import java.text.SimpleDateFormat;
  6. import java.util.Date;
  7. import java.util.*;
  8.  
  9. public class PostStory extends HttpServlet {
  10.  
  11.     private static final String DB_URL = "jdbc:h2:D://Speak Out/database/stories";
  12.     private static final String USER = "";
  13.     private static final String PASS = "";
  14.  
  15.     protected void doPost(HttpServletRequest request,
  16.                           HttpServletResponse response)
  17.             throws ServletException, IOException
  18.     {
  19.         Connection conn = null;
  20.         Statement stmt = null;
  21.  
  22.         try {
  23.             Class.forName("org.h2.Driver");
  24.  
  25.             conn = DriverManager.getConnection(DB_URL, USER, PASS);
  26.             stmt = conn.createStatement();
  27.  
  28.             String title = request.getParameter("txtTitle");
  29.             String story = request.getParameter("txtStory");
  30.             if ((title == "") | (story == "")) {
  31.                 response.sendRedirect("/index.jsp");
  32.                 stmt.close();
  33.                 conn.close();
  34.             }
  35.  
  36.             Date date = new Date();
  37.             SimpleDateFormat dateFormat = new SimpleDateFormat("'Posted on' MMMMMM d',' y 'at' h:mm a",
  38.                     Locale.ENGLISH);
  39.  
  40.             String sql = "INSERT INTO STORIES (title, contents, post_date) VALUES ('"+title+"', " +
  41.                     "'"+story+"', '"+dateFormat.format(date)+"')";
  42.  
  43.             stmt.executeUpdate(sql);
  44.             response.sendRedirect("/index.jsp");
  45.         } catch (Exception e) {
  46.             e.printStackTrace();
  47.         } finally {
  48.             try {
  49.                 if (stmt!=null)
  50.                     conn.close();
  51.             } catch (SQLException ignored) {
  52.             }
  53.             try {
  54.                 if (conn!= null)
  55.                     conn.close();
  56.             } catch (SQLException se) {
  57.                 se.printStackTrace();
  58.             }
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement