Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run java servlet?

I have a servlet. I'm new in java. But i need to run the servlet. It has two methods:

public void doGet (HttpServletRequest request,
                     HttpServletResponse response) {...}

and

public void doPost HttpServletRequest request,
                     HttpServletResponse response) {...}

What steps i need to do to run the servlet? (I have tomcat 7 installed, eclipse SE with tomcat plugin, netBeans)

like image 323
Dmytro Plekhotkin Avatar asked Sep 26 '12 07:09

Dmytro Plekhotkin


2 Answers

  1. Create a dynamic web project
  2. Create a new class extending HttpServlet and override the method doGet and doPost, write your business logic in there
  3. Configure web.xml, something like :

      <servlet>
        <servlet-name>helloworld</servlet-name>
        <servlet-class>test.helloworld</servlet-class>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>helloworld</servlet-name>
        <url-pattern>/helloworld</url-pattern>
      </servlet-mapping>
    
  4. Deploy your web project in the tomcat

  5. Type localhost:8080/mywebapp/helloworld.do in the browser's address bar, mywebapp is your project name

If you are lucky, you will see the result.

like image 59
Foredoomed Avatar answered Oct 23 '22 06:10

Foredoomed


Internally call to doGet and doPost will reach like below,

Client ----------------------------> Container  
sends request               |
                            |
                Creates    HttpServletRequest   HttpServletResponse objects 
                            |
                            |                   
                Create Thread for that Servlet and pass above objects to it
                            |
                            |
                Thread Call the Service() method and decision is made to call doGet() or doPost()
                            |
                            |
                    doGet()/doPost() called
like image 38
Jayesh Avatar answered Oct 23 '22 06:10

Jayesh