Skip to content

iswarya15/servlet-basic

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Java Web Application using Servlets, JSP & Embedded Tomcat

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

Dependencies:

  • Add Tomcat Embedded Core to pom.xml
  • Add jakarta.servlet to pom.xml

Running Tomcat

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

How to set it up

  • Class should extend HttpServlet to use service method 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

Responding to Client

  • res.getWriter returns obj of type PrintWriter

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println("<h2><b>Hello World</b></h2>");
    

About

Built a java web app using JSP and Servlet with embedded Tomcat server.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages