打卡4:Spring MVC基礎之第一個項目搭建

一. 簡述

  • MVC:Model(數據模型)+ View(視圖)+ Controller(控制器)

    Model:包含數據的對象。用來和View進行數據交互和傳值;
    View:試圖頁面,包括JSP、Thymeleaf等;
    Controller:使用@Controller註解對應的類。

  • 三層架構:Presentation tier(展示層)+ Application tier(應用層)+ Data tier(數據訪問層)

    三層架構是這個應用的架構,由Spring負責管理,一般項目結構中都有Service層和DAO層,他們反饋在應用層和數據訪問層。

二. 快速搭建Spring MVC項目

  1. pom.xml配置

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.3.0.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
        <groupId>com.muzi</groupId>
        <artifactId>springboot01</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <name>springboot01</name>
        <description>Demo project for Spring Boot</description>
    
        <properties>
            <java.version>1.8</java.version>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    
            <!-- web -->
            <jsp.version>2.2</jsp.version>
            <jstl.version>1.2</jstl.version>
            <servlet.version>3.1.0</servlet.version>
    
            <!-- spring -->
            <spring-framework.version>4.1.5.RELEASE</spring-framework.version>
    
            <!-- logging-->
            <logback.version>1.0.13</logback.version>
            <slf4j.version>1.7.5</slf4j.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>javax</groupId>
                <artifactId>javaee-web-api</artifactId>
                <version>7.0</version>
                <scope>provided</scope>
            </dependency>
    
            <!--- spring mvc -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-webmvc</artifactId>
                <version>${spring-framework.version}</version>
            </dependency>
    
            <!-- 其他依賴 -->
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>jstl</artifactId>
                <version>${jstl.version}</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>javax.servlet-api</artifactId>
                <version>${servlet.version}</version>
                <scope>provided</scope>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>jsp-api</artifactId>
                <version>${jsp.version}</version>
                <scope>provided</scope>
            </dependency>
    
            <!-- spring and taransactions -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-tx</artifactId>
                <version>${spring-framework.version}</version>
            </dependency>
    
            <!-- 使用SLF4J和LogBack作爲日誌 -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-api</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
            <dependency>
                <groupId>log4j</groupId>
                <artifactId>log4j</artifactId>
                <version>1.2.17</version>
            </dependency>
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>jcl-over-slf4j</artifactId>
                <version>${slf4j.version}</version>
            </dependency>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-classic</artifactId>
                <version>${logback.version}</version>
            </dependency>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-core</artifactId>
                <version>${logback.version}</version>
            </dependency>
            <dependency>
                <groupId>ch.qos.logback</groupId>
                <artifactId>logback-access</artifactId>
                <version>${logback.version}</version>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>2.3.2</version>
                    <configuration>
                        <source>${java.version}</source>
                        <target>${java.version}</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>2.3</version>
                    <configuration>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    
    </project>
    
  2. 日誌配置
    在src/main/resources目錄下新建logbook.xml來配置日誌。

    <?xml version="1.0" encoding="UTF-8"?>
    <configuration scan="true" scanPeriod = "1 second">
        <contextListener class = "ch.qos.logback.classic.jul.LevelChangePropagator">
            <resetJUL>true</resetJUL>
        </contextListener>
    
        <jmxConfigurator/>
            <appender name ="console" class = "ch.qos.logback.core.ConsoleAppender">
                <encoder>
                    <pattern>logback: %d{HH:mm:ss.SSS} %logger{36} - %msg%n</pattern>
                </encoder>
            </appender>
            <logger name="org.springframework.web" level="DEBUG"/>
        <root level="info">
            <appender-ref ref="console"/>
        </root>
    
    </configuration>
    
  3. 演示界面
    在src/main/resources目錄下新建views目錄,在views目錄下新建index.jsp

    <%@ page language="java" contentType="text/html;  charset = UTF-8" pageEncoding="UTF-8" %>
    <! DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dad">
    <html>
    <head>
        <meta http-equiv="Content-Type" content="txt/html; charset =UTF-8">
        <title>Insert title here</title>
    </head>
    <body>
        <pre>
            Welcome to Spring MVC world
        </pre>
    </body>
    </html>
    
  4. Spring MVC配置

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.ComponentScan;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.EnableWebMvc;
    import org.springframework.web.servlet.view.InternalResourceViewResolver;
    import org.springframework.web.servlet.view.JstlView;
    
    @Configuration
    @ComponentScan("com.muzi.springboot01.mvc")
    @EnableWebMvc
    public class MyMvcConfig {
        @Bean
        public InternalResourceViewResolver viewResolver() {
            InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
            viewResolver.setPrefix("/WEB-INF/classes/views/");
            viewResolver.setSuffix(".jsp");
            viewResolver.setViewClass(JstlView.class);
            return viewResolver;
        }
    }
    
  5. Web配置

    import org.springframework.web.WebApplicationInitializer;
    import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
    import org.springframework.web.servlet.DispatcherServlet;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRegistration;
    
    public class WebInitializer implements WebApplicationInitializer {
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            //新建WebApplicationContext,註冊配置類,將其和當前servletContext關聯
            AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
            ctx.register(MyMvcConfig.class);
            ctx.setServletContext(servletContext);
    
            //註冊Spring MVC的DispatcherServlet
            ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
            servlet.addMapping("/");
            servlet.setLoadOnStartup(1);
        }
    }
    
  6. 簡單控制器

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    @Controller
    public class HelloController {
    
    
        @RequestMapping("/index")
        public String hello() {
            return "index";
        }
    }
    
  7. 運行
    將程序部署到Tomcat中,啓動Tomcat,訪問:http://localhost:8080/index
    在這裏插入圖片描述
    在這裏插入圖片描述
    在這裏插入圖片描述
    在這裏插入圖片描述
    在這裏插入圖片描述
    在這裏插入圖片描述

  8. 運行結果
    在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章