【问题标题】:Print out from Servlet从 Servlet 打印
【发布时间】:2014-04-10 22:04:59
【问题描述】:

我想从我的 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

【问题讨论】:

    标签: java javascript mysql servlets


    【解决方案1】:

    你需要做的是替换

    pst.executeUpdate(sql);
    

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

    然后将此值写入servlet的输出流

    res.setContentType("text/html;charset=UTF-8");
    res.getWriter().write(all_day_hours);
    

    然后替换

    success: function(){
    

    success: function(data){
    

    希望这会有所帮助。

    【讨论】:

    • 你好。非常感谢你的帮助。我可以看到你说的所有东西 Sanjeev。我试图将信息放入,但现在我的 javascript 出现错误,但我会尝试使用它。非常感谢:-)
    • 当然 .. 玩,玩得开心编码 :)
    • 你好。我不知道你是否还在。我玩过它,但是当我运行程序时仍然失败。我已经编辑了我的问题,并添加了一个指向 youtube 视频的链接,其中包含我得到的错误。你能看出为什么吗?非常感谢。向 Mads 致以最诚挚的问候。
    • 我试着把:String all_day_hours = null; up,否则我得到一个编译器错误:-/
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      这应该是正确的代码:

      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);
                  }
              }
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-23
        • 1970-01-01
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        相关资源
        最近更新 更多