”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > Spring MVC 面试问问题

Spring MVC 面试问问题

发布于2024-08-20
浏览:449

1. What is Model 1 architecture?

Model 1 Architecture is an early design pattern for developing web applications. In this architecture, JSP (JavaServer Pages) plays a central role, handling both the presentation and the business logic.

alt text

As you can see in the above figure, there is picture which show the flow of the Model1 architecture.

  1. Browser sends request for the JSP page
  2. JSP accesses Java Bean and invokes business logic
  3. Java Bean connects to the database and get/save data
  4. Response is sent to the browser which is generated by JSP
  • Flow:

    • Client requests are directly sent to JSP pages.
    • JSP pages process the request, interact with the model (data), and generate a response.
  • Characteristics:

    • Simple and straightforward for small applications.
    • JSP pages mix presentation logic (HTML) with business logic (Java code).
    • Limited separation of concerns.
  • Disadvantages:

    • Difficult to maintain and scale.
    • Mixing of presentation and business logic can lead to spaghetti code.

2. What is Model 2 Architecture?

Spring MVC Interview Asked Questions

Model 2 Architecture is an advanced design pattern for developing web applications, commonly known as MVC (Model-View-Controller) architecture. It separates the application logic into three main components: Model, View, and Controller.

  • Flow:

    • Client requests are sent to a controller.
    • The controller processes the request, interacts with the model, and forwards the response to a view.
    • The view renders the response to the client.
  • Components:

    • Model: Represents the application's data and business logic.
    • View: Represents the presentation layer (typically JSP or other templating engines).
    • Controller: Handles user requests and controls the flow of the application.
  • Characteristics:

    • Clear separation of concerns.
    • Easier to maintain and extend.
    • More scalable for larger applications.

3. What is Model 2 Front Controller Architecture?

Model 2 Front Controller Architecture is a refinement of the Model 2 (MVC) architecture where a single controller, known as the Front Controller, handles all incoming requests. This pattern further decouples the request handling logic from the business logic and view rendering.

  • Flow:

    • Client requests are sent to a single front controller.
    • The front controller delegates the request to specific handlers or controllers.
    • These handlers interact with the model and forward the response to the appropriate view.
  • Components:

    • Front Controller: A central controller that handles all incoming requests and routes them to appropriate handlers.
    • Handlers/Controllers: Specific controllers that handle individual requests and business logic.
    • Model: Represents the application's data and business logic.
    • View: Represents the presentation layer (typically JSP or other templating engines).
  • Characteristics:

    • Centralized control of request handling.
    • Simplified configuration and management of application flow.
    • Enhanced security and preprocessing capabilities (e.g., authentication, logging).
    • Easier to implement common functionalities like authentication, logging, and exception handling.

Can you show an example controller method in Spring MVC?

@Controller
public class MyController {

    @RequestMapping("/hello")
    public String sayHello(Model model) {
        model.addAttribute("message", "Hello, World!");
        return "helloView";
    }
}

Summary: The above example demonstrates a simple controller method in Spring MVC that maps a /hello request to the sayHello method. The method adds a message to the model and returns a view name (helloView).


Can you explain a simple flow in Spring MVC?

  1. Client Request: A user sends an HTTP request to a URL mapped to a Spring MVC controller.
  2. DispatcherServlet: The request is received by the DispatcherServlet, the front controller in Spring MVC.
  3. Handler Mapping: The DispatcherServlet consults the HandlerMapping to determine the appropriate controller to handle the request.
  4. Controller: The controller processes the request. In the example above, MyController's sayHello method handles the request.
  5. Model: The controller interacts with the model to retrieve or update data. It adds data to the model to be used in the view.
  6. View Name: The controller returns the view name (e.g., helloView).
  7. ViewResolver: The ViewResolver resolves the logical view name to a physical view (e.g., helloView.jsp).
  8. Render View: The view (e.g., JSP, Thymeleaf) is rendered and returned to the client.

Summary: A Spring MVC request flow starts with a client request and goes through the DispatcherServlet, HandlerMapping, and controller. The controller interacts with the model, returns a view name, and the ViewResolver resolves it to a physical view which is then rendered and returned to the client.


What is a ViewResolver?

A ViewResolver is a component in Spring MVC that resolves view names to actual view files. It maps the logical view name returned by the controller to a specific view implementation (e.g., JSP file, Thymeleaf template).

Example:

@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver resolver = new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    return resolver;
}

Summary: A ViewResolver in Spring MVC maps logical view names to physical view files, enabling the separation of view names in controllers from the actual view files.


What is a Model?

A Model in Spring MVC is an interface that provides a way to pass attributes to the view for rendering. It acts as a container for the data to be displayed in the view.

Example:

@Controller
public class MyController {

    @RequestMapping("/hello")
    public String sayHello(Model model) {
        model.addAttribute("message", "Hello, World!");
        return "helloView";
    }
}

Summary: The Model in Spring MVC is used to pass data from the controller to the view. It allows adding attributes that will be available in the view for rendering.


What is ModelAndView?

ModelAndView is a holder for both the model and the view in Spring MVC. It encapsulates the data (model) and the view name or view object in one object.

Example:

@Controller
public class MyController {

    @RequestMapping("/greeting")
    public ModelAndView greeting() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("greetingView");
        modelAndView.addObject("message", "Hello, Spring MVC!");
        return modelAndView;
    }
}

Summary: ModelAndView in Spring MVC combines both the model data and the view name into one object, simplifying the return type from controllers when both model and view need to be specified.


What is a RequestMapping?

@RequestMapping is an annotation used to map HTTP requests to handler methods of MVC and REST controllers. It can map requests based on URL, HTTP method, request parameters, headers, and media types.

Example:

@Controller
@RequestMapping("/home")
public class HomeController {

    @RequestMapping(value = "/welcome", method = RequestMethod.GET)
    public String welcome(Model model) {
        model.addAttribute("message", "Welcome to Spring MVC!");
        return "welcomeView";
    }
}

Summary: @RequestMapping is an annotation in Spring MVC that maps HTTP requests to specific controller methods based on URL patterns, HTTP methods, and other parameters, allowing precise routing of requests.


Summary of All Concepts with Examples

  • Controller Method:

    • Handles HTTP requests and returns a view name or ModelAndView.
    • Example: @RequestMapping("/hello") public String sayHello(Model model)
  • Flow in Spring MVC:

    • Client request → DispatcherServlet → HandlerMapping → Controller → Model → View name → ViewResolver → Render view → Response to client.
    • Example: MyController's sayHello method.
  • ViewResolver:

    • Maps logical view names to actual view files.
    • Example: InternalResourceViewResolver mapping helloView to helloView.jsp.
  • Model:

    • Passes data from the controller to the view.
    • Example: model.addAttribute("message", "Hello, World!")
  • ModelAndView:

    • Encapsulates both model data and view name.
    • Example: ModelAndView modelAndView = new ModelAndView("greetingView"); modelAndView.addObject("message", "Hello, Spring MVC!");
  • RequestMapping:

    • Maps HTTP requests to controller methods.
    • Example: @RequestMapping(value = "/welcome", method = RequestMethod.GET)

What is Dispatcher Servlet?

The DispatcherServlet is the central dispatcher for HTTP request handlers/controllers in a Spring MVC application. It is responsible for routing incoming web requests to appropriate controller methods, handling the lifecycle of a request, and returning the appropriate response.


How do you set up Dispatcher Servlet?

In a traditional Spring MVC application, you set up the DispatcherServlet in the web.xml configuration file or via Java configuration.

Using web.xml:

dispatcherorg.springframework.web.servlet.DispatcherServletcontextConfigLocation/WEB-INF/spring/dispatcher-config.xml1dispatcher/

Using Java Configuration:

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {

    @Override
    protected Class>[] getRootConfigClasses() {
        return new Class[] { RootConfig.class };
    }

    @Override
    protected Class>[] getServletConfigClasses() {
        return new Class[] { WebConfig.class };
    }

    @Override
    protected String[] getServletMappings() {
        return new String[] { "/" };
    }
}

In this setup, RootConfig and WebConfig are configuration classes annotated with @Configuration.


Do we need to set up Dispatcher Servlet in Spring Boot?

No, in Spring Boot, you do not need to explicitly set up the DispatcherServlet. Spring Boot automatically configures the DispatcherServlet for you. By default, it is mapped to the root URL pattern (/), and Spring Boot will scan your classpath for @Controller and other related annotations.

Spring Boot Application Class:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MySpringBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class, args);
    }
}

In this setup, Spring Boot handles the DispatcherServlet setup internally, allowing you to focus on your application's logic without worrying about the boilerplate configuration.

Summary

  • DispatcherServlet: The core of Spring MVC that routes requests to appropriate handlers.
  • Traditional Setup: Configured via web.xml or Java configuration.
  • Spring Boot: Automatically configured, no explicit setup required.

What is a Form Backing Object?

A form backing object in Spring MVC is a Java object that is used to capture form input data. It acts as a data holder for form fields, facilitating the transfer of form data between the view and the controller. The form backing object is typically a POJO (Plain Old Java Object) with properties that correspond to the form fields.

Example:

public class User {
    private String name;
    private String email;
    // Getters and setters
}

How is Validation Done Using Spring MVC?

Validation in Spring MVC is typically done using JSR-303/JSR-380 (Bean Validation API) annotations and a validator implementation. Spring provides support for validating form backing objects using these annotations and the @Valid or @Validated annotation in controller methods.

Example:

  1. Form Backing Object with validation annotations:

    import javax.validation.constraints.Email;
    import javax.validation.constraints.NotEmpty;
    
    public class User {
        @NotEmpty(message = "Name is required")
        private String name;
    
        @Email(message = "Email should be valid")
        @NotEmpty(message = "Email is required")
        private String email;
    
        // Getters and setters
    }
    
  2. Controller method with @Valid:

    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.PostMapping;
    
    import javax.validation.Valid;
    
    @Controller
    public class UserController {
    
        @GetMapping("/userForm")
        public String showForm(Model model) {
            model.addAttribute("user", new User());
            return "userForm";
        }
    
        @PostMapping("/userForm")
        public String submitForm(@Valid @ModelAttribute("user") User user, BindingResult result) {
            if (result.hasErrors()) {
                return "userForm";
            }
            // Process the form submission
            return "success";
        }
    }
    

What is BindingResult?

BindingResult is an interface provided by Spring that holds the results of the validation and binding of form backing objects. It contains information about validation errors and can be used to determine whether the form submission is valid.

Example:

@PostMapping("/userForm")
public String submitForm(@Valid @ModelAttribute("user") User user, BindingResult result) {
    if (result.hasErrors()) {
        return "userForm";
    }
    // Process the form submission
    return "success";
}

How Do You Map Validation Results to Your View?

Validation results are automatically mapped to the view using the BindingResult object. The view can then access the error messages through the Spring form tags.

Example (JSP):


What are Spring Form Tags?

Spring form tags are a set of JSP tags provided by the Spring Framework to simplify the development of web forms. These tags bind form fields to form backing objects, making it easier to handle form data and validation errors.

Common Spring Form Tags:

  • : Represents the form element.
  • : Displays validation errors.
  • : Creates a checkbox input.
  • : Creates a radio button input.
  • : Creates a hidden input field.

Example:



    

User Form

Summary:

  • Form Backing Object: A Java object that holds form data.
  • Validation in Spring MVC: Done using JSR-303/JSR-380 annotations and the @Valid annotation in controllers.
  • BindingResult: Holds validation and binding results.
  • Mapping Validation Results: Done via the BindingResult object and Spring form tags.
  • Spring Form Tags: JSP tags for simplifying form handling and validation in views.

What is a Path Variable?

A Path Variable in Spring MVC is used to extract values from the URI of a web request. It allows you to capture dynamic values from the URI and use them in your controller methods.

Example:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getUserById(@PathVariable("id") String userId) {
        return "User ID: "   userId;
    }
}

In this example, if a request is made to /user/123, the method getUserById will capture 123 as the userId parameter.


What is a Model Attribute?

A Model Attribute in Spring MVC is used to bind a method parameter or a return value to a named model attribute, which can be accessed in the view. It is typically used to prepare data for rendering in the view.

Example:

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class MyController {

    @RequestMapping(value = "/form", method = RequestMethod.GET)
    public String showForm(Model model) {
        model.addAttribute("user", new User());
        return "userForm";
    }

    @RequestMapping(value = "/form", method = RequestMethod.POST)
    public String submitForm(@ModelAttribute User user) {
        // Process form submission
        return "result";
    }
}

In this example, the User object is added to the model and made available to the view (userForm.jsp). When the form is submitted, the User object is populated with the form data and processed in the submitForm method.


What is a Session Attribute?

A Session Attribute in Spring MVC is used to store model attributes in the HTTP session, allowing them to persist across multiple requests. This is useful for maintaining state between requests.

Example:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@SessionAttributes("user")
public class MyController {

    @RequestMapping(value = "/form", method = RequestMethod.GET)
    public String showForm(Model model) {
        model.addAttribute("user", new User());
        return "userForm";
    }

    @RequestMapping(value = "/form", method = RequestMethod.POST)
    public String submitForm(@ModelAttribute User user) {
        // Process form submission
        return "result";
    }

    @RequestMapping(value = "/clearSession", method = RequestMethod.GET)
    public String clearSession(SessionStatus status) {
        status.setComplete();
        return "sessionCleared";
    }
}

In this example, the User object is stored in the session and can be accessed across multiple requests. The clearSession method can be used to clear the session attributes.

Summary:

  • Path Variable: Extracts values from the URI to use in controller methods.
  • Model Attribute: Binds method parameters or return values to model attributes, making them accessible in views.
  • Session Attribute: Stores model attributes in the HTTP session to maintain state across multiple requests.

What is an Init Binder?

An Init Binder in Spring MVC is a mechanism that allows you to customize the way data is bound to the form backing objects. It is used to initialize WebDataBinder, which performs data binding from web request parameters to JavaBean objects. @InitBinder methods are used to register custom editors, formatters, and validators for specific form fields or types.

Key Uses of Init Binder:

  • Register Custom Property Editors: To convert form field values to specific types.
  • Register Custom Formatters: To format the input/output of date, number, or other complex types.
  • Add Validators: To perform custom validation logic.

Example of Init Binder

Scenario: You have a form that includes a date field and you want to use a specific date format.

Step 1: Define a form backing object

public class User {
    private String name;
    private Date birthDate;

    // Getters and setters
}

Step 2: Define a controller with an @InitBinder method

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class UserController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    @RequestMapping(value = "/form", method = RequestMethod.GET)
    public String showForm(Model model) {
        model.addAttribute("user", new User());
        return "userForm";
    }

    @RequestMapping(value = "/form", method = RequestMethod.POST)
    @ResponseBody
    public String submitForm(@ModelAttribute User user) {
        // Process form submission
        return "Name: "   user.getName()   ", Birth Date: "   user.getBirthDate();
    }
}

Explanation:

  1. Form Backing Object: User class with name and birthDate fields.
  2. Controller:
    • The @InitBinder method initBinder is defined to customize the data binding process.
    • WebDataBinder is used to register a custom editor (CustomDateEditor) for Date class.
    • CustomDateEditor uses a SimpleDateFormat to parse and format dates in the "yyyy-MM-dd" format.
    • The showForm method adds a new User object to the model and returns the view name userForm.
    • The submitForm method processes the form submission and returns a response with the user's name and birth date.

Step 3: Define the form view (JSP example)



    

User Form

Summary:

  • Init Binder: A method annotated with @InitBinder in a Spring MVC controller that customizes data binding.
  • Key Uses:
    • Register custom property editors.
    • Register custom formatters.
    • Add validators.
  • Example:
    • Custom date formatting using CustomDateEditor.
    • Binding form data to a User object with a birthDate field formatted as "yyyy-MM-dd".

This customization allows precise control over how form data is converted and validated before it is bound to the controller's method parameters.


To set a default date format in a Spring application, you typically use an @InitBinder method in your controller to register a custom date editor. This approach allows you to specify the date format that should be used for all date fields in your form backing objects.

Here is a detailed example:

Step-by-Step Guide to Setting a Default Date Format

1. Define the Form Backing Object

Create a simple Java class to represent your form data.

public class User {
    private String name;
    private Date birthDate;

    // Getters and setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthDate() {
        return birthDate;
    }

    public void setBirthDate(Date birthDate) {
        this.birthDate = birthDate;
    }
}

2. Define the Controller

Create a Spring MVC controller with an @InitBinder method to register the custom date editor.

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class UserController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }

    @RequestMapping(value = "/form", method = RequestMethod.GET)
    public String showForm(Model model) {
        model.addAttribute("user", new User());
        return "userForm";
    }

    @RequestMapping(value = "/form", method = RequestMethod.POST)
    public String submitForm(@ModelAttribute User user, Model model) {
        // Process form submission
        model.addAttribute("user", user);
        return "result";
    }
}

3. Define the View (JSP Example)

Create a JSP file for the form (e.g., userForm.jsp).



    

User Form

Create another JSP file to display the result (e.g., result.jsp).


    

Form Submitted

Name: ${user.name}

Birth Date: ${user.birthDate}

Summary

  1. Form Backing Object: Define a class (e.g., User) with a date field.
  2. Controller:
    • Use @InitBinder to register a CustomDateEditor with a specific date format.
    • Handle form display and submission.
  3. Views: Create JSP files for the form and the result display.

This approach ensures that all date fields in your form backing objects use the specified date format ("yyyy-MM-dd" in this example), simplifying date handling and validation in your Spring application.


Exception Handling in Spring MVC

Exception handling in Spring MVC can be done in various ways, from using traditional try-catch blocks to leveraging Spring's @ExceptionHandler and @ControllerAdvice annotations for a more centralized and sophisticated approach.

1. Using @ExceptionHandler in Controllers

You can handle exceptions locally within a controller by using the @ExceptionHandler annotation. This annotation is used to define a method that will handle exceptions thrown by request handling methods in the same controller.

Example:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    public String test() {
        if (true) {
            throw new RuntimeException("Test exception");
        }
        return "test";
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public String handleRuntimeException(RuntimeException ex) {
        return "Handled RuntimeException: "   ex.getMessage();
    }
}

2. Using @ControllerAdvice

For a more global approach to exception handling, you can use @ControllerAdvice. This annotation allows you to define a class that will handle exceptions for all controllers or specific controllers.

Example:

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public String handleRuntimeException(RuntimeException ex) {
        return "Handled by GlobalExceptionHandler: "   ex.getMessage();
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception ex) {
        ModelAndView mav = new ModelAndView("error");
        mav.addObject("message", ex.getMessage());
        return mav;
    }
}

In this example, GlobalExceptionHandler will handle RuntimeException and Exception globally for all controllers in the application.

Summary

  • Local Exception Handling:

    • Use @ExceptionHandler in a controller to handle exceptions thrown by methods in the same controller.
  • Global Exception Handling:

    • Use @ControllerAdvice to create a global exception handler that applies to multiple controllers.
    • @ExceptionHandler methods within @ControllerAdvice can handle specific exceptions or a range of exceptions.

Detailed Example with Controller Advice

Step 1: Create a Controller

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/api")
public class MyApiController {

    @GetMapping("/test")
    @ResponseBody
    public String test() {
        if (true) {
            throw new RuntimeException("Test exception in API");
        }
        return "test";
    }
}

Step 2: Create a Global Exception Handler with @ControllerAdvice

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public String handleRuntimeException(RuntimeException ex) {
        return "Handled by GlobalExceptionHandler: "   ex.getMessage();
    }

    @ExceptionHandler(Exception.class)
    public ModelAndView handleException(Exception ex) {
        ModelAndView mav = new ModelAndView("error");
        mav.addObject("message", ex.getMessage());
        return mav;
    }
}

In this setup:

  • Any RuntimeException thrown by any controller will be handled by the handleRuntimeException method in GlobalExceptionHandler.
  • Any general Exception will be handled by the handleException method, returning a view named error with an error message.

Summary Points

  • Exception Handling in Controllers:

    • @ExceptionHandler methods handle exceptions within the same controller.
  • Global Exception Handling with @ControllerAdvice:

    • Centralized exception handling for all controllers.
    • Can handle specific exceptions and provide common handling logic across the application.
    • Simplifies maintenance by separating exception handling from business logic.
  • Use Cases:

    • Local Handling: For specific exception handling needs within a single controller.
    • Global Handling: For a consistent and reusable exception handling strategy across the entire application.

Why is Spring MVC so popular?

Spring MVC is popular for several reasons:

  • Simplicity: Spring MVC provides a simple approach to creating web applications, with minimal configuration required.

  • Modularity: It allows for a modular approach to design, which makes it easier to maintain and update the code.

  • Integration: Spring MVC can be easily integrated with other popular Java frameworks like Hibernate, JPA, etc.

  • Testability: It provides excellent support for testing, which makes it easier to ensure the quality of the application.

  • Community Support: It has a large and active community, which means that help is readily available.

  • Versatility: It can be used to develop a wide range of applications, from simple web sites to complex enterprise applications.

  • Documentation: It has extensive and detailed documentation, which makes it easier to learn and use.

版本声明 本文转载于:https://dev.to/vampirepapi/spring-mvc-interview-asked-questions-2d15?1如有侵犯,请联系[email protected]删除
最新教程 更多>
  • Polyfills——填充物还是缝隙? (第 1 部分)
    Polyfills——填充物还是缝隙? (第 1 部分)
    几天前,我们在组织的 Teams 聊天中收到一条优先消息,内容如下:发现安全漏洞 - 检测到 Polyfill JavaScript - HIGH。 举个例子,我在一家大型银行公司工作,你必须知道,银行和安全漏洞就像主要的敌人。因此,我们开始深入研究这个问题,并在几个小时内解决了这个问题,我将在下面...
    编程 发布于2024-11-05
  • 移位运算符和按位简写赋值
    移位运算符和按位简写赋值
    1。移位运算符 :向右移动。 >>>:无符号右移(零填充)。 2.移位运算符的一般语法 value > num-bits:将值位向右移动,保留符号位。 value >>> num-bits:通过在左侧插入零将值位向右移动。 3.左移 每次左移都会导致该值的所有位向左移动一位。 右侧插入0位。 效果:...
    编程 发布于2024-11-05
  • 如何使用 VBA 从 Excel 建立与 MySQL 数据库的连接?
    如何使用 VBA 从 Excel 建立与 MySQL 数据库的连接?
    VBA如何在Excel中连接到MySQL数据库?使用VBA连接到MySQL数据库尝试连接使用 VBA 在 Excel 中访问 MySQL 数据库有时可能具有挑战性。在您的情况下,您在尝试建立连接时遇到错误。要使用 VBA 成功连接到 MySQL 数据库,请按照下列步骤操作:Sub ConnectDB...
    编程 发布于2024-11-05
  • 测试自动化:使用 Java 和 TestNG 进行 Selenium 指南
    测试自动化:使用 Java 和 TestNG 进行 Selenium 指南
    测试自动化已成为软件开发过程中不可或缺的一部分,使团队能够提高效率、减少手动错误并以更快的速度交付高质量的产品。 Selenium 是一个用于自动化 Web 浏览器的强大工具,与 Java 的多功能性相结合,为构建可靠且可扩展的自动化测试套件提供了一个强大的框架。使用 Selenium Java 进...
    编程 发布于2024-11-05
  • 我对 DuckDuckGo 登陆页面的看法
    我对 DuckDuckGo 登陆页面的看法
    “你为什么不谷歌一下呢?”是我在对话中得到的常见答案。谷歌的无处不在甚至催生了新的动词“谷歌”。但是我编写的代码越多,我就越质疑我每天使用的数字工具。也许我对谷歌使用我的个人信息的方式不再感到满意。或者我们很多人依赖谷歌进行互联网搜索和其他应用程序,说实话,我厌倦了在搜索某个主题或产品后弹出的广告,...
    编程 发布于2024-11-05
  • 为什么 Turbo C++ 的“cin”只读取第一个字?
    为什么 Turbo C++ 的“cin”只读取第一个字?
    Turbo C 的“cin”限制:仅读取第一个单词在 Turbo C 中,“cin”输入运算符有一个处理字符数组时的限制。具体来说,它只会读取直到遇到空白字符(例如空格或换行符)。尝试读取多字输入时,这可能会导致意外行为。请考虑以下 Turbo C 代码:#include <iostream....
    编程 发布于2024-11-05
  • 使用 Buildpack 创建 Spring Boot 应用程序的 Docker 映像
    使用 Buildpack 创建 Spring Boot 应用程序的 Docker 映像
    介绍 您已经创建了一个 Spring Boot 应用程序。它在您的本地计算机上运行良好,现在您需要将该应用程序部署到其他地方。在某些平台上,您可以直接提交jar文件,它将被部署。在某些地方,您可以启动虚拟机,下载源代码,构建并运行它。但是,大多数时候您需要使用容器来部署应用程序。大...
    编程 发布于2024-11-05
  • 如何保护 PHP 代码免遭未经授权的访问?
    如何保护 PHP 代码免遭未经授权的访问?
    保护 PHP 代码免遭未经授权的访问保护 PHP 软件背后的知识产权对于防止其滥用或盗窃至关重要。为了解决这个问题,可以使用多种方法来混淆和防止未经授权的访问您的代码。一种有效的方法是利用 PHP 加速器。这些工具通过缓存频繁执行的部分来增强代码的性能。第二个好处是,它们使反编译和逆向工程代码变得更...
    编程 发布于2024-11-05
  • React:了解 React 的事件系统
    React:了解 React 的事件系统
    Overview of React's Event System What is a Synthetic Event? Synthetic events are an event-handling mechanism designed by React to ach...
    编程 发布于2024-11-05
  • 为什么在使用 Multipart/Form-Data POST 请求时会收到 301 Moved Permanently 错误?
    为什么在使用 Multipart/Form-Data POST 请求时会收到 301 Moved Permanently 错误?
    Multipart/Form-Data POSTs尝试使用 multipart/form-data POST 数据时,可能会出现类似所提供的错误消息遭遇。理解问题需要检查问题的构成。遇到的错误是 301 Moved Permanently 响应,表明资源已被永久重定向。当未为 multipart/f...
    编程 发布于2024-11-05
  • 如何使用日期和时间对象确定 PHP 中的时间边界?
    如何使用日期和时间对象确定 PHP 中的时间边界?
    确定 PHP 中的时间边界在此编程场景中,我们的任务是确定给定时间是否在预定义的范围内。具体来说,我们得到三个时间字符串:当前时间、日出和日落。我们的目标是确定当前时间是否位于日出和日落的边界时间之间。为了应对这一挑战,我们将使用 DateTime 类。这个类使我们能够表示和操作日期和时间。我们将创...
    编程 发布于2024-11-05
  • 如何使用 CSS 变换比例修复 jQuery 拖动/调整大小问题?
    如何使用 CSS 变换比例修复 jQuery 拖动/调整大小问题?
    jQuery 使用 CSS 变换缩放拖动/调整大小问题: 当应用 CSS 变换时,特别是变换:矩阵(0.5, 0, 0, 0.5, 0, 0);,对于一个 div 并在子元素上使用 jQuery 的draggable() 和 resizing() 插件,jQuery 所做的更改变得与鼠标位置“不同步...
    编程 发布于2024-11-05
  • 如何修复 TensorFlow 中的“ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型浮点)”错误?
    如何修复 TensorFlow 中的“ValueError:无法将 NumPy 数组转换为张量(不支持的对象类型浮点)”错误?
    TensorFlow:解决“ValueError: Failed to Convert NumPy Array to Tensor (Unsupported Object Type Float)”工作时遇到的常见错误TensorFlow 的错误是“ValueError:无法将 NumPy 数组转换为...
    编程 发布于2024-11-05
  • 如何高效判断本地存储项是否存在?
    如何高效判断本地存储项是否存在?
    确定本地存储项目是否存在使用 Web 存储时,在访问或修改特定项目之前验证它们是否存在至关重要。在本例中,我们想要确定 localStorage 中是否设置了特定项目。当前方法检查项目是否存在的当前方法似乎是:if (!(localStorage.getItem("infiniteScro...
    编程 发布于2024-11-05
  • Java 中的原子是什么?了解 Java 中的原子性和线程安全
    Java 中的原子是什么?了解 Java 中的原子性和线程安全
    1. Java 原子简介 1.1 Java 中什么是原子? 在Java中,java.util.concurrent.atomic包提供了一组支持对单个变量进行无锁线程安全编程的类。这些类统称为原子变量。最常用的原子类包括 AtomicInteger 、 Atomic...
    编程 发布于2024-11-05

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3