javaservletsintellij-ideajava-server

how to load servlet from main method


I have Main class, there I doing api request and integrate with database. I also create servlet where I want to get data from clients and put it in database. it is the main method in Main class:

public static void main(String[] args) throws IOException {

    serverSocket = new ServerSocket(8888); // Server port
    System.out.println("Server started. Listening to the port 8888");

    initProviderList();
    initNewsAppDB();

    Thread newFeedsUpdate = new Thread(new NewFeedsUpdate(providerList));
    newFeedsUpdate.start();
}

it is the servlet:

  @WebServlet(name = "GetClientTokenServlet")
public class GetClientTokenServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String token = request.getParameter("token");
        System.out.println(token);
    }

web.xml:

    <?xml version="1.0" encoding="UTF-8"?>
<web-app
        xmlns="http://xmlns.jcp.org/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
        version="4.0">

    <servlet>
        <servlet-name>GetClientTokenServlet</servlet-name>
        <servlet-class>GetClientTokenServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>GetClientTokenServlet</servlet-name>
        <url-pattern>/GetClientTokenServlet</url-pattern>
    </servlet-mapping>
</web-app>

how I can setup the GetClientTokenServlet (to be able listen to clients calls) into main method?


Solution

  • In most cases web applications in Java don't have main methods. The main method is implemented by a servlet container, such as Tomcat, and that's what you actually run. The servlet container discovers your application's classes and web.xml through some method, often by finding them in a WAR file that you have dropped in a directory defined by the servlet container, such as Tomcat's webapps directory. The servlet container then instantiates the servlets identified in your web.xml file.

    That said, there are some web servers that you can instantiate as components within your own application. A server that is commonly used for this purpose is Jetty. Jetty is a web server that passes incoming requests to "handlers" that you define. You can have Jetty load your entire web application from your WAR file and instantiate the servlets defined in your web.xml, or you can use ServletHandler to register servlets manually; in this case you don't need web.xml.