> Java > java지도 시간 > 본문

Spring MVC 인터뷰 질문

王林
풀어 주다: 2024-07-16 17:15:18
원래의
358명이 탐색했습니다.

1. 모델 1 아키텍처란 무엇입니까?

모델 1 아키텍처는 웹 애플리케이션 개발을 위한 초기 디자인 패턴입니다. 이 아키텍처에서는 JSP(JavaServer Pages)가 프레젠테이션과 비즈니스 로직을 모두 처리하는 중심 역할을 합니다.

alt text

위 그림에서 볼 수 있듯이 Model1 아키텍처의 흐름을 보여주는 사진이 있습니다.

  1. 브라우저가 JSP 페이지에 대한 요청을 보냅니다
  2. JSP는 Java Bean에 액세스하고 비즈니스 로직을 호출합니다
  3. Java Bean이 데이터베이스에 연결하여 데이터를 가져오거나 저장합니다
  4. JSP에서 생성된 브라우저로 응답이 전송됩니다
  • 흐름:

    • 클라이언트 요청은 JSP 페이지로 직접 전송됩니다.
    • JSP 페이지는 요청을 처리하고 모델(데이터)과 상호 작용하며 응답을 생성합니다.
  • 특성:

    • 소규모 애플리케이션에 간단하고 간단합니다.
    • JSP 페이지에는 프레젠테이션 로직(HTML)과 비즈니스 로직(Java 코드)이 혼합되어 있습니다.
    • 제한적인 관심사 분리.
  • 단점:

    • 유지관리 및 확장이 어렵습니다.
    • 프레젠테이션 로직과 비즈니스 로직을 혼합하면 스파게티 코드가 발생할 수 있습니다.

2. 모델 2 아키텍처란 무엇입니까?

Spring MVC Interview Asked Questions

모델 2 아키텍처는 일반적으로 MVC(Model-View-Controller) 아키텍처로 알려진 웹 애플리케이션 개발을 위한 고급 디자인 패턴입니다. 애플리케이션 로직을 모델, 뷰, 컨트롤러의 세 가지 주요 구성요소로 분리합니다.

  • 흐름:

    • 클라이언트 요청은 컨트롤러로 전송됩니다.
    • 컨트롤러는 요청을 처리하고 모델과 상호작용하며 응답을 뷰에 전달합니다.
    • 뷰는 클라이언트에 대한 응답을 렌더링합니다.
  • 구성 요소:

    • 모델: 애플리케이션의 데이터와 비즈니스 로직을 나타냅니다.
    • 보기: 프리젠테이션 계층을 나타냅니다(일반적으로 JSP 또는 기타 템플릿 엔진).
    • 컨트롤러: 사용자 요청을 처리하고 애플리케이션의 흐름을 제어합니다.
  • 특성:

    • 명확한 우려사항 분리
    • 유지관리 및 확장이 더 쉽습니다.
    • 대규모 애플리케이션에 맞게 확장성이 뛰어납니다.

3. Model 2 전면 컨트롤러 아키텍처란 무엇입니까?

Model 2 전면 컨트롤러 아키텍처는 전면 컨트롤러라고 하는 단일 컨트롤러가 들어오는 모든 요청을 처리하는 Model 2(MVC) 아키텍처를 개선한 것입니다. 이 패턴은 비즈니스 로직 및 뷰 렌더링에서 요청 처리 로직을 더욱 분리합니다.

  • 흐름:

    • 클라이언트 요청은 단일 전면 컨트롤러로 전송됩니다.
    • 프런트 컨트롤러는 특정 핸들러나 컨트롤러에게 요청을 위임합니다.
    • 이러한 핸들러는 모델과 상호 작용하고 적절한 뷰에 응답을 전달합니다.
  • 구성 요소:

    • 전면 컨트롤러: 들어오는 모든 요청을 처리하고 이를 적절한 핸들러로 라우팅하는 중앙 컨트롤러입니다.
    • 핸들러/컨트롤러: 개별 요청과 비즈니스 로직을 처리하는 특정 컨트롤러
    • 모델: 애플리케이션의 데이터와 비즈니스 로직을 나타냅니다.
    • 보기: 프리젠테이션 계층을 나타냅니다(일반적으로 JSP 또는 기타 템플릿 엔진).
  • 특성:

    • 요청 처리를 중앙 집중식으로 제어합니다.
    • 신청 흐름 구성 및 관리가 단순화되었습니다.
    • 향상된 보안 및 전처리 기능(예: 인증, 로깅)
    • 인증, 로깅, 예외 처리 등의 일반적인 기능 구현이 더 쉬워졌습니다.

Spring MVC의 컨트롤러 메소드 예시를 보여줄 수 있나요?

@Controller
public class MyController {

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

요약: 위의 예는 /hello 요청을 sayHello 메소드에 매핑하는 Spring MVC의 간단한 컨트롤러 메소드를 보여줍니다. 이 메서드는 모델에 메시지를 추가하고 뷰 이름(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:

<web-app>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
로그인 후 복사

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):

<form:form modelAttribute="user" method="post">
    <form:errors path="*" cssClass="error" />
    <div>
        <form:label path="name">Name:</form:label>
        <form:input path="name" />
        <form:errors path="name" cssClass="error" />
    </div>
    <div>
        <form:label path="email">Email:</form:label>
        <form:input path="email" />
        <form:errors path="email" cssClass="error" />
    </div>
    <input type="submit" value="Submit" />
</form:form>
로그인 후 복사

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.
  • : Creates an input field.
  • : Creates a label for a field.
  • : Displays validation errors.
  • : Creates a select (dropdown) field.
  • : Represents an option in a dropdown field.
  • : Creates a checkbox input.
  • : Creates a radio button input.
  • : Creates a hidden input field.

Example:

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
<body>
    <h2>User Form</h2>
    <form:form modelAttribute="user" method="post">
        <div>
            <form:label path="name">Name:</form:label>
            <form:input path="name" />
            <form:errors path="name" cssClass="error" />
        </div>
        <div>
            <form:label path="email">Email:</form:label>
            <form:input path="email" />
            <form:errors path="email" cssClass="error" />
        </div>
        <input type="submit" value="Submit" />
    </form:form>
</body>
</html>
로그인 후 복사

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)

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
<body>
    <h2>User Form</h2>
    <form:form modelAttribute="user" method="post">
        <div>
            <form:label path="name">Name:</form:label>
            <form:input path="name" />
        </div>
        <div>
            <form:label path="birthDate">Birth Date (yyyy-MM-dd):</form:label>
            <form:input path="birthDate" />
        </div>
        <input type="submit" value="Submit" />
    </form:form>
</body>
</html>
로그인 후 복사
로그인 후 복사

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).

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
<body>
    <h2>User Form</h2>
    <form:form modelAttribute="user" method="post">
        <div>
            <form:label path="name">Name:</form:label>
            <form:input path="name" />
        </div>
        <div>
            <form:label path="birthDate">Birth Date (yyyy-MM-dd):</form:label>
            <form:input path="birthDate" />
        </div>
        <input type="submit" value="Submit" />
    </form:form>
</body>
</html>
로그인 후 복사
로그인 후 복사

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

<html>
<body>
    <h2>Form Submitted</h2>
    <p>Name: ${user.name}</p>
    <p>Birth Date: ${user.birthDate}</p>
</body>
</html>
로그인 후 복사

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:

    • 로컬 처리: 단일 컨트롤러 내에서 특정 예외 처리가 필요한 경우
    • 전역 처리: 전체 애플리케이션에 걸쳐 일관되고 재사용 가능한 예외 처리 전략을 사용합니다.

Spring MVC가 왜 그렇게 인기가 있습니까?

Spring MVC는 여러 가지 이유로 인기가 있습니다.

  • 단순성: Spring MVC는 최소한의 구성만으로 웹 애플리케이션을 생성하는 간단한 접근 방식을 제공합니다.

  • 모듈화: 모듈식 설계 접근 방식을 허용하므로 코드 유지 관리 및 업데이트가 더 쉬워집니다.

  • 통합: Spring MVC는 Hibernate, JPA 등과 같은 다른 인기 있는 Java 프레임워크와 쉽게 통합될 수 있습니다.

  • 테스트 용이성: 테스트에 대한 탁월한 지원을 제공하므로 애플리케이션의 품질을 보다 쉽게 ​​보장할 수 있습니다.

  • 커뮤니티 지원: 규모가 크고 활동적인 커뮤니티가 있어 쉽게 도움을 받을 수 있습니다.

  • 다양성: 간단한 웹 사이트부터 복잡한 기업 애플리케이션까지 다양한 애플리케이션을 개발하는 데 사용할 수 있습니다.

  • 문서: 광범위하고 자세한 문서가 있어 배우고 사용하기가 더 쉽습니다.

위 내용은 Spring MVC 인터뷰 질문의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿