SoFunction
Updated on 2025-03-10

The difference between Servlet and Spring MVC and instructions for use

Preface

In Java Web development, Servlet and Spring MVC are two important technologies. Servlets are the basic component of the Java Web, while Spring MVC is a high-level web framework built on the basis of Servlets and provides powerful features and ease of use.

This article will introduce Servlets and Spring MVC in detail from multiple aspects such as definition, principles, function comparison, application scenarios, etc., and analyze their differences and connections.

1. What is Servlet

1. Definition

Servlet is the core component of Java Web applications. It is a small program running on the server, specially used to process client HTTP requests and generate dynamic responses.

Servlets are part of the Java EE specification and define how to write server-side web applications through Java.

2. Working principle

The core idea of ​​Servlet is based onRequest-response model

  1. The client (usually the browser) sends an HTTP request.
  2. A web container such as Tomcat routes the request to the Servlet.
  3. The servlet processes the request, executes logic, generates and returns an HTTP response.

3. Core Components

  • HttpServletRequest: Represents the client's request object, containing all the requested information (such as request parameters, request header, etc.).
  • HttpServletResponse: Represents the server's response object, including all the information of the response (such as response header, response status code, response body, etc.).

4. Servlet life cycle

The life cycle of a servlet is managed by a web container and consists of the following stages:

  1. initialization
    • When the Servlet is accessed for the first time, the container will load the Servlet class and call itinit()The method completes initialization.
  2. Serve
    • Called every requestservice()Method, call the corresponding HTTP method (GET, POST, etc.) according to the requested HTTP method (GET, POST, etc.).doGet()ordoPost()method.
  3. destroy
    • Called when the server shuts down or uninstalls the Servletdestroy()Method to release resources.

5. Sample code

Here is a simple Servlet example:

@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // Set the response content type        ("text/html");
        // Return a simple HTML response        ().write("<h1>Hello, Servlet!</h1>");
    }
}

2. What is Spring MVC

1. Definition

Spring MVC is a web development module based on the Spring framework and providesMVC(Model-View-Controller)Complete implementation of design patterns.

It simplifies web application development and provides powerful support for request mapping, parameter binding, view resolution and other functions.

2. Core idea

Spring MVC byDispatcherServlet(Front-end controller) intercepts all requests uniformly and distributes them to specific processors (Controllers), and then generates a response in conjunction with the View.

3. Spring MVC architecture

The core components of Spring MVC:

  1. DispatcherServlet
    • Front-end controller, responsible for receiving and distributing all HTTP requests.
  2. HandlerMapping
    • Request a mapper to map the URL to a specific controller method.
  3. Controller
    • The business processor is responsible for executing specific logic.
  4. ModelAndView
    • Data model and view objects, used to encapsulate business data and return view information.
  5. ViewResolver
    • View parser, parsing logical view names into physical views (such as JSP, Thymeleaf pages).
  6. View
    • Responsible for generating the final response content (HTML, JSON, etc.).

4. Workflow

Spring MVC workflow

  1. The client sends the request.
  2. DispatcherServletReceive the request and delegate it toHandlerMappingFind the corresponding Controller method.
  3. The Controller method handles the request and returns data (Model) and view (View).
  4. ViewResolverResolves the logical view name into a physical view.
  5. Render the data to the view, generate a response and return it to the client.

5. Sample code

Here is a simple Spring MVC example:

Controller class:

@Controller
public class HelloController {
    @GetMapping("/hello")
    @ResponseBody
    public String sayHello(@RequestParam String name) {
        return "<h1>Hello, " + name + "!</h1>";
    }
}

3. The difference between Servlet and Spring MVC

Contrast dimensions Servlet Spring MVC
position Basic technologies for Java Web development. Advanced Web Framework built on Servlets.
Design Thoughts Directly based on the HTTP request-response model. Based on MVC (Model-View-Controller) design pattern.
Development complexity Higher, requiring manual resolution of requests and generation of responses. Lower, provides automation functions (such as parameter binding, view resolution).
Feature richness There are fewer functions and need to implement extensions on your own (such as request mapping, data binding). Rich features, built-in request mapping, form verification, exception handling and other functions.
Request Mapping Static URL mapping, directly configure routing through web containers. Flexible dynamic mapping, supporting regular expressions, RESTful URLs, etc.
View support Need to manually splice HTML or JSP pages. Supports multiple view technologies (JSP, Thymeleaf, JSON, etc.).
Form Verification Manual verification of parameters is required. Provide annotated verifications (such as @Valid and @NotNull).
Exception handling The exception needs to be explicitly caught and processed in the code. Provides a global exception handling mechanism (such as @ControllerAdvice).
Extensibility The scalability is limited, and some common functions need to be implemented through Filter or Listener. It provides an interceptor mechanism, supports AOP and dependency injection, and is extremely scalable.
Learning curve It is easy to get started, but it is difficult to develop complex projects. You need to learn the basics of Spring framework, and the learning curve for beginners is slightly steep.
Applicable scenarios Small projects or scenarios where HTTP requests are required to be operated directly. Medium- and large-scale projects, especially scenarios that require high scalability and rapid development.

4. The connection between Servlet and Spring MVC

Although Servlets and Spring MVC differ in positioning and functionality, they are closely related:

1. Built based on Servlet

  • Spring MVC is a high-level framework built on the basis of Servlets.
  • The core components of Spring MVCDispatcherServletEssentially a Servlet that is responsible for receiving and distributing requests.

2. Servlet is the basis of Spring MVC

  • Spring MVC uses Servlets to handle HTTP requests, but blocks complex details such as parameter resolution, request distribution, etc.

3. Spring MVC depends on Servlet container

  • Spring MVC must run in Servlet-enabled web containers (such as Tomcat, Jetty).
  • Servlet containers are responsible for loading and managingDispatcherServlet

5. When to choose Servlet or Spring MVC

1. Use Servlet

  • Suitable for small projects, simple functions.
  • I hope to have a deep understanding of the underlying principles of Java Web.
  • It does not require complex framework support and can manually implement request processing and response.

2. Use Spring MVC

  • Suitable for medium and large projects, with complex functions.
  • Efficient development, flexible configuration and good scaling capabilities are required.
  • Hope to enjoy the Spring framework ecosystem (such as Spring Data, Spring Security, etc.).

Sample code

Suppose we need to build a simple web service:

  • Request path:http://localhost:8080/hello?name=Tom
  • Return to content:Hello, Tom!

Complete Servlet implementation

import ;
import ;
import ;
import ;
import ;
import ;

// Annotate the map path "/hello" using @WebServlet@WebServlet("/hello")
public class HelloServlet extends HttpServlet {

    // Initialize the servlet (execute only once)    @Override
    public void init() throws ServletException {
        ();
        ("Servlet initialization is complete!");
    }

    // Process GET requests    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Set the response content type        ("text/html;charset=UTF-8");

        // Get request parameters        String name = ("name");
        if (name == null || ()) {
            name = "World"; // default value        }

        // Return dynamic response        ().write("&lt;h1&gt;Hello, " + name + "!&lt;/h1&gt;");
    }

    // Destroy Servlet (execute only once, used to free resources)    @Override
    public void destroy() {
        ();
        ("The Servlet has been destroyed!");
    }
}

Code optimization points

  1. Annotation simplified configuration:
    • use@WebServletAnnotations instead of traditionalConfiguration.
  2. Default parameter processing:
    • If the user does not pass the parameter, the default "World" is returned.
  3. Character encoding:
    • pass("text/html;charset=UTF-8")Set character encoding to prevent Chinese garbled code.
  4. Log output:
    • existinit()anddestroy()Add log information to the method for easy debugging.

How to run

  1. Package the code as.warand deploy to Tomcat.
  2. Access URL:http://localhost:8080/hello?name=Tom
  3. Return result:Hello, Tom!

Spring MVC implementation

Spring MVC is more concise and powerful.

The following code implements the same functionality.

Controller class

import ;
import ;
import ;
import ;

@Controller
public class HelloController {

    // Process GET requests, map the path "/hello"    @GetMapping("/hello")
    @ResponseBody
    public String sayHello(@RequestParam(name = "name", required = false, defaultValue = "World") String name) {
        // Return to dynamic content        return "&lt;h1&gt;Hello, " + name + "!&lt;/h1&gt;";
    }
}

Spring Boot Main Class

If you build a project using Spring Boot, you can quickly start it with the following code:

import ;
import ;

@SpringBootApplication
public class SpringMvcApplication {

    public static void main(String[] args) {
        (, args);
    }
}

Code optimization points

  1. Annotation-driven development:
    • use@Controllerand@GetMappingAnnotation processes requests, simplifying configuration.
  2. Automatic parameter binding:
    • use@RequestParamAutomatically extract parameters from the request, and set default values.
  3. Automatic response:
    • pass@ResponseBodyThe returned string is directly used as the response body, eliminating manual processingHttpServletResponse
  4. Spring Boot Quick Start:
    • Use Spring Boot to automate configuration without the need to deploy to Tomcat separately.

How to run

  1. Save the code as a Spring Boot application.
  2. Run the main classSpringMvcApplication
  3. Access URL:http://localhost:8080/hello?name=Tom
  4. Return result:Hello, Tom!

Sample Scenario Extension

In order to better understand the application scenarios of Servlet and Spring MVC, we will expand another function: return JSON data based on user input.

Servlet example (returns JSON data)

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

@WebServlet("/json")
public class JsonServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Set the response type to JSON        ("application/json;charset=UTF-8");

        // Get request parameters        String name = ("name");
        if (name == null || ()) {
            name = "World";
        }

        // Construct response data        Map&lt;String, String&gt; responseData = new HashMap&lt;&gt;();
        ("message", "Hello, " + name + "!");

        // Convert data to JSON        String jsonResponse = new Gson().toJson(responseData);

        // Return JSON response        ().write(jsonResponse);
    }
}

Spring MVC example (returns JSON data)

import ;
import ;
import ;

import ;
import ;

@RestController
public class JsonController {

    @GetMapping("/json")
    public Map&lt;String, String&gt; sayHello(@RequestParam(name = "name", required = false, defaultValue = "World") String name) {
        // Construct response data        Map&lt;String, String&gt; response = new HashMap&lt;&gt;();
        ("message", "Hello, " + name + "!");
        return response;
    }
}

doGet()doPost()andservice()The difference

characteristic service() doGet() doPost()
position Common method for handling all HTTP request types. Specially used to handle HTTP GET requests. Specially used to handle HTTP POST requests.
Call method Called directly by the web container. The call is distributed by the service() method according to the HTTP request method. The call is distributed by the service() method according to the HTTP request method.
Achieve the goal Automatically distribute the request to the corresponding doXxx() method. Process read-only requests (such as querying data). Process data submission (such as form, file upload).
Developer rewrite Rarely rewritten and is usually hosted by web containers. Often rewritten to process GET requests. Often rewritten to process POST requests.
Request Semantics No specific semantics, as a distribution portal. Follows the semantics (idempotent) of HTTP GET requests. Follows the semantics (non-idempotent) of HTTP POST requests.

Summarize

the difference

  • ServletIt is a basic technology of Java Web development, providing the ability to directly operate HTTP requests and responses, suitable for small projects or scenarios where in-depth understanding of the underlying principles are required.
  • Spring MVCIt is a high-level web framework based on Servlets, providing a large number of automation functions and development conveniences, suitable for medium and large projects.

connect

  • Spring MVC is a framework built on Servlet technology, throughDispatcherServletImplement the reception and distribution of requests.
  • Servlets are the foundation of Spring MVC, but Spring MVC encapsulates many underlying details to make development more efficient.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.