What is the method for constructing and using the Spring MVC framework?

The methods for setting up and using the Spring MVC framework are as follows:

  1. Add Spring MVC dependency: Add the Spring MVC dependency in the project’s build file, such as pom.xml. For example, for Maven projects, you can add the following dependency:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.9</version>
</dependency>
  1. Setting up Spring MVC involves creating a Spring MVC configuration file (such as servlet-config.xml) and making necessary configurations. This includes setting up view resolver, static resource handler, request mappings, etc. Below is a simple configuration example:
<!-- 配置Spring MVC -->
<mvc:annotation-driven />
<mvc:default-servlet-handler />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>
  1. Create a Controller: Develop one or more @Controller classes to handle client requests. Within the Controller class, define methods to handle different URL requests and use appropriate annotations (such as @RequestMapping) for mapping. For example:
@Controller
@RequestMapping("/example")
public class ExampleController {
    @RequestMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("message", "Hello Spring MVC!");
        return "hello";
    }
}
  1. Create a view: Create the corresponding JSP or HTML file in the views folder to display the processing results. For example, in the above example, you can create a JSP file named “hello.jsp” and display the message in it.
<!DOCTYPE html>
<html>
<head>
    <title>Hello</title>
</head>
<body>
    <h1>${message}</h1>
</body>
</html>
  1. Deploying and running applications: Deploy the application to a web server (such as Tomcat) and start the server. By accessing the URL of the application (such as http://localhost:8080/example/hello), you will be able to see the processing result.

The methods outlined above are the basic ways to build and utilize a Spring MVC framework. Depending on specific needs, you can also use other functionalities and features such as data binding, form validation, interceptors, etc.

bannerAds