Introduction to Java Servlets
Web server contains a servlet container (Tomcat)
Servlet container (Tomcat) contains Servlet (Your implementation of HttpServlet that processes HTTP methods)
HTTP methods include POST, GET, DELETE, PUT
Here is what we wish to achieve using Java Servlets:
- Make a custom servlet that processes HTTP methods at certain url
More familarly, we want to make sure that if we send a GET request to localhost:8080/hello endpoint, we get something in response.
Here are things we need to do:
1. Create servlet that defines HTTP methods
2. map servlet to url endpoint
Create servlet that defines HTTP methods
Here's what servlet looks like:
You can override any HTTP methods from HttpServlet.
Now, there's a file called web.xml. I won't really go into the details here, but if you initialised the project to be a web app, you will have it in the directory shown here:
This is all you need to add to map the servlet to /hello endpoint:
That's it! If you run this with Tomcat, and access http://localhost:10000/example-03/hello on the browser (which sends GET request to that endpoint)
You can make a little bit more extension by adding more parameters:
And if you map it to /basicMultiply, for example, then if you access this url from browser:
http://localhost:10000/example-03/basicMultiply?num1=200&num2=300
This is what gets returned as a result.