简体   繁体   English

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

[英]Connecting Database using Java Servlet, JSP, and AJAX

I am building a dynamic webpage for a Web Development course I've been attending for the last 6 months. 我正在为过去6个月来参加的Web开发课程构建一个动态网页。 Currently I have a dynamic web project in which I need to have database content dynamically change on a bootstrap website I have built. 当前,我有一个动态Web项目,需要在已建立的引导网站上动态更改数据库内容。 I have to use JSP, AJAX and Java Servlets to accomplish this. 我必须使用JSP,AJAX和Java Servlet来完成此任务。

The issue I am having seems to be server side. 我遇到的问题似乎在服务器端。 The website is for Posting and reading of Jokes and when I try to post a random joke to one of the pages from the database when a button (id="getRandom") is pressed, nothing seems to happen. 该网站用于发布和阅读笑话,当我按下按钮(id =“ getRandom”)尝试将随机笑话发布到数据库中的某个页面时,似乎什么也没发生。

This is my code so far: 到目前为止,这是我的代码:

JSP: 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: package controller; 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: 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');

                        });             

                    });

                }); 

This is the log error I get in the browser console when I run it with Tomcat: Screen Shot 这是在使用Tomcat运行时在浏览器控制台中出现的日志错误: 屏幕截图

I have been trying to find a solution to this for a week now and its driving me mad. 一个星期以来,我一直在寻找解决方案,这让我发疯。 Any help would be appreciated. 任何帮助,将不胜感激。 Thanks in advance. 提前致谢。

Your error in provided screen shot is very clear. 您提供的屏幕截图中的错误非常清楚。 You declared servlet method as post but accessing as get. 您将servlet方法声明为post,但将其作为get访问。 You can not access post method directly in the browser. 您不能直接在浏览器中访问post方法。

I mean Your class contains public void doPost( method. 我的意思是您的课程包含public void doPost(方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM