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.
As you can see in the above figure, there is picture which show the flow of the Model1 architecture.
Flow:
Characteristics:
Disadvantages:
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:
Components:
Characteristics:
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:
Components:
Characteristics:
@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).
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.
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.
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.
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.
@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.
Controller Method:
Flow in Spring MVC:
ViewResolver:
Model:
ModelAndView:
RequestMapping:
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.
In a traditional Spring MVC application, you set up the DispatcherServlet in the web.xml configuration file or via Java configuration.
Using web.xml:
dispatcher org.springframework.web.servlet.DispatcherServlet contextConfigLocation /WEB-INF/spring/dispatcher-config.xml 1 dispatcher /
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.
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.
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 }
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:
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 }
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"; } }
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"; }
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):
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:
Example:
User Form
Summary:
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.
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.
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:
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.
Scenario: You have a form that includes a date field and you want to use a specific date format.
public class User { private String name; private Date birthDate; // Getters and setters }
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(); } }
User Form
Summary:
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:
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; } }
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"; } }
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}
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 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.
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(); } }
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.
Local Exception Handling:
Global Exception Handling:
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"; } }
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:
Exception Handling in Controllers:
Global Exception Handling with @ControllerAdvice:
Use Cases:
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.
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3