从Servlet打印出来

时间:2014-03-07 16:30:09

标签: java javascript mysql servlets

我想从MySQL数据库中打印出一列。我有一个日历系统,您可以在其中选择“从”日期“到”日期。当您选择时间段时,它应该从MySQL数据库打印出COLUMN“Allday_hours”。我正在使用javascript,AJAX和JSON。这是在调用我的servlet。有连接,所以工作字体,但我真的不知道如何从我的servlet打印出列。是某种System.out.println("")我必须使用,还是?

    package WorkPackage;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/getHoursSQL")
public class getHoursSQL extends HttpServlet{

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException{

        String connectionURL = "jdbc:mysql://localhost/NekiWork";
        Connection connection=null;
        String all_day_hours = null;                            // new code
        res.setContentType("text/html;charset=UTF-8");          // new code
        res.getWriter().write(all_day_hours);                   // new code

        try {

            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(connectionURL, "root", ""); 
            String sql = "SELECT *, (Day_hours + (Day_minutes / 100)) AS Allday_hours FROM Workdata";
            PreparedStatement pst = connection.prepareStatement(sql);
            ResultSet rs = pst.executeQuery(sql);

            if(rs.next()){                                      // new code
                 all_day_hours = rs.getString("Allday_hours");  // new code
            }                                                   // new code
            pst.close();
        }
        catch(ClassNotFoundException e){

            System.out.println("Couldn't load database driver: " + e.getMessage());
        }
        catch(SQLException e){
            System.out.println("SQLException caught: " + e.getMessage());
        }
        catch (Exception e){
            System.out.println(e);
        }
        finally {

            try {
                if (connection != null) connection.close();
            }
            catch (SQLException ignored){
                System.out.println(ignored);
            }
        }
    }
}

使用Javascript:

<form>
        <input id="startDate" />
        <input id="endDate" />
    </form>
    <div id="result"></div>
    <script>

    $(function(){
        $("#startDate").datepicker({
            dateFormat: 'yy-mm-dd',
            onSelect: function(dateText,inst){
                alert(dateText);

                $.ajax({
                      url: "../getHoursSQL",
                      type: "post",
                      data: JSON,
                      success: function(data){
                          alert("success");
                          $("#result").html(data);

                      },
                      error:function(){
                          alert("failure");
                          $("#result").html('there is error while submit');
                      }  
                    });
            }
        });
    });

    $(function(){
            $("#endDate").datepicker({
                dateFormat: 'yy-mm-dd',
                onSelect: function(dateText,inst){
                    alert(dateText);

                    $.ajax({
                          url: "../getHoursSQL",
                          type: "post",
                          data: JSON,
                          success: function(data){
                              alert("success");
                              $("#result").html(data);
                          },
                          error:function(){
                              alert("failure");
                              $("#result").html('there is error while submit');
                          }  
                        });
                }
            });
        });

</script>

有错误的视频: https://www.youtube.com/watch?v=UzdvQ4B9clw

3 个答案:

答案 0 :(得分:0)

您需要做的是替换

pst.executeUpdate(sql);

ResultSet rs = pst.execute(sql);
String all_day_hours = null;
if(rs.next()){
     all_day_hours = rs.getString("Allday_hours");
}

然后通过

将此值写入servlet的out stream
res.setContentType("text/html;charset=UTF-8");
res.getWriter().write(all_day_hours);

并替换

success: function(){

success: function(data){

希望这有帮助。

答案 1 :(得分:0)

使用setContentType作为“application / JSON”而不是text / HTML。此外,如果要从数据库获取值数组,则必须使用GSON并将对象转换为JSON对象。然后使用out.println并将转换后的JSON对象传递给它。希望这会有所帮助。

答案 2 :(得分:0)

这应该是正确的代码:

package WorkPackage;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;

@WebServlet("/getHoursSQL")
public class getHoursSQL extends HttpServlet{

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) 
        throws ServletException, IOException{

        String connectionURL = "jdbc:mysql://localhost/NekiWork";
        Connection connection=null;
                                // new code
                    // new code

        try {

            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(connectionURL, "root", ""); 
            String sql = "SELECT *, (Day_hours + (Day_minutes / 100)) AS Allday_hours FROM Workdata";
            PreparedStatement pst = connection.prepareStatement(sql);

            ResultSet rs = pst.executeQuery(sql);
            String all_day_hours = null;    

            if(rs.next()){                                      
                 all_day_hours = rs.getString("Allday_hours");  
            }       
            res.setContentType("text/html;charset=UTF-8");          
            res.getWriter().write(all_day_hours);   
            pst.close();

        }
        catch(ClassNotFoundException e){

            System.out.println("Couldn't load database driver: " + e.getMessage());
        }
        catch(SQLException e){
            System.out.println("SQLException caught: " + e.getMessage());
        }
        catch (Exception e){
            System.out.println(e);
        }
        finally {

            try {
                if (connection != null) connection.close();
            }
            catch (SQLException ignored){
                System.out.println(ignored);
            }
        }
    }
}