3

I have been playing around with java servers and servlets. However one question still remains. Lets say I write a server like this:

class server {
  public static void main(String[] args){
    int port = 8080;
    try{      
      ServerSocket ss = new ServerSocket(port);
      Socket s = ss.accept();
    }catch(Exception e){
      System.out.println("Something went wrong");
    }
  }
}

this will listen for httprequest on port 8080. Now lets say I have a servlet that looks like this:

public class HelloWorld extends HttpServlet {
  public void doGet(HttpServletRequest req, HttpServletResponse res)
                               throws ServletException, IOException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    out.println("<HTML>");
    out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
    out.println("<BODY>");
    out.println("<BIG>Hello World</BIG>");
    out.println("</BODY></HTML>");
  }
}

I can easily use an already existing server like tomcat or glassfish to deploy this servlet. But is it possible to deploy this from the simple server here above?

user966504
  • 63
  • 2

3 Answers3

1

No, you need a Servlet implementation or if you want to re-invent the wheel create your own. For instance Catalina is the Tomcat servlet implementation.

PbxMan
  • 7,525
  • 1
  • 36
  • 40
0

No. You need java implementation that handle servlet's code and return html. Basically glassfish or tomcat is a server which listens to your request, run java code at back end and return result. On superficial level, tomcat and glassfish use basic server to capture requests. However there are a lot more things to do.

In your simple server, there is nothing to handle java code written in servlet.

Your server will return text of servelet instead of running it.

SaurabhJinturkar
  • 554
  • 7
  • 20
0
  1. not a easy way.
  2. servlet need a java container implementation,like tomcat or glassfish。 if you think tomcat or glassfish is too heavy, can try jetty.

    public class HelloHandler extends AbstractHandler
    {
        public void handle(String target,Request baseRequest,
                HttpServletRequest request,HttpServletResponse response) 
                throws IOException, ServletException
        {
            response.setContentType("text/html;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("<h1>Hello World</h1>");
        }
    }
    
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(8080);
        server.setHandler(new HelloHandler());
    
        server.start();
        server.join();
    }
    
  3. you also can write a simple Servlet implementation by netty.

morgano
  • 17,210
  • 10
  • 45
  • 56
jolestar
  • 1,285
  • 15
  • 21