2
public class DemoServlet extends HttpServlet {

    public void service(HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {

        //prints out my string
        resp.getOutputStream().write("Hello from servlet\n".getBytes());

        String variable ="VAR";
        //trying to print out variable by this way but doesn't work
        resp.getOutputStream().write("%s\n".getBytes(),variable);
        //doesn't work this way either
        resp.getOutputStream().write("variable is:"+ variable +"something else\n".getBytes());
    }
}

First, I was using PageWriter out= resp.getWriter(); but then I switched to ServletOutputStream because I wanted to print images. Every thing else is OK but:

public void makedbconnection() {
    try {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        Dbcon = DriverManager.getConnection("jdbc:mysql://localhost/test");
    } catch(Exception idc) {
       //ON THIS LINE, out is ServletOutputStream.
       idc.printStackTrace(out);
    }
    //System.out.println("connection made");
}
1
  • Please, next time explain your problem with text, not only code. Also, when you are satisfied with an answer, accept it. Thanks! Commented Apr 21, 2011 at 16:34

3 Answers 3

5

Obviously you can use ServletOutputStream#print but you could use PrintWriter as well.

resp.getWriter().print(yourvariable)
Sign up to request clarification or add additional context in comments.

Comments

4

out is a ServletOutputStream. It has a rich set of overloaded print() methods. Just use

out.print(variable);

Comments

0

ServletOutputStream has a large set of print(...) methods. When printing text, it's better to use them instead of write(...) ones.

Also, note that you can use print or write multiple times:

out.print("Hello, the variable is ");
out.print(variable);
out.println(". Something else?");

Notice that, instead of adding a \n in the end of the string, it's better to use println.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.