如何将输出从普通java类重定向到httpservlet类

时间:2014-10-16 20:49:26

标签: java servlets

我已拨打HttpServlet课程,让我们的电话为Test。我可以使用HttpServletResponse对象将此类中的任何内容输出到我的html页面中。现在,我有另一个普通的java类,让它调用它Home,在这个类中我需要把东西放到html页面中。不幸的是,即使我尝试从HttpServlet类继承Home并使用HttpServletResponse对象进行输出,它也会产生麻烦。

有没有办法将Home类的输出重定向到Test类?

这是方法doGetof my Test类,它创建home的对象并调用connectToHom()方法进行身份验证。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws  ServletException, IOException {
       String tst = "username"
        tst = new Home();
        tst.connectToHome(tst); 

}

这是类Home的方法connectToHome():

public void connectToHome(String tst){
  -> Try to login using tst,
  connect = Connection.open(tst);

  if(connect.getMessage()!=null){
    System.out.println("-- Error: " + connect.getMessage()); 
    return null;
 }
}

上面的代码可以工作,但它会在控制台上打印出来,而不是在html页面上打印出来。

提前致谢!

1 个答案:

答案 0 :(得分:2)

您需要发送OutputStream参考号。到Home课程:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws  ServletException, IOException {
    String tst = "username"
    tst = new Home();
    tst.connectToHome(tst, response.getOutputStream());   
}


public void connectToHome(String tst, OutputStream out){
  -> Try to login using tst,
  connect = Connection.open(tst);

  if(connect.getMessage()!=null){
    out.print("-- Error: " + connect.getMessage() + "\n"); 
    out.flush();
    return null;
 }
}