使用Java Servlet,JSP和AJAX连接数据库

时间:2015-12-09 14:31:00

标签: java jquery ajax jsp servlets

我正在为我过去6个月一直参加的网络发展课程建立一个动态网页。目前我有一个动态的Web项目,我需要在我构建的引导程序网站上动态更改数据库内容。我必须使用JSP,AJAX和Java Servlet来实现这一目标。

我遇到的问题似乎是服务器端。该网站用于发布和阅读笑话,当我按下按钮(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

我一直试图找到解决方案一个星期,它让我发疯。任何帮助,将不胜感激。提前致谢。

1 个答案:

答案 0 :(得分:0)

提供的屏幕截图中的错误非常清楚。您将servlet方法声明为post但访问为get。您无法直接在浏览器中访问post方法。

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