We can build Web Applications in Java using Servlets.
Java Server Pages (View Technology): write Java in HTML content as writing HTML within java gets messy, Servlet -> accept request from the client & do the processing and pass the data to JSP page, JSP -> create the webpage. In same application, we can build Servlet and JSP.
MVC: Model (simple Java class) is the data/object. Controller (Servlet) sends the model to view technology. view (JSP) fetches the data and builds the page and gives it back to the client.
As tomcat server runs in Servlet container, it will understand only Servlet, so behind the scenes JSP gets converted to Servlet
- Add Tomcat Embedded Core to pom.xml
- Add jakarta.servlet to pom.xml
In Spring Boot, embedded Tomcat is auto-configured by the framework, so manual server setup is not required. In a plain Servlet-based project, Tomcat must be configured and started explicitly.
So you must explicitly:
- Create the Tomcat instance
- Define context
- Register servlets
- Map URLs
- Start and keep the server alive
- Class should extend
HttpServletto useservicemethod which is responsible for handling client requests - Tomcat.start() starts the server but to keep it running use await()
Tomcat tomcat = new Tomcat(); tomcat.start(); tomcat.getServer().await(); - If we use external tomcat, on top of Servlet, we use @WebServlet() annotation and request path will call this Servlet
@WebServlet("/hello") - In embedded tomcat, we write all this config in
main.java - To do the mapping of request, add context using
tomcat.addContext()which takes 2 params -- application name (default uses "") & directory structure - To add servlet, use
Tomcat.addServlet()-- context, servlet name, servlet class obj - To map Servlet, do
context.addServletMappingDecoded("/hello", "HelloServlet")-- add requestUrl and servlet name
-
res.getWriterreturns obj of type PrintWriterres.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<h2><b>Hello World</b></h2>");