0

I have just started learning servlets: As far as i know, we can create servlet in 3 ways:

  1. By writing a class that extends HttpServlet
  2. By writing a class that extends GenericServlet
  3. By directly implementing Servlet interface (is this correct?)

I was trying the 3rd method: but in this, i don't know how to print to a web page. In 1st two examples we used to call print on response object which was obtained by getWriter() method.

So can i print something on a webpage when i use method 3 to create a servlet?

4

1 回答 1

1

看起来您在 service() 方法中以相同的方式执行此操作。这对我有用:

package com.example.ServletInterface.servlets;

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

@WebServlet("/MyServlet")
public class MyServlet implements Servlet{
    ServletConfig config = null;

    public void init(ServletConfig config) {
        this.config = config;
    }

    public void service(ServletRequest req, ServletResponse resp)
                    throws IOException, ServletException {

        resp.setContentType("text/html");
        PrintWriter out = resp.getWriter(); //<***********LOOK AT ME********

        out.print("<html>");
        out.print("<head><title>Test</title>");
        out.print("<body><div>hello world</div></body>");
        out.print("</html>");

    }

    public void destroy() {
        System.out.println("Servlet is destroyed");
    }

    public ServletConfig getServletConfig() {
        return config;
    }

    public String getServletInfo() {
        return "MyServlet";
    }
}

按照这个例子: http ://www.javatpoint.com/Servlet-interface

于 2013-06-14T04:50:04.887 回答