2015-12-09 76 views
0

我正在爲過去6個月參加的Web開發課程構建動態網頁。目前,我有一個動態Web項目,我需要在已建立的引導程序網站上動態更改數據庫內容。我必須使用JSP,AJAX和Java Servlets來實現這一點。使用Java Servlet,JSP和AJAX連接數據庫

我遇到的問題似乎是服務器端。該網站是用於發佈和閱讀笑話,當我嘗試從按下按鈕(id =「getRandom」)按下時向數據庫中的某個頁面發佈隨機笑話時,似乎沒有任何事情發生。

這是我到目前爲止的代碼:

JSP:

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
      pageEncoding="ISO-8859-1"%> 
      <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
     <!DOCTYPE html> 
     <html lang="en"> 
     <head> 
      <meta charset="utf-8"> 
      <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <title>Vicoteka | Random</title> 

      <!-- Bootstrap --> 
      <link href="css/bootstrap.css" rel="stylesheet"> 
      <link rel="stylesheet" href="css/stil.css"> 

      <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> 
      <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> 
     <!--[if lt IE 9]> 
       <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> 
       <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> 
       <![endif]--> 

      </head> 
      <body> 
      <nav class="navbar navbar-inverse navbar-fixed-top"> 
       <div class="container"> 
        <!-- Brand and toggle get grouped for better mobile display --> 
        <div class="navbar-header"> 
         <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#defaultNavbar1"><span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span></button> 
         <a class="navbar-brand" href="#"><img src="img/brand.png" alt="Vicoteka Logo"></a> </div> 

         <!-- Collect the nav links --> 
         <div class="collapse navbar-collapse" id="defaultNavbar1"> 
          <ul class="nav navbar-nav pull-right"> 
           <li ><a href="index.jsp">Pocetna<span class="sr-only">(current)</span></a></li> 
           <li class="active"><a href="random.jsp">Random Vic<span class="sr-only">(current)</span></a></li> 

           <li ><a href="vicevi.jsp">Vicevi<span class="sr-only">(current)</span></a></li> 
           <li> <a href="kategorije.jsp" >Kategorije<span class="sr-only">(current)</span></a> 
           </li> 
           <li ><a href="myModal" type="button" data-toggle="modal" data-target="#myModal" id="dugme">Dodaj<span class="sr-only">(current)</span></a></li> 
          </ul> 
          <!-- /.navbar-collapse --> 
         </div> 
         <!-- /.container--> 
        </div> 
       </nav> 

       <section id="random"> 
        <div class="container"> 

         <div class="jumbotron"> 
         <h2>Blic Vic</h2> 

         <div class="problem_text"> 
          <div class="vic"> 
          <span class="lead" id="message">Procitejte svoj random vic</span> 

             </div> 
          <hr> 
          <p> 
           <input class="btn btn-warning btn-xl pull-right" id="getRandom" type="submit" value="random"role="button"/> 
          </p> 
         </div> 
        </div> 

       </div> 
      </section> 
     <c:out value="${vic.text}"></c:out> 
      <footer class="navbar navbar-fixed-bottom"> 
       <div class="row spacer" > 
        <div class="text-center col-md-6 col-md-offset-3"> 
         <p>Copyright &copy; 2015 VICOTEKA - Developed by Dijana Markovic</p> 
        </div> 
       </div> 
      </footer> 

      <!-- Dodaj Vic Prozor (Modal) --> 
      <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> 
       <div class="modal-dialog" role="document"> 
        <div class="modal-content"> 
         <div class="modal-header"> 
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
          <h4 class="modal-title" id="myModalLabel">Dadajte Vas Vic</h4> 
         </div> 
         <div class="modal-body"> 
          <div class="jumbotron"> 
           <div class="container"> 
            <div class="message"> 

             </div> 
             <form method="post" action="ControllerServlet"> 
              <input type="hidden" name="action" value="addNew"/> 

              <div class="form-group"> 
              <label for="title">Title</label> 
              <input type="text" class="form-control" name="title"> 
             </div> 

             <div class="form-group"> 
              <label for="author">Autor</label> 
              <input type="text" class="form-control" name="author"> 
             </div> 

             <div class="form-group row"> 
              <div class="container"> 
               <label for="Kategorija">Kategorija</label> 
               <select class="form-control" name="category"> 
                <option value="mujo_haso">Mujo i Haso</option> 
                <option value="plavuse">Plavuse</option> 
                <option value="panduri">Panduri</option> 
                <option value="maliPerica">Mali Perica</option> 
               </select> 
              </div> 
             </div> 

             <div class="form-group"> 
              <label for="name">Vas Vic</label> 
              <textarea class="form-control" required data-validation-required-message="Niste ukucali vic!" name="text"></textarea> 
             </div> 
            </form> 
           </div> 
          </div> 
         </div> 
         <div class="modal-footer"> 
          <button type="button" class="btn btn-default" data-dismiss="modal">Odkazi</button> 
          <button type="submit" class="btn btn-warning">Sacuvaj</button> 
         </div> 
        </div> 
       </div> 
      </div> 
      <!-- jQuery (necessary for Bootstrap's JavaScript plugins) --> 
      <script src="js/jquery-1.11.2.min.js"></script> 

      <script src="js/ajax.js"></script> 

      <!-- Include all compiled plugins (below), or include individual files as needed --> 
      <script src="js/bootstrap.js"></script> 
     </body> 
     </html> 

的Java Srevlet: 包控制;

  import java.io.IOException; 
      import java.sql.DriverManager; 
      import java.sql.SQLException; 
      import java.util.List; 

      import javax.servlet.ServletConfig; 
      import javax.servlet.ServletContext; 
      import javax.servlet.ServletException; 
      import javax.servlet.annotation.WebServlet; 
      import javax.servlet.http.HttpServlet; 
      import javax.servlet.http.HttpServletRequest; 
      import javax.servlet.http.HttpServletResponse; 

      import com.mysql.jdbc.Connection; 

      import dao.Vic; 
      import service.VicMetode; 

      /** 
      * Servlet implementation class ControllerServlet 
      */ 
      @WebServlet("/ControllerServlet") 
      public class ControllerServlet extends HttpServlet { 
       private static final long serialVersionUID = 1L; 

       private static final String USERNAME = "root"; 
       private static final String PASSWORD = "root"; 
       private static final String CONN_STRING = "jdbc:mysql://localhost:3306/vicevi"; 
       private Connection conn = null; 

       /** 
       * @see Servlet#init(ServletConfig) 
       */ 
       public void init(ServletConfig config){ 

        try { 
         Class.forName("com.mysql.jdbc.Driver"); 
         //connect to the database 
         conn = (Connection) DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD); 
         System.out.println("CONECTED"); 
        } catch (SQLException e) { 
         System.err.println(e); 
        } catch (ClassNotFoundException e) { 

         e.printStackTrace(); 
        } 

       } 

       /** 
       * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
       */ 
       protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
        ServletContext context = ((ServletConfig) request).getServletContext(); 
        context.setAttribute("conn", conn); 

        String action = request.getParameter("action"); 

        System.out.println(action); 

        if(action.equals("addNew")){ 
         String title = request.getParameter("title"); 
         String author = request.getParameter("author"); 
         String category = request.getParameter("category"); 
         String text = request.getParameter("text"); 

         VicMetode vicService = new VicMetode(conn); 
         String message = vicService.addVic(title, author, category, text); 
         request.setAttribute("message", message); 
         request.getRequestDispatcher("index.jsp").forward(request, response); 
        } 

        if(action.equals("loadFirstPage")){ 

         VicMetode vicService = new VicMetode(conn); 
         List<Vic> vicList = vicService.getVicList(); 
         request.getSession().setAttribute("vicList", vicList); 

        } 

        if(action.equals("random")){ 

         VicMetode vicService = new VicMetode(conn); 
         List<Vic> vicList = vicService.getVicList(); 

         int index = (int)(Math.random() * vicList.size() - 1); 

         request.getSession().setAttribute("vic", vicList.get(index)); 


        } 
       } 


       } 

AJAX:

    $(document).ready(function() { 

        $('#getRandom').bind('click',function() { 
         var action = $('#message').val(); 


         $.ajax({ 
          type : 'POST', 
          data : { 

           action : action 

          }, 
          url : 'ControllerServlet', 
         }).success(function(response) { 
          $('#message').load('random.jsp'); 

         });    

        }); 

       }); 

這是日誌錯誤我在瀏覽器控制檯中看到,當我在Tomcat中運行它: Screen Shot

我一直在試圖找到一個解決這個現在一週,它讓我發瘋。任何幫助,將不勝感激。提前致謝。

+0

這個錯誤顯然是在你的控制器中。 500錯誤意味着服務器代碼中存在錯誤。 – unekwu

+0

分別測試您的控制器代碼。轉到http:// localhost:8080/Vicko/ControllerServlet。它應該在瀏覽器中完整地打印錯誤消息。與我們分享該錯誤消息。 – unekwu

+0

這是當我運行控制器時得到的http://prntscr.com/9c5qvk – Deny

回答

0

您提供的屏幕截圖中的錯誤非常明顯。您將servlet方法聲明爲post,但是以get方式訪問。您無法直接在瀏覽器中訪問post方法。

我的意思是你的班級包含public void doPost(方法。

+0

他正在通過POST訪問它。看到他的ajax電話。我不認爲這是問題。這可能是數據庫連接問題,但除非他提供堆棧跟蹤,否則無法知道。 – unekwu

+0

我無法找到catalina.out或stacktrace日誌文件。 – Deny

+0

@unekwu我同意拒絕不提供任何東西,但我從這個屏幕截圖假設http://prntscr.com/9c5qvk – Ghayel