-1

I'm learning servlets and I want to create two different endpoints in a single servlet. I mean, I want to have /hello and /test each one of them should execute or refer to different class as shown below.

In other words, I want to be able to acceess to:

http://localhost:8080/HelloServlet/hello
and
http://localhost:8080/HelloServlet/Test

So that the corresponding or the respective class must be invoked and display the respective contents

HelloWorld example:

@WebServlet(name = "HelloServlet", urlPatterns = {"/sayHello", "/hello", "/helloWorld"})
public class HelloWorld extends HttpServlet{

    private String responseContentType = null;
    
    public HelloWorld() {
        super();
    }
    
    public void init() throws ServletException {
        responseContentType = "text/html;charset=UTF-8";
    }
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
                   throws IOException, ServletException {
          // Set the response message's MIME type
          response.setContentType(responseContentType);
          // Allocate a output writer to write the response message into the network socket
          PrintWriter out = response.getWriter();
     
          // Write the response message, in an HTML page
          try {
             out.println("<!DOCTYPE html>");
             out.println("<html><head>");
             out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
             out.println("<title>Hello, World</title></head>");
             out.println("<body>");
             out.println("<h1>Hello, world!</h1>");  // says Hello
             // Echo client's request information
             out.println("<p>Request URI: " + request.getRequestURI() + "</p>");
             out.println("<p>Protocol: " + request.getProtocol() + "</p>");
             out.println("<p>PathInfo: " + request.getPathInfo() + "</p>");
             out.println("<p>Remote Address: " + request.getRemoteAddr() + "</p>");
             // Generate a random number upon each request
             out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");
             out.println("</body>");
             out.println("</html>");
          } finally {
             out.close();  // Always close the output writer
          }
       }
}

Test example:

@WebServlet(name = "HelloServlet", urlPatterns = {"/test"})
public class Test extends HttpServlet{
    
private String responseContentType = null;
    
    public Test() {
        super();
    }
    
    public void init() throws ServletException {
        responseContentType = "text/html;charset=UTF-8";
    }
    
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
   // Set the response message's MIME type
   response.setContentType(responseContentType);
   // Allocate a output writer to write the response message into the network socket
   PrintWriter out = response.getWriter();

   // Write the response message, in an HTML page
   try {
      out.println("<!DOCTYPE html>");
      out.println("<html><head>");
      out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
      out.println("<title>Hello, World</title></head>");
      out.println("<body>");
      out.println("<h1>TEST</h1>");  // says Hello
      // Echo client's request information

      // Generate a random number upon each request
      out.println("<p>A Random Number: <strong>" + Math.random() + "</strong></p>");
      out.println("</body>");
      out.println("</html>");
   } finally {
      out.close();  // Always close the output writer
   }
}
}

web.xml:

    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>HelloServlet</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
      <servlet-name>HelloServlet</servlet-name>
      <servlet-class>com.examples.HelloWorld</servlet-class>
      <servlet-class>com.examples.Test</servlet-class>
   </servlet>
   
 <servlet-mapping>
      <servlet-name>HelloServlet</servlet-name>
      <url-pattern>/sayHello</url-pattern>
      <url-pattern>/hello</url-pattern>
      <url-pattern>/helloWorld</url-pattern>
   </servlet-mapping>
   
 <servlet-mapping>
      <servlet-name>HelloServlet</servlet-name>
      <url-pattern>/test</url-pattern>
   </servlet-mapping>

</webapp>
Amrmsmb
  • 1
  • 27
  • 104
  • 226

1 Answers1

0

If you really want to create two DIFFERENT endpoints inside the same class, for whatever strange reason, here's 2 solutions I can think of:

  1. Try implementing an inner class with the @WebServlet annotation. I don't know if that gets picked up and installed, but worth a try
  2. Have two classes, but let the second class (with the second address) call into the first class. This is what I often do (static) when I have a task that is needed by multiple pages.

I myself once wrote a library that resolved Annotations to addresses, and I thought "ahh I'm better than that stupid JEE stuff... I will allow single methods to be anotated too". Which was not difficult to implement at all. BUT: I regret doing that, because the software that used that got really clumsy and strange, with one file being the possible root of multiple endpoints... So when I re-designed that library, I removed that function and now only allow endpoint annotations on class level. Projects sticking to this are just SO MUCH cleaner and easier to maintain.

Well... so those two options are out there for JEE. But the most important questio is: WHY would you want what you are asking for? This seems like an XY question: https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem.

JayC667
  • 2,418
  • 2
  • 17
  • 31