The basic steps to create a SpringMVC project

  1. Create an empty Maven project as the parent project, delete src
  2. Add related dependencies for this parent project

spring,servlet,jsp,jstl…

<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
  1. Prevent Maven static resource export problems
<build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
  1. Create a new blank Maven subproject
  2. Right click and select add framework support

image-20210227182715934

  1. Choose web application

image-20210227182801084

In this way, a web project was successfully created

image-20210227212219071

  1. Configure web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!--注册servlet-->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
        <!-- 启动顺序,数字越小,启动越早 -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!--所有请求都会被Spring拦截-->
    <servlet-mapping>
        <servlet-name>SpringMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


</web-app>

The difference between / and /*: <url-pattern> / </ url-pattern> will not match the .jsp, only for the requests we write; that is, the .jsp will not enter the Spring DispatcherServlet class. <url-pattern> /* </ url-pattern> will match *.jsp, and the DispatcherServlet class of spring will appear again when returning to the jsp view, causing the corresponding controller not to be found, so a 404 error is reported.

    • Pay attention to the issue of web.xml version, ask for the latest version!
    • Register DispatcherServlet
    • Associated SpringMVC configuration file
    • Startup level is 1
    • The mapping path is / [Do not use /*, it will 404]

8. Add springMVC configuration file

Add the springmvc-servlet.xml configuration file under resources. The configuration form is similar to the basic configuration of the Spring container. In order to support the annotation-based IOC, the automatic scanning package function is set. The specific configuration information is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc
       https://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
    <context:component-scan base-package="top.faroz.controller"/>
    <!-- 让Spring MVC不处理静态资源 -->
    <mvc:default-servlet-handler />
    <!--
    支持mvc注解驱动
        在spring中一般采用@RequestMapping注解来完成映射关系
        要想使@RequestMapping注解生效
        必须向上下文中注册DefaultAnnotationHandlerMapping
        和一个AnnotationMethodHandlerAdapter实例
        这两个实例分别在类级别和方法级别处理。
        而annotation-driven配置帮助我们自动完成上述两个实例的注入。
     -->
    <mvc:annotation-driven />

    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!-- 后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>
</beans>
  1. In the view resolver, we store all the views in the /WEB-INF/ directory , which can ensure the security of the view, because the files in this directory cannot be directly accessed by the client .

    • Let the IOC comments take effect
    • Static resource filtering: HTML. JS. CSS. Pictures, videos...
    • Annotation-driven MVC
    • Configure view resolver

9. Create the controller

Write a java control class

@Controller
@RequestMapping("/HelloController")
public class HelloController {
    
    

    //真实访问地址 : 项目名/HelloController/hello
    @RequestMapping("/hello")
    public String sayHello(Model model) {
    
    
        //向模型中添加属性msg与值,可以在JSP页面中取出并渲染
        model.addAttribute("msg","hello,SpringMVC");
        //web-inf/jsp/hello.jsp
        return "hello";
    }
}
  • @Controller is to allow the Spring IOC container to be automatically scanned when it is initialized;
  • @RequestMapping is to map the request path, here because there are mappings on the class and method, it should be /HelloController/hello when accessed;
  • The method declares the parameters of the Model type to bring the data in the Action to the view;
  • Results hello method returns the name of the view, together with the prefix and suffix profile-INF into the WEB / JSP / hello .jsp. Previously, the following paragraph in springmvc-servlet.xml was used for this:image-20210227214423343
  1. Create the view layer

  2. Create hello.jsp in the WEB-INF/jsp directory, the view can directly retrieve and display the information brought back from the Controller;

  3. The value or object stored in the Model can be retrieved through EL representation;

  4. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
       <title>SpringMVC</title>
    </head>
    <body>
    ${msg}
    </body>
    </html>
    
  5. Configure Tomcat

  6. To run, enter the URL http://localhost:8080/HelloController/hello

Found that the result is 404

image-20210227215831809

Here must pay attention to a guide package problem

  1. Guide package problem

image-20210227220123220

Add lib

image-20210227220230257

Select all here, then click OK

image-20210227220306324

At this time, we restarted the project and found that it was OK

image-20210227220410119

Guess you like

Origin blog.csdn.net/weixin_44062380/article/details/114195145